@tempad-dev/mcp 0.7.1 → 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/README.md +42 -5
- package/README.zh-Hans.md +36 -4
- package/dist/cli.mjs +11 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/hub.mjs +3067 -711
- package/dist/hub.mjs.map +1 -1
- package/dist/shared--YD93aQ6.mjs +2491 -0
- package/dist/shared--YD93aQ6.mjs.map +1 -0
- package/package.json +14 -11
- package/dist/shared-Df79xZoB.mjs +0 -120
- package/dist/shared-Df79xZoB.mjs.map +0 -1
package/dist/hub.mjs
CHANGED
|
@@ -1,532 +1,1777 @@
|
|
|
1
|
-
import { c as
|
|
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 {
|
|
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
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
-
ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
|
|
36
|
-
TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
|
|
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
|
+
}
|
|
37
29
|
};
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
const TOOL_RESULT_OUTCOME_ERROR = "Tool results must contain exactly one defined payload or error.";
|
|
43
|
-
function hasToolResultOutcome(result) {
|
|
44
|
-
return result.payload !== void 0 !== (result.error !== void 0);
|
|
45
|
-
}
|
|
46
|
-
const TEMPAD_MCP_BROWSER_SOURCE = "tempad-dev:mcp";
|
|
47
|
-
const MCP_MAX_ASSET_BASE64_LENGTH = 4 * Math.ceil(MCP_MAX_ASSET_BYTES / 3);
|
|
48
|
-
const MessageBaseSchema = z.object({
|
|
49
|
-
source: z.literal(TEMPAD_MCP_BROWSER_SOURCE),
|
|
50
|
-
version: z.literal(1)
|
|
51
|
-
}).strict();
|
|
52
|
-
const PageMessageBaseSchema = MessageBaseSchema.extend({ sessionId: z.string().min(1) }).strict();
|
|
53
|
-
function messageSchema(base, type, shape) {
|
|
54
|
-
return base.extend({
|
|
55
|
-
type: z.literal(type),
|
|
56
|
-
...shape
|
|
57
|
-
}).strict();
|
|
58
|
-
}
|
|
59
|
-
const AssetMetadataSchema = z.object({
|
|
60
|
-
height: z.number().int().positive().optional(),
|
|
61
|
-
themeable: z.boolean().optional(),
|
|
62
|
-
width: z.number().int().positive().optional()
|
|
63
|
-
}).strict();
|
|
64
|
-
const AssetUploadPayloadSchema = z.object({
|
|
65
|
-
base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
|
|
66
|
-
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
67
|
-
metadata: AssetMetadataSchema.optional(),
|
|
68
|
-
mimeType: z.string().min(1)
|
|
69
|
-
}).strict();
|
|
70
|
-
const PageEnableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.enable", {});
|
|
71
|
-
const PageDisableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.disable", {});
|
|
72
|
-
const PageActivateSessionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.activateSession", {});
|
|
73
|
-
const PageToolResultMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.toolResult", {
|
|
74
|
-
callId: z.string().min(1),
|
|
75
|
-
error: TempadMcpErrorPayloadSchema.optional(),
|
|
76
|
-
payload: z.unknown().optional()
|
|
77
|
-
});
|
|
78
|
-
const PageAssetUploadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.uploadAsset", {
|
|
79
|
-
payload: AssetUploadPayloadSchema,
|
|
80
|
-
requestId: z.string().min(1)
|
|
81
|
-
});
|
|
82
|
-
z.discriminatedUnion("type", [
|
|
83
|
-
PageEnableMessageSchema,
|
|
84
|
-
PageDisableMessageSchema,
|
|
85
|
-
PageActivateSessionMessageSchema,
|
|
86
|
-
PageToolResultMessageSchema,
|
|
87
|
-
PageAssetUploadMessageSchema
|
|
88
|
-
]).refine((message) => {
|
|
89
|
-
return message.type !== "mcp.toolResult" || hasToolResultOutcome(message);
|
|
90
|
-
}, { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
91
|
-
const McpBrowserStateStatusSchema = z.enum([
|
|
92
|
-
"disabled",
|
|
93
|
-
"connecting",
|
|
94
|
-
"connected",
|
|
95
|
-
"error"
|
|
96
|
-
]);
|
|
97
|
-
const BridgeStateMessageSchema = messageSchema(MessageBaseSchema, "mcp.state", { payload: z.object({
|
|
98
|
-
activeSessionId: z.string().nullable(),
|
|
99
|
-
assetServerUrl: z.string().nullable().optional(),
|
|
100
|
-
errorMessage: z.string().nullable(),
|
|
101
|
-
sessionCount: z.number().nonnegative(),
|
|
102
|
-
sessionId: z.string(),
|
|
103
|
-
status: McpBrowserStateStatusSchema
|
|
104
|
-
}).strict() });
|
|
105
|
-
const BridgeToolCallMessageSchema = messageSchema(MessageBaseSchema, "mcp.toolCall", {
|
|
106
|
-
callId: z.string().min(1),
|
|
107
|
-
payload: z.object({
|
|
108
|
-
args: z.unknown().optional(),
|
|
109
|
-
name: z.string()
|
|
110
|
-
}).strict()
|
|
111
|
-
});
|
|
112
|
-
const BridgeAssetUploadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetUploadResult", {
|
|
113
|
-
error: TempadMcpErrorPayloadSchema.optional(),
|
|
114
|
-
requestId: z.string().min(1),
|
|
115
|
-
sessionId: z.string().min(1)
|
|
116
|
-
});
|
|
117
|
-
z.discriminatedUnion("type", [
|
|
118
|
-
BridgeStateMessageSchema,
|
|
119
|
-
BridgeToolCallMessageSchema,
|
|
120
|
-
BridgeAssetUploadResultMessageSchema
|
|
121
|
-
]);
|
|
122
|
-
const SERVER_NAME = "tempad-dev";
|
|
123
|
-
const SERVER_COMMAND = "npx";
|
|
124
|
-
const SERVER_ARGS = ["-y", "@tempad-dev/mcp@latest"];
|
|
125
|
-
const REPOSITORY = "ecomfe/tempad-dev";
|
|
126
|
-
const MARKETPLACE_NAME = "tempad-dev";
|
|
127
|
-
const PLUGIN_NAME = "tempad-dev";
|
|
128
|
-
const SKILL_URL = "https://github.com/ecomfe/tempad-dev/tree/main/skill";
|
|
129
|
-
const SKILL_INSTALL_COMMAND = `npx skills add ${SKILL_URL}`;
|
|
130
|
-
const stdioConfig = {
|
|
131
|
-
type: "stdio",
|
|
132
|
-
command: SERVER_COMMAND,
|
|
133
|
-
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
|
+
}
|
|
134
34
|
};
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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();
|
|
226
|
+
}
|
|
138
227
|
};
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
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();
|
|
326
|
+
}
|
|
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"
|
|
339
|
+
},
|
|
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));
|
|
372
|
+
}
|
|
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();
|
|
385
|
+
}
|
|
386
|
+
};
|
|
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);
|
|
439
|
+
return {
|
|
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: [{
|
|
639
|
+
type: "text",
|
|
640
|
+
text,
|
|
641
|
+
text_elements: []
|
|
642
|
+
}],
|
|
643
|
+
restoreMessage: {
|
|
644
|
+
text,
|
|
645
|
+
context: {}
|
|
646
|
+
},
|
|
647
|
+
additionalContext: { "tempad-design-task": {
|
|
648
|
+
kind: "untrusted",
|
|
649
|
+
value: `Design task: ${JSON.stringify(taskId)}`
|
|
650
|
+
} }
|
|
651
|
+
};
|
|
652
|
+
}
|
|
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
|
|
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
|
+
}
|
|
919
|
+
}
|
|
920
|
+
/** Fence receipts first, then remove only this task's native queue entries. */
|
|
921
|
+
async cancelQueued(taskId) {
|
|
922
|
+
this.cancelledTasks.add(taskId);
|
|
923
|
+
const pendingConversation = this.taskConversations.get(taskId);
|
|
924
|
+
if (pendingConversation) await this.queues.get(pendingConversation)?.catch(() => {});
|
|
925
|
+
const queues = /* @__PURE__ */ new Map();
|
|
926
|
+
for (const { receipt } of await this.queueReceipts()) if (receipt.taskId === taskId) queues.set(JSON.stringify([receipt.conversationId, receipt.backend ?? "legacy"]), receipt);
|
|
927
|
+
for (const { conversationId, backend = "legacy" } of queues.values()) await this.schedule(conversationId, async () => {
|
|
928
|
+
const receipts = (await this.queueReceipts()).filter(({ receipt }) => receipt.taskId === taskId && receipt.conversationId === conversationId && (receipt.backend ?? "legacy") === backend && receipt.messageId);
|
|
929
|
+
if (!receipts.length) return;
|
|
930
|
+
const ids = new Set(receipts.map(({ receipt }) => receipt.messageId));
|
|
931
|
+
for (const { path, receipt } of receipts) if (receipt.status !== "removed") await this.saveReceipt(path, {
|
|
932
|
+
...receipt,
|
|
933
|
+
status: "cancelled"
|
|
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
|
+
}
|
|
953
|
+
});
|
|
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()
|
|
1352
|
+
});
|
|
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 {};
|
|
259
1406
|
}
|
|
260
1407
|
};
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
id: "skill-cli",
|
|
296
|
-
label: "Agent skill",
|
|
297
|
-
kind: "command",
|
|
298
|
-
value: buildSkillInstallCommand("cursor")
|
|
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");
|
|
299
1442
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
}]
|
|
316
|
-
},
|
|
317
|
-
gemini: {
|
|
318
|
-
id: "gemini",
|
|
319
|
-
name: "Gemini",
|
|
320
|
-
actions: [{
|
|
321
|
-
id: "mcp-cli",
|
|
322
|
-
label: "MCP CLI",
|
|
323
|
-
kind: "command",
|
|
324
|
-
value: buildCliCommand("gemini")
|
|
325
|
-
}, {
|
|
326
|
-
id: "skill-cli",
|
|
327
|
-
label: "Agent skill",
|
|
328
|
-
kind: "command",
|
|
329
|
-
value: `gemini skills install ${SKILL_URL}`
|
|
330
|
-
}]
|
|
331
|
-
},
|
|
332
|
-
vscode: {
|
|
333
|
-
id: "vscode",
|
|
334
|
-
name: "VS Code",
|
|
335
|
-
actions: [
|
|
336
|
-
{
|
|
337
|
-
id: "mcp-deep-link",
|
|
338
|
-
label: "MCP install",
|
|
339
|
-
kind: "deep-link",
|
|
340
|
-
value: MCP_CLIENTS_BY_ID.vscode.deepLink ?? ""
|
|
341
|
-
},
|
|
342
|
-
{
|
|
343
|
-
id: "mcp-cli",
|
|
344
|
-
label: "MCP CLI",
|
|
345
|
-
kind: "command",
|
|
346
|
-
value: buildCliCommand("vscode")
|
|
347
|
-
},
|
|
348
|
-
{
|
|
349
|
-
id: "skill-cli",
|
|
350
|
-
label: "Agent skill",
|
|
351
|
-
kind: "command",
|
|
352
|
-
value: buildSkillInstallCommand("github-copilot")
|
|
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 } : {}
|
|
353
1458
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
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
|
+
}
|
|
386
1751
|
}
|
|
387
1752
|
};
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
}).strict();
|
|
402
|
-
const ToolCallMessageSchema = z.object({
|
|
403
|
-
type: z.literal("toolCall"),
|
|
404
|
-
id: z.string().min(1),
|
|
405
|
-
payload: ToolCallPayloadSchema
|
|
406
|
-
}).strict();
|
|
407
|
-
z.discriminatedUnion("type", [
|
|
408
|
-
RegisteredMessageSchema,
|
|
409
|
-
StateMessageSchema,
|
|
410
|
-
ToolCallMessageSchema
|
|
411
|
-
]);
|
|
412
|
-
const ActivateMessageSchema = z.object({ type: z.literal("activate") }).strict();
|
|
413
|
-
const ToolResultMessageSchema = z.object({
|
|
414
|
-
type: z.literal("toolResult"),
|
|
415
|
-
id: z.string().min(1),
|
|
416
|
-
payload: z.unknown().optional(),
|
|
417
|
-
error: TempadMcpErrorPayloadSchema.optional()
|
|
418
|
-
}).strict().refine(hasToolResultOutcome, { message: TOOL_RESULT_OUTCOME_ERROR });
|
|
419
|
-
const PingMessageSchema = z.object({ type: z.literal("ping") }).strict();
|
|
420
|
-
const MessageFromExtensionSchema = z.union([
|
|
421
|
-
ActivateMessageSchema,
|
|
422
|
-
ToolResultMessageSchema,
|
|
423
|
-
PingMessageSchema
|
|
424
|
-
]);
|
|
425
|
-
const ENCODER = new TextEncoder();
|
|
426
|
-
function utf8Bytes(value) {
|
|
427
|
-
return ENCODER.encode(serializeUtf8Value(value)).length;
|
|
428
|
-
}
|
|
429
|
-
function measureCallToolResultBytes(result) {
|
|
430
|
-
return utf8Bytes(result);
|
|
431
|
-
}
|
|
432
|
-
function buildGetCodeToolResult(payload) {
|
|
433
|
-
const summary = [];
|
|
434
|
-
const codeSize = utf8Bytes(payload.code);
|
|
435
|
-
summary.push(`Generated \`${payload.lang}\` snippet (${formatBytes(codeSize)}).`);
|
|
436
|
-
if (payload.warnings?.length) summary.push(...payload.warnings.map((warning) => warning.message));
|
|
437
|
-
summary.push(payload.assets?.length ? `Assets attached: ${payload.assets.length}. Download bytes from each asset.url.` : "No binary assets were attached to this response.");
|
|
438
|
-
const tokenCount = payload.tokens ? Object.keys(payload.tokens).length : 0;
|
|
439
|
-
if (tokenCount) summary.push(`Token references included: ${tokenCount}.`);
|
|
440
|
-
summary.push("Read structuredContent for the full code string and metadata.");
|
|
441
|
-
return buildTextToolResult(summary.join("\n"), payload);
|
|
442
|
-
}
|
|
443
|
-
function buildGetStructureToolResult(payload) {
|
|
444
|
-
const roots = payload.roots.length;
|
|
445
|
-
const nodeCount = countOutlineNodes(payload.roots);
|
|
446
|
-
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);
|
|
447
|
-
}
|
|
448
|
-
function buildGetTokenDefsToolResult(payload) {
|
|
449
|
-
const count = Object.keys(payload).length;
|
|
450
|
-
return buildTextToolResult(`${count === 0 ? "No token definitions were resolved." : `Resolved ${formatCount(count, "token definition")}.`}\nRead structuredContent for token values and aliases.`, payload);
|
|
451
|
-
}
|
|
452
|
-
function buildGetScreenshotToolResult(payload) {
|
|
453
|
-
return buildTextToolResult(`${describeScreenshot(payload)} - Download: ${payload.asset.url}`, payload);
|
|
454
|
-
}
|
|
455
|
-
function buildGetAssetsToolResult(payload) {
|
|
456
|
-
const summary = [];
|
|
457
|
-
summary.push(payload.assets.length ? `Resolved ${formatCount(payload.assets.length, "asset")}.` : "No assets were resolved for the requested hashes.");
|
|
458
|
-
if (payload.missing.length) summary.push(`Missing: ${payload.missing.join(", ")}`);
|
|
459
|
-
summary.push("Download bytes from each asset.url.");
|
|
460
|
-
return buildTextToolResult(summary.join("\n"), payload);
|
|
461
|
-
}
|
|
462
|
-
function buildTextToolResult(text, structuredContent) {
|
|
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.");
|
|
463
1766
|
return {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
}],
|
|
468
|
-
structuredContent
|
|
1767
|
+
bytes,
|
|
1768
|
+
hash: createHash("sha256").update(bytes).digest("hex"),
|
|
1769
|
+
mimeType
|
|
469
1770
|
};
|
|
470
1771
|
}
|
|
471
|
-
function serializeUtf8Value(value) {
|
|
472
|
-
if (typeof value === "string") return value;
|
|
473
|
-
return JSON.stringify(value, null, 0) ?? "undefined";
|
|
474
|
-
}
|
|
475
|
-
function countOutlineNodes(nodes) {
|
|
476
|
-
let count = 0;
|
|
477
|
-
const stack = [...nodes];
|
|
478
|
-
while (stack.length) {
|
|
479
|
-
const current = stack.pop();
|
|
480
|
-
if (!current) continue;
|
|
481
|
-
count += 1;
|
|
482
|
-
if (current.children?.length) stack.push(...current.children);
|
|
483
|
-
}
|
|
484
|
-
return count;
|
|
485
|
-
}
|
|
486
|
-
function formatBytes(bytes) {
|
|
487
|
-
if (bytes < 1024) return `${bytes} B`;
|
|
488
|
-
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
489
|
-
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
490
|
-
}
|
|
491
|
-
function formatCount(count, singular) {
|
|
492
|
-
return `${count} ${count === 1 ? singular : `${singular}s`}`;
|
|
493
|
-
}
|
|
494
|
-
function describeScreenshot(result) {
|
|
495
|
-
return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes(result.bytes)})`;
|
|
496
|
-
}
|
|
497
|
-
const AssetDescriptorSchema = z.object({
|
|
498
|
-
hash: z.string().regex(MCP_HASH_PATTERN),
|
|
499
|
-
url: z.string().url(),
|
|
500
|
-
mimeType: z.string().min(1),
|
|
501
|
-
size: z.number().int().nonnegative(),
|
|
502
|
-
width: z.number().int().positive().optional(),
|
|
503
|
-
height: z.number().int().positive().optional(),
|
|
504
|
-
themeable: z.boolean().optional()
|
|
505
|
-
});
|
|
506
|
-
const GetCodeParametersSchema = z.object({
|
|
507
|
-
nodeId: z.string().describe("Optional target node id; omit to use the current single selection when pulling the baseline snapshot.").optional(),
|
|
508
|
-
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(),
|
|
509
|
-
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(),
|
|
510
|
-
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()
|
|
511
|
-
});
|
|
512
|
-
const GetTokenDefsParametersSchema = z.object({
|
|
513
|
-
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."),
|
|
514
|
-
includeAllModes: z.boolean().describe("Include all token modes (light/dark/etc.) instead of just the active one to mirror responsive tokens; default false.").optional()
|
|
515
|
-
});
|
|
516
|
-
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() });
|
|
517
|
-
const GetStructureParametersSchema = z.object({
|
|
518
|
-
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(),
|
|
519
|
-
options: z.object({ depth: z.number().int().positive().describe("Limit traversal depth; defaults to full tree (subject to safety caps).").optional() }).optional()
|
|
520
|
-
});
|
|
521
|
-
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.") });
|
|
522
|
-
const GetAssetsResultSchema = z.object({
|
|
523
|
-
assets: z.array(AssetDescriptorSchema),
|
|
524
|
-
missing: z.array(z.string().regex(MCP_HASH_PATTERN))
|
|
525
|
-
});
|
|
526
1772
|
//#endregion
|
|
527
1773
|
//#region src/asset-utils.ts
|
|
528
|
-
const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{8})(?:\\.[a-z0-9]+)
|
|
529
|
-
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]+)?$`);
|
|
530
1775
|
const SAFE_IMAGE_EXTENSION_PATTERN = /^[a-z0-9-]+$/;
|
|
531
1776
|
function normalizeMimeType(mimeType) {
|
|
532
1777
|
if (!mimeType) return "application/octet-stream";
|
|
@@ -536,8 +1781,7 @@ function normalizeMimeType(mimeType) {
|
|
|
536
1781
|
function getImageExtension(mimeType) {
|
|
537
1782
|
const normalized = normalizeMimeType(mimeType);
|
|
538
1783
|
if (!normalized.startsWith("image/")) return "";
|
|
539
|
-
|
|
540
|
-
if (override) return `.${override}`;
|
|
1784
|
+
if (normalized === "image/jpeg") return ".jpg";
|
|
541
1785
|
const subtype = normalized.slice(6);
|
|
542
1786
|
if (!subtype) return "";
|
|
543
1787
|
const ext = subtype.split("+", 1)[0] || subtype;
|
|
@@ -562,8 +1806,8 @@ function parseNonNegativeInt(envValue, fallback) {
|
|
|
562
1806
|
const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
|
|
563
1807
|
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
564
1808
|
}
|
|
565
|
-
function resolveToolTimeoutMs() {
|
|
566
|
-
return parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT,
|
|
1809
|
+
function resolveToolTimeoutMs(specializedValue, fallback = MCP_TOOL_TIMEOUT_MS) {
|
|
1810
|
+
return parsePositiveInt(specializedValue, parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, fallback));
|
|
567
1811
|
}
|
|
568
1812
|
function resolveAutoActivateGraceMs() {
|
|
569
1813
|
return parsePositiveInt(process.env.TEMPAD_MCP_AUTO_ACTIVATE_GRACE, MCP_AUTO_ACTIVATE_GRACE_MS);
|
|
@@ -587,6 +1831,8 @@ function getMcpServerConfig() {
|
|
|
587
1831
|
return {
|
|
588
1832
|
wsPortCandidates: [...MCP_PORT_CANDIDATES],
|
|
589
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),
|
|
590
1836
|
maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
|
|
591
1837
|
autoActivateGraceMs: resolveAutoActivateGraceMs(),
|
|
592
1838
|
maxAssetSizeBytes: resolveMaxAssetSizeBytes(),
|
|
@@ -641,7 +1887,6 @@ function isChromeExtensionOrigin(origin) {
|
|
|
641
1887
|
//#endregion
|
|
642
1888
|
//#region src/asset-http-server.ts
|
|
643
1889
|
const LOOPBACK_HOST = "127.0.0.1";
|
|
644
|
-
const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
|
|
645
1890
|
const ASSET_REQUEST_TIMEOUT_MS = 15e3;
|
|
646
1891
|
const ASSET_HEADERS_TIMEOUT_MS = 5e3;
|
|
647
1892
|
const ASSET_KEEP_ALIVE_TIMEOUT_MS = 5e3;
|
|
@@ -651,6 +1896,7 @@ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
|
|
|
651
1896
|
function createAssetHttpServer(store, options = {}) {
|
|
652
1897
|
const config = getMcpServerConfig();
|
|
653
1898
|
const accessToken = options.accessToken ?? createCapabilityToken();
|
|
1899
|
+
const legacyAccessToken = createCapabilityToken();
|
|
654
1900
|
const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
|
|
655
1901
|
const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
|
|
656
1902
|
const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
|
|
@@ -691,9 +1937,9 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
691
1937
|
server.close();
|
|
692
1938
|
port = null;
|
|
693
1939
|
}
|
|
694
|
-
function getBaseUrl() {
|
|
1940
|
+
function getBaseUrl(legacy = false) {
|
|
695
1941
|
if (port === null) throw new Error("Asset HTTP server is not running.");
|
|
696
|
-
return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
|
|
1942
|
+
return `http://${LOOPBACK_HOST}:${port}/${legacy ? legacyAccessToken : accessToken}`;
|
|
697
1943
|
}
|
|
698
1944
|
function handleRequest(req, res) {
|
|
699
1945
|
const startedAt = Date.now();
|
|
@@ -710,7 +1956,8 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
710
1956
|
return;
|
|
711
1957
|
}
|
|
712
1958
|
const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
|
|
713
|
-
|
|
1959
|
+
const legacy = secretsEqual(segments[0] ?? "", legacyAccessToken);
|
|
1960
|
+
if (segments.length !== 3 || !legacy && !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
|
|
714
1961
|
sendError(res, 404, "Not Found");
|
|
715
1962
|
return;
|
|
716
1963
|
}
|
|
@@ -737,6 +1984,10 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
737
1984
|
return;
|
|
738
1985
|
}
|
|
739
1986
|
if (req.method === "POST") {
|
|
1987
|
+
if (!legacy && hash.length !== 64) {
|
|
1988
|
+
sendError(res, 400, "Legacy Asset Hashes Are Read-Only");
|
|
1989
|
+
return;
|
|
1990
|
+
}
|
|
740
1991
|
handleUpload(req, res, hash);
|
|
741
1992
|
return;
|
|
742
1993
|
}
|
|
@@ -807,11 +2058,6 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
807
2058
|
stream.pipe(res);
|
|
808
2059
|
}
|
|
809
2060
|
function handleUpload(req, res, hash) {
|
|
810
|
-
if (!HASH_HEX_PATTERN.test(hash)) {
|
|
811
|
-
req.resume();
|
|
812
|
-
sendError(res, 400, "Invalid Hash");
|
|
813
|
-
return;
|
|
814
|
-
}
|
|
815
2061
|
const declaredSize = parseContentLength(req);
|
|
816
2062
|
if (declaredSize === "invalid") {
|
|
817
2063
|
req.resume();
|
|
@@ -834,7 +2080,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
834
2080
|
if (themeable) metadata.themeable = true;
|
|
835
2081
|
const assetMetadata = Object.keys(metadata).length ? metadata : void 0;
|
|
836
2082
|
const existing = store.get(hash);
|
|
837
|
-
if (existing) {
|
|
2083
|
+
if (existing && hash.length === 64) {
|
|
838
2084
|
let existingPath = existing.filePath;
|
|
839
2085
|
if (!existsSync(existingPath) && existsSync(filePath)) {
|
|
840
2086
|
existing.filePath = filePath;
|
|
@@ -916,7 +2162,8 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
916
2162
|
}
|
|
917
2163
|
return;
|
|
918
2164
|
}
|
|
919
|
-
|
|
2165
|
+
const computedHash = hasher.digest("hex");
|
|
2166
|
+
if (computedHash.slice(0, hash.length) !== hash) {
|
|
920
2167
|
cleanup();
|
|
921
2168
|
sendError(res, 400, "Hash Mismatch");
|
|
922
2169
|
return;
|
|
@@ -927,6 +2174,27 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
927
2174
|
return;
|
|
928
2175
|
}
|
|
929
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
|
+
}
|
|
930
2198
|
renameSync(tmpPath, filePath);
|
|
931
2199
|
} catch (error) {
|
|
932
2200
|
log.error({
|
|
@@ -959,7 +2227,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
959
2227
|
if (!requestUrl) return requestUrl;
|
|
960
2228
|
try {
|
|
961
2229
|
const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
|
|
962
|
-
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>";
|
|
963
2231
|
return `/${segments.join("/")}`;
|
|
964
2232
|
} catch {
|
|
965
2233
|
return "<invalid>";
|
|
@@ -1088,76 +2356,570 @@ function createAssetStore(options = {}) {
|
|
|
1088
2356
|
error
|
|
1089
2357
|
}, "Failed to remove asset file on delete.");
|
|
1090
2358
|
}
|
|
1091
|
-
}
|
|
1092
|
-
function reconcile() {
|
|
1093
|
-
let changed = false;
|
|
1094
|
-
for (const [hash, record] of records) if (!existsSync(record.filePath)) {
|
|
1095
|
-
records.delete(hash);
|
|
1096
|
-
changed = true;
|
|
2359
|
+
}
|
|
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
|
+
});
|
|
2838
|
+
}
|
|
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);
|
|
2867
|
+
}
|
|
2868
|
+
if (saved.reviewClosed) {
|
|
2869
|
+
this.closeReview(saved.taskId);
|
|
2870
|
+
return;
|
|
1097
2871
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
for (const file of files) {
|
|
1102
|
-
if (file === INDEX_FILENAME) continue;
|
|
1103
|
-
if (file.includes(".tmp.")) {
|
|
1104
|
-
try {
|
|
1105
|
-
const filePath = join(ASSET_DIR, file);
|
|
1106
|
-
if (now - statSync(filePath).mtimeMs > 3600 * 1e3) {
|
|
1107
|
-
rmSync(filePath, { force: true });
|
|
1108
|
-
log.info({ file }, "Cleaned up stale temp file.");
|
|
1109
|
-
}
|
|
1110
|
-
} catch (e) {
|
|
1111
|
-
log.debug({
|
|
1112
|
-
error: e,
|
|
1113
|
-
file
|
|
1114
|
-
}, "Failed to cleanup stale temp file.");
|
|
1115
|
-
}
|
|
1116
|
-
continue;
|
|
1117
|
-
}
|
|
1118
|
-
const hash = getHashFromAssetFilename(file);
|
|
1119
|
-
if (!hash) continue;
|
|
1120
|
-
if (!records.has(hash)) {
|
|
1121
|
-
const filePath = join(ASSET_DIR, file);
|
|
1122
|
-
try {
|
|
1123
|
-
const stat = statSync(filePath);
|
|
1124
|
-
records.set(hash, {
|
|
1125
|
-
hash,
|
|
1126
|
-
filePath,
|
|
1127
|
-
mimeType: "application/octet-stream",
|
|
1128
|
-
size: stat.size,
|
|
1129
|
-
uploadedAt: stat.birthtimeMs,
|
|
1130
|
-
lastAccess: stat.atimeMs
|
|
1131
|
-
});
|
|
1132
|
-
changed = true;
|
|
1133
|
-
log.info({ hash }, "Recovered orphan asset file.");
|
|
1134
|
-
} catch (e) {
|
|
1135
|
-
log.warn({
|
|
1136
|
-
error: e,
|
|
1137
|
-
file
|
|
1138
|
-
}, "Failed to stat orphan file.");
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
} catch (error) {
|
|
1143
|
-
log.warn({ error }, "Failed to scan asset directory for orphans.");
|
|
2872
|
+
if (saved.status === "cancelled") {
|
|
2873
|
+
this.stop(saved.taskId, "cancelled");
|
|
2874
|
+
return;
|
|
1144
2875
|
}
|
|
1145
|
-
if (
|
|
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);
|
|
1146
2896
|
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
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
|
+
};
|
|
1161
2923
|
//#endregion
|
|
1162
2924
|
//#region src/extension-registry.ts
|
|
1163
2925
|
var ExtensionRegistry = class {
|
|
@@ -1236,15 +2998,22 @@ function attachExtensionSocket(ws, options) {
|
|
|
1236
2998
|
const extension = {
|
|
1237
2999
|
id: options.createId(),
|
|
1238
3000
|
origin: options.origin.toLowerCase(),
|
|
3001
|
+
connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3002
|
+
legacy: ws.protocol !== TEMPAD_MCP_BRIDGE_SUBPROTOCOL,
|
|
1239
3003
|
ws
|
|
1240
3004
|
};
|
|
1241
3005
|
options.registry.add(extension);
|
|
1242
3006
|
options.onConnected?.(extension.id);
|
|
1243
3007
|
const registered = {
|
|
1244
3008
|
id: extension.id,
|
|
3009
|
+
protocolVersion: 13,
|
|
3010
|
+
supportedProtocolVersions: [...TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS],
|
|
1245
3011
|
type: "registered"
|
|
1246
3012
|
};
|
|
1247
|
-
ws.send(JSON.stringify(
|
|
3013
|
+
ws.send(JSON.stringify(extension.legacy ? {
|
|
3014
|
+
type: "registered",
|
|
3015
|
+
id: extension.id
|
|
3016
|
+
} : registered));
|
|
1248
3017
|
options.onStateChange();
|
|
1249
3018
|
scheduleAutoActivation(options);
|
|
1250
3019
|
ws.on("message", (raw, isBinary) => {
|
|
@@ -1266,7 +3035,7 @@ function attachExtensionSocket(ws, options) {
|
|
|
1266
3035
|
});
|
|
1267
3036
|
return;
|
|
1268
3037
|
}
|
|
1269
|
-
const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
|
|
3038
|
+
const parseResult = (extension.legacy ? LegacyMessageFromExtensionSchema : MessageFromExtensionSchema).safeParse(parsedJson);
|
|
1270
3039
|
if (!parseResult.success) {
|
|
1271
3040
|
options.onProtocolWarning?.({
|
|
1272
3041
|
error: parseResult.error.flatten(),
|
|
@@ -1277,6 +3046,13 @@ function attachExtensionSocket(ws, options) {
|
|
|
1277
3046
|
}
|
|
1278
3047
|
const message = parseResult.data;
|
|
1279
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;
|
|
1280
3056
|
case "activate":
|
|
1281
3057
|
if (options.registry.activate(extension.id)) {
|
|
1282
3058
|
options.onActivated?.(extension.id);
|
|
@@ -1291,6 +3067,21 @@ function attachExtensionSocket(ws, options) {
|
|
|
1291
3067
|
if (message.error !== void 0) options.onToolError(message.id, extension.id, message.error);
|
|
1292
3068
|
else options.onToolResult(message.id, extension.id, message.payload);
|
|
1293
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;
|
|
1294
3085
|
case "ping": break;
|
|
1295
3086
|
}
|
|
1296
3087
|
});
|
|
@@ -1320,7 +3111,7 @@ function rawDataToBuffer(raw) {
|
|
|
1320
3111
|
}
|
|
1321
3112
|
//#endregion
|
|
1322
3113
|
//#region src/instructions.md?raw
|
|
1323
|
-
var instructions_default = "You are connected to
|
|
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";
|
|
1324
3115
|
//#endregion
|
|
1325
3116
|
//#region src/request.ts
|
|
1326
3117
|
const pendingCalls = /* @__PURE__ */ new Map();
|
|
@@ -1329,11 +3120,19 @@ function createToolError(code, message) {
|
|
|
1329
3120
|
err.code = code;
|
|
1330
3121
|
return err;
|
|
1331
3122
|
}
|
|
1332
|
-
function register(extensionId, timeout) {
|
|
3123
|
+
function register(extensionId, timeout, options = {}) {
|
|
1333
3124
|
const requestId = nanoid();
|
|
1334
3125
|
return {
|
|
1335
3126
|
promise: new Promise((resolve, reject) => {
|
|
1336
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
|
+
}
|
|
1337
3136
|
pendingCalls.delete(requestId);
|
|
1338
3137
|
reject(createToolError(TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT, `Extension did not respond within ${timeout / 1e3}s.`));
|
|
1339
3138
|
}, timeout);
|
|
@@ -1347,39 +3146,34 @@ function register(extensionId, timeout) {
|
|
|
1347
3146
|
requestId
|
|
1348
3147
|
};
|
|
1349
3148
|
}
|
|
1350
|
-
function
|
|
3149
|
+
function pendingResponse(requestId, extensionId, outcome) {
|
|
1351
3150
|
const call = pendingCalls.get(requestId);
|
|
1352
|
-
if (call) {
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
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);
|
|
1366
3171
|
}
|
|
1367
3172
|
function reject(requestId, extensionId, error) {
|
|
1368
|
-
const call =
|
|
1369
|
-
if (call)
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
reqId: requestId,
|
|
1373
|
-
expectedExtId: call.extensionId,
|
|
1374
|
-
receivedExtId: extensionId
|
|
1375
|
-
}, "Ignored tool error from the wrong extension.");
|
|
1376
|
-
return;
|
|
1377
|
-
}
|
|
1378
|
-
const { timer, reject: fail } = call;
|
|
1379
|
-
clearTimeout(timer);
|
|
1380
|
-
fail(error);
|
|
1381
|
-
pendingCalls.delete(requestId);
|
|
1382
|
-
} 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);
|
|
1383
3177
|
}
|
|
1384
3178
|
function cleanupForExtension(extensionId) {
|
|
1385
3179
|
for (const [reqId, call] of pendingCalls.entries()) {
|
|
@@ -1405,7 +3199,81 @@ function cleanupAll() {
|
|
|
1405
3199
|
pendingCalls.clear();
|
|
1406
3200
|
}
|
|
1407
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
|
|
1408
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
|
+
};
|
|
1409
3277
|
const CONNECTIVITY_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1410
3278
|
TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION,
|
|
1411
3279
|
TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT,
|
|
@@ -1417,14 +3285,14 @@ const SELECTION_ERROR_CODES = /* @__PURE__ */ new Set([TEMPAD_MCP_ERROR_CODES.IN
|
|
|
1417
3285
|
const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
|
|
1418
3286
|
const CONNECTIVITY_TROUBLESHOOTING_LINES = [
|
|
1419
3287
|
"Troubleshooting:",
|
|
1420
|
-
"- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration.",
|
|
1421
|
-
"- If multiple Figma tabs are open, click the
|
|
1422
|
-
"-
|
|
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."
|
|
1423
3291
|
];
|
|
1424
3292
|
const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
return
|
|
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.";
|
|
3294
|
+
function isRecord(value) {
|
|
3295
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
1428
3296
|
}
|
|
1429
3297
|
function extTool(definition) {
|
|
1430
3298
|
return definition;
|
|
@@ -1433,16 +3301,83 @@ function hubTool(definition) {
|
|
|
1433
3301
|
return definition;
|
|
1434
3302
|
}
|
|
1435
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
|
+
}),
|
|
1436
3353
|
extTool({
|
|
1437
3354
|
name: "get_code",
|
|
1438
|
-
description: "
|
|
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,
|
|
1439
3357
|
parameters: GetCodeParametersSchema,
|
|
1440
3358
|
target: "extension",
|
|
1441
3359
|
format: createCodeToolResponse
|
|
1442
3360
|
}),
|
|
3361
|
+
extTool({
|
|
3362
|
+
name: "get_design_system",
|
|
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,
|
|
3365
|
+
parameters: GetDesignSystemParametersSchema,
|
|
3366
|
+
target: "extension",
|
|
3367
|
+
format: createDesignSystemToolResponse
|
|
3368
|
+
}),
|
|
3369
|
+
extTool({
|
|
3370
|
+
name: "apply_canvas",
|
|
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,
|
|
3373
|
+
parameters: ApplyCanvasParametersSchema,
|
|
3374
|
+
target: "extension",
|
|
3375
|
+
format: createApplyCanvasToolResponse
|
|
3376
|
+
}),
|
|
1443
3377
|
extTool({
|
|
1444
3378
|
name: "get_token_defs",
|
|
1445
3379
|
description: "Resolve canonical token names to literal values (optionally including all modes) for tokens referenced by get_code.",
|
|
3380
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
1446
3381
|
parameters: GetTokenDefsParametersSchema,
|
|
1447
3382
|
target: "extension",
|
|
1448
3383
|
format: createTokenDefsToolResponse,
|
|
@@ -1450,22 +3385,33 @@ const TOOL_DEFS = [
|
|
|
1450
3385
|
}),
|
|
1451
3386
|
extTool({
|
|
1452
3387
|
name: "get_screenshot",
|
|
1453
|
-
description: "Capture
|
|
3388
|
+
description: "Capture one bounded rendered PNG asset for an exact node or the current single selection.",
|
|
3389
|
+
annotations: READ_ONLY_ANNOTATIONS,
|
|
1454
3390
|
parameters: GetScreenshotParametersSchema,
|
|
1455
3391
|
target: "extension",
|
|
1456
|
-
format: createScreenshotToolResponse
|
|
1457
|
-
exposed: false
|
|
3392
|
+
format: createScreenshotToolResponse
|
|
1458
3393
|
}),
|
|
1459
3394
|
extTool({
|
|
1460
3395
|
name: "get_structure",
|
|
1461
|
-
description: "
|
|
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,
|
|
1462
3398
|
parameters: GetStructureParametersSchema,
|
|
1463
3399
|
target: "extension",
|
|
1464
3400
|
format: createStructureToolResponse
|
|
1465
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
|
+
}),
|
|
1466
3411
|
hubTool({
|
|
1467
3412
|
name: "get_assets",
|
|
1468
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,
|
|
1469
3415
|
parameters: GetAssetsParametersSchema,
|
|
1470
3416
|
target: "hub",
|
|
1471
3417
|
outputSchema: GetAssetsResultSchema,
|
|
@@ -1473,9 +3419,9 @@ const TOOL_DEFS = [
|
|
|
1473
3419
|
})
|
|
1474
3420
|
];
|
|
1475
3421
|
function extractToolErrorCode(error) {
|
|
1476
|
-
const code = getRecordProperty
|
|
3422
|
+
const code = getRecordProperty(error, "code");
|
|
1477
3423
|
if (isTempadMcpErrorCode(code)) return code;
|
|
1478
|
-
const causeCode = getRecordProperty
|
|
3424
|
+
const causeCode = getRecordProperty(getRecordProperty(error, "cause"), "code");
|
|
1479
3425
|
if (isTempadMcpErrorCode(causeCode)) return causeCode;
|
|
1480
3426
|
}
|
|
1481
3427
|
function isTempadMcpErrorCode(value) {
|
|
@@ -1484,10 +3430,8 @@ function isTempadMcpErrorCode(value) {
|
|
|
1484
3430
|
function extractToolErrorMessage(error) {
|
|
1485
3431
|
if (error instanceof Error) return error.message || "Unknown error occurred.";
|
|
1486
3432
|
if (typeof error === "string") return error;
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
if (typeof candidate.message === "string" && candidate.message.trim()) return candidate.message;
|
|
1490
|
-
}
|
|
3433
|
+
const message = getRecordProperty(error, "message");
|
|
3434
|
+
if (typeof message === "string" && message.trim()) return message;
|
|
1491
3435
|
return "Unknown error occurred.";
|
|
1492
3436
|
}
|
|
1493
3437
|
function createToolErrorResponse(toolName, error) {
|
|
@@ -1505,57 +3449,59 @@ function buildTroubleshootingText(code, message) {
|
|
|
1505
3449
|
const help = [];
|
|
1506
3450
|
if (isConnectivityToolError(code, message)) help.push(...CONNECTIVITY_TROUBLESHOOTING_LINES);
|
|
1507
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);
|
|
1508
3453
|
return help.length ? `\n\n${help.join("\n")}` : "";
|
|
1509
3454
|
}
|
|
1510
3455
|
function isConnectivityToolError(code, message) {
|
|
1511
|
-
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) || /
|
|
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);
|
|
1512
3457
|
}
|
|
1513
3458
|
function isSelectionToolError(code, message) {
|
|
1514
3459
|
return (code ? SELECTION_ERROR_CODES.has(code) : false) || /select exactly one visible node/i.test(message) || /no visible node found/i.test(message);
|
|
1515
3460
|
}
|
|
1516
3461
|
function createCodeToolResponse(payload) {
|
|
1517
|
-
|
|
1518
|
-
|
|
3462
|
+
return formatToolResult("get_code", payload, isCodeResult, buildGetCodeToolResult);
|
|
3463
|
+
}
|
|
3464
|
+
function createDesignSystemToolResponse(payload) {
|
|
3465
|
+
return formatToolResult("get_design_system", payload, isDesignSystemResult, buildGetDesignSystemToolResult);
|
|
3466
|
+
}
|
|
3467
|
+
function createApplyCanvasToolResponse(payload) {
|
|
3468
|
+
return formatToolResult("apply_canvas", payload, isApplyCanvasResult, buildApplyCanvasToolResult);
|
|
1519
3469
|
}
|
|
1520
3470
|
function createStructureToolResponse(payload) {
|
|
1521
|
-
|
|
1522
|
-
return toCallToolResult(buildGetStructureToolResult(payload));
|
|
3471
|
+
return formatToolResult("get_structure", payload, isStructureResult, buildGetStructureToolResult);
|
|
1523
3472
|
}
|
|
1524
3473
|
function createTokenDefsToolResponse(payload) {
|
|
1525
|
-
|
|
1526
|
-
return toCallToolResult(buildGetTokenDefsToolResult(payload));
|
|
3474
|
+
return formatToolResult("get_token_defs", payload, isTokenDefsResult, buildGetTokenDefsToolResult);
|
|
1527
3475
|
}
|
|
1528
3476
|
function createScreenshotToolResponse(payload) {
|
|
1529
|
-
|
|
1530
|
-
|
|
3477
|
+
return formatToolResult("get_screenshot", payload, isScreenshotResult, buildGetScreenshotToolResult);
|
|
3478
|
+
}
|
|
3479
|
+
function formatToolResult(toolName, payload, isValid, build) {
|
|
3480
|
+
if (!isValid(payload)) throw new Error(`Invalid ${toolName} payload received from extension.`);
|
|
3481
|
+
return toCallToolResult(build(payload));
|
|
1531
3482
|
}
|
|
1532
3483
|
function isScreenshotResult(payload) {
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
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";
|
|
3485
|
+
}
|
|
3486
|
+
function isDesignSystemResult(payload) {
|
|
3487
|
+
return GetDesignSystemResultSchema.safeParse(payload).success;
|
|
3488
|
+
}
|
|
3489
|
+
function isApplyCanvasResult(payload) {
|
|
3490
|
+
return ApplyCanvasResultSchema.safeParse(payload).success;
|
|
1536
3491
|
}
|
|
1537
3492
|
function isCodeResult(payload) {
|
|
1538
|
-
|
|
1539
|
-
const candidate = payload;
|
|
1540
|
-
return typeof candidate.code === "string" && typeof candidate.lang === "string" && (candidate.assets === void 0 || Array.isArray(candidate.assets));
|
|
3493
|
+
return isRecord(payload) && typeof payload.code === "string" && typeof payload.lang === "string" && (payload.assets === void 0 || Array.isArray(payload.assets));
|
|
1541
3494
|
}
|
|
1542
3495
|
function isStructureResult(payload) {
|
|
1543
|
-
|
|
1544
|
-
const candidate = payload;
|
|
1545
|
-
return Array.isArray(candidate.roots);
|
|
3496
|
+
return isRecord(payload) && Array.isArray(payload.roots);
|
|
1546
3497
|
}
|
|
1547
3498
|
function isTokenDefsResult(payload) {
|
|
1548
|
-
if (!
|
|
1549
|
-
for (const
|
|
1550
|
-
if (!value || typeof value !== "object") return false;
|
|
1551
|
-
const token = value;
|
|
1552
|
-
if (typeof token.kind !== "string") return false;
|
|
1553
|
-
if (token.value === void 0) return false;
|
|
1554
|
-
}
|
|
3499
|
+
if (!isRecord(payload)) return false;
|
|
3500
|
+
for (const token of Object.values(payload)) if (!isRecord(token) || typeof token.kind !== "string" || token.value === void 0) return false;
|
|
1555
3501
|
return true;
|
|
1556
3502
|
}
|
|
1557
3503
|
function coercePayloadToToolResponse(payload) {
|
|
1558
|
-
if (payload &&
|
|
3504
|
+
if (isRecord(payload) && Array.isArray(payload.content)) return payload;
|
|
1559
3505
|
return { content: [{
|
|
1560
3506
|
type: "text",
|
|
1561
3507
|
text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2)
|
|
@@ -1564,6 +3510,29 @@ function coercePayloadToToolResponse(payload) {
|
|
|
1564
3510
|
function createAssetsToolResponse(payload) {
|
|
1565
3511
|
return toCallToolResult(buildGetAssetsToolResult(payload));
|
|
1566
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
|
+
}
|
|
1567
3536
|
function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
|
|
1568
3537
|
return {
|
|
1569
3538
|
isError: true,
|
|
@@ -1578,12 +3547,20 @@ function toCallToolResult(result) {
|
|
|
1578
3547
|
}
|
|
1579
3548
|
function getBudgetRetryGuidance(toolName) {
|
|
1580
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.";
|
|
3556
|
+
case "apply_canvas": return "Submit a smaller desired subtree and retry.";
|
|
1581
3557
|
case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
|
|
3558
|
+
case "get_design_system": return "Continue from another catalog cursor or avoid the oversized exact definition.";
|
|
1582
3559
|
case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
|
|
1583
3560
|
case "get_token_defs": return "Reduce requested names or split them into smaller batches and retry.";
|
|
1584
|
-
case "get_screenshot": return "
|
|
3561
|
+
case "get_screenshot": return "Pass a smaller nodeId and retry.";
|
|
1585
3562
|
case "get_assets": return "Request fewer hashes in a single call and retry.";
|
|
1586
|
-
|
|
3563
|
+
case "upload_asset": return "Generate a smaller PNG, JPEG, or GIF and retry without printing its data URL.";
|
|
1587
3564
|
}
|
|
1588
3565
|
}
|
|
1589
3566
|
//#endregion
|
|
@@ -1594,12 +3571,14 @@ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections,
|
|
|
1594
3571
|
host: "127.0.0.1",
|
|
1595
3572
|
port: candidate,
|
|
1596
3573
|
maxPayload: maxPayloadBytes,
|
|
3574
|
+
handleProtocols: (protocols) => protocols.has("tempad-mcp") ? TEMPAD_MCP_BRIDGE_SUBPROTOCOL : false,
|
|
1597
3575
|
verifyClient: (info) => {
|
|
1598
3576
|
if (server.clients.size >= maxConnections) {
|
|
1599
3577
|
onConnectionLimit?.(maxConnections);
|
|
1600
3578
|
return false;
|
|
1601
3579
|
}
|
|
1602
|
-
const
|
|
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"));
|
|
1603
3582
|
if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
|
|
1604
3583
|
return allowed;
|
|
1605
3584
|
}
|
|
@@ -1644,20 +3623,35 @@ function resolveListeningPort(server, candidate) {
|
|
|
1644
3623
|
//#region src/hub.ts
|
|
1645
3624
|
const SHUTDOWN_TIMEOUT = 2e3;
|
|
1646
3625
|
const SOCKET_PROBE_TIMEOUT_MS = 300;
|
|
1647
|
-
const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
|
|
3626
|
+
const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
|
|
1648
3627
|
const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
|
|
1649
3628
|
log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
|
|
1650
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();
|
|
1651
3648
|
let consumerCount = 0;
|
|
1652
3649
|
let selectedWsPort = 0;
|
|
1653
3650
|
let releaseHubLock = null;
|
|
1654
3651
|
let shuttingDown = false;
|
|
1655
3652
|
let wss = null;
|
|
3653
|
+
let hubRuntimeIdentity = null;
|
|
1656
3654
|
const consumerSessions = /* @__PURE__ */ new Set();
|
|
1657
|
-
function getRecordProperty(record, key) {
|
|
1658
|
-
if (!record || typeof record !== "object") return;
|
|
1659
|
-
return Reflect.get(record, key);
|
|
1660
|
-
}
|
|
1661
3655
|
function classifySocketProbeError(error) {
|
|
1662
3656
|
if (error.code === "ENOENT") return "missing";
|
|
1663
3657
|
if (error.code === "ECONNREFUSED" || error.code === "ENOTSOCK") return { staleCode: error.code };
|
|
@@ -1740,10 +3734,44 @@ async function cleanSocketPath() {
|
|
|
1740
3734
|
function enrichToolDefinition(tool) {
|
|
1741
3735
|
if (tool.target === "extension") return tool;
|
|
1742
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
|
+
};
|
|
1743
3767
|
case "get_assets": return {
|
|
1744
3768
|
...tool,
|
|
1745
3769
|
handler: handleGetAssets
|
|
1746
3770
|
};
|
|
3771
|
+
case "upload_asset": return {
|
|
3772
|
+
...tool,
|
|
3773
|
+
handler: handleUploadAsset
|
|
3774
|
+
};
|
|
1747
3775
|
default: throw new Error("No handler configured for hub tool.");
|
|
1748
3776
|
}
|
|
1749
3777
|
}
|
|
@@ -1821,6 +3849,7 @@ function buildAssetDescriptor(record) {
|
|
|
1821
3849
|
return {
|
|
1822
3850
|
hash: record.hash,
|
|
1823
3851
|
url: `${assetHttpServer.getBaseUrl()}/assets/${filename}`,
|
|
3852
|
+
localPath: record.filePath,
|
|
1824
3853
|
mimeType: record.mimeType,
|
|
1825
3854
|
size: record.size,
|
|
1826
3855
|
width: record.metadata?.width,
|
|
@@ -1828,52 +3857,195 @@ function buildAssetDescriptor(record) {
|
|
|
1828
3857
|
...record.metadata?.themeable ? { themeable: true } : {}
|
|
1829
3858
|
};
|
|
1830
3859
|
}
|
|
1831
|
-
function
|
|
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) {
|
|
1832
3952
|
const mcp = new McpServer({
|
|
1833
3953
|
name: "tempad-dev",
|
|
1834
3954
|
title: "TemPad Dev",
|
|
1835
3955
|
version: PACKAGE_VERSION
|
|
1836
3956
|
}, { instructions: instructions_default });
|
|
3957
|
+
mcp.server.setNotificationHandler(ClientEventSchema, (notification) => agentClients.event(ownerId, notification));
|
|
3958
|
+
mcp.server.setRequestHandler(ClientHookRequestSchema, (request) => agentClients.clientHook(request.params));
|
|
1837
3959
|
const registered = [];
|
|
1838
3960
|
for (const tool of TOOL_DEFINITIONS) {
|
|
1839
3961
|
if ("exposed" in tool && tool.exposed === false) continue;
|
|
1840
|
-
registerTool(mcp, tool);
|
|
3962
|
+
registerTool(mcp, tool, ownerId);
|
|
1841
3963
|
registered.push(tool.name);
|
|
1842
3964
|
}
|
|
1843
3965
|
log.info({ tools: registered }, "Registered tools.");
|
|
1844
3966
|
return mcp;
|
|
1845
3967
|
}
|
|
1846
|
-
function registerTool(mcp, tool) {
|
|
1847
|
-
if (tool.target === "extension") registerProxiedTool(mcp, tool);
|
|
1848
|
-
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);
|
|
1849
3971
|
}
|
|
1850
|
-
function registerProxiedTool(mcp, tool) {
|
|
3972
|
+
function registerProxiedTool(mcp, tool, ownerId) {
|
|
1851
3973
|
const registerToolFn = mcp.registerTool.bind(mcp);
|
|
1852
3974
|
const schema = tool.parameters;
|
|
1853
|
-
const
|
|
3975
|
+
const connectionId = ownerId;
|
|
3976
|
+
const handler = async (args, extra) => {
|
|
3977
|
+
const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
|
|
1854
3978
|
let requestId;
|
|
1855
3979
|
try {
|
|
1856
|
-
const
|
|
1857
|
-
const
|
|
1858
|
-
if (
|
|
1859
|
-
const
|
|
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" });
|
|
1860
4007
|
requestId = registration.requestId;
|
|
1861
4008
|
const message = {
|
|
1862
4009
|
type: "toolCall",
|
|
1863
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
|
+
},
|
|
1864
4020
|
payload: {
|
|
1865
4021
|
name: tool.name,
|
|
1866
4022
|
args: parsedArgs
|
|
1867
4023
|
}
|
|
1868
4024
|
};
|
|
1869
|
-
|
|
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
|
+
}
|
|
1870
4032
|
log.info({
|
|
1871
4033
|
tool: tool.name,
|
|
1872
4034
|
req: registration.requestId,
|
|
1873
4035
|
extId: activeExt.id
|
|
1874
4036
|
}, "Forwarded tool call.");
|
|
1875
4037
|
const payload = await registration.promise;
|
|
1876
|
-
|
|
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);
|
|
1877
4049
|
} catch (error) {
|
|
1878
4050
|
const normalized = coerceToolError(error);
|
|
1879
4051
|
log.error({
|
|
@@ -1886,22 +4058,36 @@ function registerProxiedTool(mcp, tool) {
|
|
|
1886
4058
|
}
|
|
1887
4059
|
};
|
|
1888
4060
|
registerToolFn(tool.name, {
|
|
4061
|
+
annotations: tool.annotations,
|
|
1889
4062
|
description: tool.description,
|
|
1890
4063
|
inputSchema: schema
|
|
1891
4064
|
}, handler);
|
|
1892
4065
|
}
|
|
1893
|
-
function registerLocalTool(mcp, tool) {
|
|
4066
|
+
function registerLocalTool(mcp, tool, ownerId) {
|
|
1894
4067
|
const schema = tool.parameters;
|
|
1895
4068
|
const handler = tool.handler;
|
|
1896
4069
|
const registerToolFn = mcp.registerTool.bind(mcp);
|
|
1897
4070
|
const registrationOptions = {
|
|
4071
|
+
annotations: tool.annotations,
|
|
1898
4072
|
description: tool.description,
|
|
1899
4073
|
inputSchema: schema
|
|
1900
4074
|
};
|
|
1901
4075
|
if (tool.outputSchema) registrationOptions.outputSchema = tool.outputSchema;
|
|
1902
|
-
const
|
|
4076
|
+
const connectionId = ownerId;
|
|
4077
|
+
const registerHandler = async (args, extra) => {
|
|
4078
|
+
const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
|
|
1903
4079
|
try {
|
|
1904
|
-
|
|
4080
|
+
const parsed = schema.parse(args);
|
|
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);
|
|
1905
4091
|
} catch (error) {
|
|
1906
4092
|
log.error({
|
|
1907
4093
|
tool: tool.name,
|
|
@@ -1912,21 +4098,41 @@ function registerLocalTool(mcp, tool) {
|
|
|
1912
4098
|
};
|
|
1913
4099
|
registerToolFn(tool.name, registrationOptions, registerHandler);
|
|
1914
4100
|
}
|
|
1915
|
-
function createToolResponse(toolName, payload) {
|
|
1916
|
-
const
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
return
|
|
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;
|
|
1927
4116
|
}
|
|
1928
|
-
|
|
4117
|
+
if (toolName === "apply_canvas" && runtime) return {
|
|
4118
|
+
...payload,
|
|
4119
|
+
runtime
|
|
4120
|
+
};
|
|
4121
|
+
return payload;
|
|
1929
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);
|
|
1930
4136
|
const resultBytes = measureCallToolResultBytes(rawResult);
|
|
1931
4137
|
if (resultBytes > 65536) {
|
|
1932
4138
|
log.warn({
|
|
@@ -1938,6 +4144,34 @@ function createToolResponse(toolName, payload) {
|
|
|
1938
4144
|
}
|
|
1939
4145
|
return rawResult;
|
|
1940
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
|
+
}
|
|
1941
4175
|
async function handleGetAssets({ hashes }) {
|
|
1942
4176
|
if (hashes.length > 100) throw new Error("Too many hashes requested. Limit is 100.");
|
|
1943
4177
|
const unique = Array.from(new Set(hashes));
|
|
@@ -1952,6 +4186,27 @@ async function handleGetAssets({ hashes }) {
|
|
|
1952
4186
|
missing: unique.filter((hash) => !found.has(hash))
|
|
1953
4187
|
}));
|
|
1954
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
|
+
}
|
|
1955
4210
|
function unrefTimer(timer) {
|
|
1956
4211
|
if (typeof timer === "object" && timer !== null) {
|
|
1957
4212
|
const handle = timer;
|
|
@@ -1959,21 +4214,41 @@ function unrefTimer(timer) {
|
|
|
1959
4214
|
}
|
|
1960
4215
|
}
|
|
1961
4216
|
function broadcastState() {
|
|
4217
|
+
publishHubRuntimeIdentity();
|
|
1962
4218
|
const activeId = extensionRegistry.getActiveId();
|
|
1963
|
-
const
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
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
|
+
}
|
|
1969
4227
|
log.debug({
|
|
1970
4228
|
activeId,
|
|
1971
4229
|
count: extensionRegistry.size
|
|
1972
4230
|
}, "Broadcasted state.");
|
|
1973
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
|
+
}
|
|
1974
4246
|
function shutdown() {
|
|
1975
4247
|
if (shuttingDown) return;
|
|
1976
4248
|
shuttingDown = true;
|
|
4249
|
+
clearInterval(designTaskTimer);
|
|
4250
|
+
clearInterval(clientCapabilityTimer);
|
|
4251
|
+
agentClients.close();
|
|
1977
4252
|
log.info("Hub is shutting down...");
|
|
1978
4253
|
consumerSessions.forEach((session) => {
|
|
1979
4254
|
session.close().catch((err) => {
|
|
@@ -1987,6 +4262,7 @@ function shutdown() {
|
|
|
1987
4262
|
netServer.close(() => log.info("Net server closed."));
|
|
1988
4263
|
wss?.close(() => log.info("WebSocket server closed."));
|
|
1989
4264
|
cleanupAll();
|
|
4265
|
+
removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
|
|
1990
4266
|
releaseHubLockIfNeeded();
|
|
1991
4267
|
unrefTimer(setTimeout(() => {
|
|
1992
4268
|
log.warn("Shutdown timed out. Forcing exit.");
|
|
@@ -1994,7 +4270,8 @@ function shutdown() {
|
|
|
1994
4270
|
}, SHUTDOWN_TIMEOUT));
|
|
1995
4271
|
}
|
|
1996
4272
|
const netServer = createServer((sock) => {
|
|
1997
|
-
const
|
|
4273
|
+
const ownerId = randomUUID();
|
|
4274
|
+
const mcp = createMcpServer(ownerId);
|
|
1998
4275
|
consumerSessions.add(mcp);
|
|
1999
4276
|
consumerCount++;
|
|
2000
4277
|
log.info(`Consumer connected. Total: ${consumerCount}`);
|
|
@@ -2011,6 +4288,7 @@ const netServer = createServer((sock) => {
|
|
|
2011
4288
|
transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
|
|
2012
4289
|
});
|
|
2013
4290
|
sock.on("close", async () => {
|
|
4291
|
+
agentClients.disconnect(ownerId);
|
|
2014
4292
|
await transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
|
|
2015
4293
|
await mcp.close().catch((closeErr) => log.warn({ err: closeErr }, "MCP session close failed."));
|
|
2016
4294
|
consumerSessions.delete(mcp);
|
|
@@ -2026,7 +4304,10 @@ async function initializeHubRuntime() {
|
|
|
2026
4304
|
ensureDir(RUNTIME_DIR);
|
|
2027
4305
|
if (await probeSocketPath() === "live") await exitExistingHub();
|
|
2028
4306
|
releaseHubLock = await acquireHubLock();
|
|
4307
|
+
designTasks.restore();
|
|
2029
4308
|
await cleanSocketPath();
|
|
4309
|
+
hubRuntimeIdentity = createHubRuntimeIdentity(fileURLToPath(import.meta.url), PACKAGE_VERSION);
|
|
4310
|
+
writeHubRuntimeIdentity(HUB_RUNTIME_IDENTITY_PATH, hubRuntimeIdentity);
|
|
2030
4311
|
await assetHttpServer.start();
|
|
2031
4312
|
scheduleAssetCleanup();
|
|
2032
4313
|
}
|
|
@@ -2092,6 +4373,7 @@ async function startHubRuntime() {
|
|
|
2092
4373
|
async function abortStartup(error) {
|
|
2093
4374
|
log.error({ err: error }, "Failed to initialize Hub runtime.");
|
|
2094
4375
|
assetHttpServer.stop();
|
|
4376
|
+
removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
|
|
2095
4377
|
await releaseHubLockIfNeeded();
|
|
2096
4378
|
process.exit(1);
|
|
2097
4379
|
}
|
|
@@ -2122,6 +4404,7 @@ activeWss.on("connection", (ws, request) => {
|
|
|
2122
4404
|
},
|
|
2123
4405
|
onDisconnected: (extensionId, wasActive) => {
|
|
2124
4406
|
log.info({ id: extensionId }, `Extension disconnected. Remaining: ${extensionRegistry.size}`);
|
|
4407
|
+
designTasks.disconnectExtension(extensionId);
|
|
2125
4408
|
cleanupForExtension(extensionId);
|
|
2126
4409
|
if (wasActive) log.warn({ id: extensionId }, "Active extension disconnected.");
|
|
2127
4410
|
},
|
|
@@ -2136,6 +4419,76 @@ activeWss.on("connection", (ws, request) => {
|
|
|
2136
4419
|
extId: warning.extensionId
|
|
2137
4420
|
}, "Invalid message shape.");
|
|
2138
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
|
+
},
|
|
2139
4492
|
onSocketError: (extensionId, error) => {
|
|
2140
4493
|
log.warn({
|
|
2141
4494
|
err: error,
|
|
@@ -2144,6 +4497,8 @@ activeWss.on("connection", (ws, request) => {
|
|
|
2144
4497
|
},
|
|
2145
4498
|
onStateChange: broadcastState,
|
|
2146
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);
|
|
2147
4502
|
const normalized = coerceToolError(error);
|
|
2148
4503
|
log.warn({
|
|
2149
4504
|
toolReq: requestId,
|
|
@@ -2154,7 +4509,8 @@ activeWss.on("connection", (ws, request) => {
|
|
|
2154
4509
|
reject(requestId, extensionId, normalized);
|
|
2155
4510
|
},
|
|
2156
4511
|
onToolResult: (requestId, extensionId, payload) => {
|
|
2157
|
-
|
|
4512
|
+
designTasks.finishOperation(requestId, extensionId);
|
|
4513
|
+
resolve$1(requestId, extensionId, payload);
|
|
2158
4514
|
}
|
|
2159
4515
|
});
|
|
2160
4516
|
});
|