@milaboratories/pl-mcp-server 53.0.0 → 54.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -2
- package/dist/instructions.cjs +3 -2
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +3 -2
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +72 -0
- package/dist/project-holds.cjs.map +1 -0
- package/dist/project-holds.js +72 -0
- package/dist/project-holds.js.map +1 -0
- package/dist/server-log.cjs +373 -0
- package/dist/server-log.cjs.map +1 -0
- package/dist/server-log.js +371 -0
- package/dist/server-log.js.map +1 -0
- package/dist/server.cjs +77 -22
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +31 -7
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -23
- package/dist/server.js.map +1 -1
- package/dist/tools/await.cjs +59 -60
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +60 -61
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +11 -9
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +11 -9
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-params.cjs +4 -3
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +4 -3
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +46 -41
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +47 -42
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/blocks.cjs +30 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +30 -20
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/connection.cjs.map +1 -1
- package/dist/tools/connection.js.map +1 -1
- package/dist/tools/data-query.cjs +111 -80
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +114 -83
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/ids.cjs +16 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +13 -1
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/logs.cjs +28 -26
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +28 -26
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/ping.cjs.map +1 -1
- package/dist/tools/ping.js.map +1 -1
- package/dist/tools/projects.cjs +10 -27
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +11 -28
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/sandbox.cjs +110 -8
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +107 -9
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/screenshot.cjs +9 -1
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.js +9 -1
- package/dist/tools/screenshot.js.map +1 -1
- package/dist/tools/types.cjs +29 -0
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +27 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/ui-interaction.cjs.map +1 -1
- package/dist/tools/ui-interaction.js.map +1 -1
- package/package.json +6 -5
- package/src/instructions.ts +3 -2
- package/src/project-holds.test.ts +183 -0
- package/src/project-holds.ts +105 -0
- package/src/server-log.test.ts +871 -0
- package/src/server-log.ts +504 -0
- package/src/server.logging.test.ts +383 -0
- package/src/server.request-failure.test.ts +49 -0
- package/src/server.test.ts +15 -5
- package/src/server.ts +111 -26
- package/src/test/recording-logger.ts +33 -0
- package/src/tools/await.ts +96 -98
- package/src/tools/block-action-context.ts +16 -16
- package/src/tools/block-params.ts +6 -6
- package/src/tools/block-state.ts +61 -60
- package/src/tools/blocks.ts +49 -40
- package/src/tools/connection.ts +2 -3
- package/src/tools/data-query.ts +151 -108
- package/src/tools/ids.ts +22 -1
- package/src/tools/logs.ts +43 -43
- package/src/tools/ping.ts +2 -3
- package/src/tools/projects.ts +22 -45
- package/src/tools/sandbox.test.ts +183 -0
- package/src/tools/sandbox.ts +126 -10
- package/src/tools/screenshot.ts +15 -4
- package/src/tools/types.test.ts +4 -3
- package/src/tools/types.ts +73 -3
- package/src/tools/ui-interaction.ts +2 -3
package/dist/tools/projects.cjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
const require_types = require("./types.cjs");
|
|
2
2
|
const require_ids = require("./ids.cjs");
|
|
3
|
+
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
3
4
|
let zod = require("zod");
|
|
4
5
|
// src/tools/projects.ts
|
|
5
6
|
function registerProjectTools(server, ctx) {
|
|
6
7
|
server.registerTool("list_projects", {
|
|
7
8
|
title: "List Projects",
|
|
8
9
|
annotations: require_types.hints.read,
|
|
9
|
-
description: "List all projects with their IDs, labels, and
|
|
10
|
+
description: "List all projects with their IDs, labels, and creation and modification times"
|
|
10
11
|
}, async () => {
|
|
11
12
|
const ml = ctx.requireMl();
|
|
12
13
|
await ml.projectList.refreshState();
|
|
@@ -14,7 +15,6 @@ function registerProjectTools(server, ctx) {
|
|
|
14
15
|
return require_types.textResult(projects.map((p) => ({
|
|
15
16
|
projectId: p.id,
|
|
16
17
|
label: p.meta.label,
|
|
17
|
-
opened: p.opened,
|
|
18
18
|
created: p.created.toISOString(),
|
|
19
19
|
lastModified: p.lastModified.toISOString()
|
|
20
20
|
})));
|
|
@@ -22,43 +22,26 @@ function registerProjectTools(server, ctx) {
|
|
|
22
22
|
server.registerTool("create_project", {
|
|
23
23
|
title: "Create Project",
|
|
24
24
|
annotations: require_types.hints.additive,
|
|
25
|
-
description: "Create a new, empty project and return its ID.
|
|
25
|
+
description: "Create a new, empty project and return its ID.",
|
|
26
26
|
inputSchema: zod.z.object({ label: zod.z.string().describe("Project name") })
|
|
27
27
|
}, async ({ label }) => {
|
|
28
28
|
const projectId = await ctx.requireMl().createProject({ label });
|
|
29
29
|
await ctx.callbacks.onProjectCreated?.(projectId);
|
|
30
30
|
return require_types.textResult({ projectId });
|
|
31
31
|
});
|
|
32
|
-
server.registerTool("open_project", {
|
|
33
|
-
title: "Open Project",
|
|
34
|
-
annotations: require_types.hints.idempotent,
|
|
35
|
-
description: "Open a project for editing. Required before working with blocks.",
|
|
36
|
-
inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID from list_projects or create_project") })
|
|
37
|
-
}, async ({ projectId }) => {
|
|
38
|
-
const entry = await ctx.resolveProject(projectId);
|
|
39
|
-
await ctx.requireMl().openProject(entry.id);
|
|
40
|
-
await ctx.callbacks.onProjectOpened?.(projectId);
|
|
41
|
-
return require_types.textResult({ ok: true });
|
|
42
|
-
});
|
|
43
|
-
server.registerTool("close_project", {
|
|
44
|
-
title: "Close Project",
|
|
45
|
-
annotations: require_types.hints.idempotent,
|
|
46
|
-
description: "Close an opened project, releasing its resources in the application. Nothing is deleted.",
|
|
47
|
-
inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID") })
|
|
48
|
-
}, async ({ projectId }) => {
|
|
49
|
-
const entry = await ctx.resolveProject(projectId);
|
|
50
|
-
await ctx.requireMl().closeProject(entry.id);
|
|
51
|
-
await ctx.callbacks.onProjectClosed?.(projectId);
|
|
52
|
-
return require_types.textResult({ ok: true });
|
|
53
|
-
});
|
|
54
32
|
server.registerTool("delete_project", {
|
|
55
33
|
title: "Delete Project",
|
|
56
34
|
annotations: require_types.hints.destructive,
|
|
57
|
-
description: "Delete a project permanently.
|
|
35
|
+
description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent or by the user in the application.",
|
|
58
36
|
inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID") })
|
|
59
37
|
}, async ({ projectId }) => {
|
|
60
38
|
const entry = await ctx.resolveProject(projectId);
|
|
61
|
-
|
|
39
|
+
try {
|
|
40
|
+
await ctx.requireMl().deleteProject(entry.id, { refuseIfHeldBy: (holder) => holder !== ctx.projectHolder });
|
|
41
|
+
} catch (e) {
|
|
42
|
+
if (!(0, _milaboratories_pl_middle_layer.isProjectInUseError)(e)) throw e;
|
|
43
|
+
return require_types.errorResult(`Project ${projectId} was not deleted: it is still in use by another agent or by the user in the application.`);
|
|
44
|
+
}
|
|
62
45
|
await ctx.callbacks.onProjectDeleted?.(projectId);
|
|
63
46
|
return require_types.textResult({ ok: true });
|
|
64
47
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projects.cjs","names":["hints","textResult","z","projectIdInput"],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"projects.cjs","names":["hints","textResult","z","projectIdInput","isProjectInUseError","errorResult"],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { isProjectInUseError } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and creation and modification times\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description: \"Create a new, empty project and return its ID.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description:\n \"Delete a project permanently, with all its blocks and results. Refused while the project \" +\n \"is in use by another agent or by the user in the application.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n try {\n // This server's own holds, kept or of calls still running, end with the delete: a deleted\n // project is not snapshotted. Anyone else's hold refuses it.\n await ctx.requireMl().deleteProject(entry.id, {\n refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,\n });\n } catch (e: unknown) {\n if (!isProjectInUseError(e)) throw e;\n return errorResult(\n `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +\n \"user in the application.\",\n );\n }\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAOC,cAAAA,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aAAa;EACb,aAAaE,IAAAA,EAAE,OAAO,EAAE,OAAOA,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOD,cAAAA,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaD,cAAAA,MAAM;EACnB,aACE;EAEF,aAAaE,IAAAA,EAAE,OAAO,EAAE,WAAWC,YAAAA,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,IAAI;GAGF,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,IAAI,EAC5C,iBAAiB,WAAW,WAAW,IAAI,cAC7C,CAAC;EACH,SAAS,GAAY;GACnB,IAAI,EAAA,GAACC,gCAAAA,oBAAAA,CAAoB,CAAC,GAAG,MAAM;GACnC,OAAOC,cAAAA,YACL,WAAW,UAAU,yFAEvB;EACF;EACA,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOJ,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
|
package/dist/tools/projects.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { hints, textResult } from "./types.js";
|
|
1
|
+
import { errorResult, hints, textResult } from "./types.js";
|
|
2
2
|
import { projectIdInput } from "./ids.js";
|
|
3
|
+
import { isProjectInUseError } from "@milaboratories/pl-middle-layer";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
// src/tools/projects.ts
|
|
5
6
|
function registerProjectTools(server, ctx) {
|
|
6
7
|
server.registerTool("list_projects", {
|
|
7
8
|
title: "List Projects",
|
|
8
9
|
annotations: hints.read,
|
|
9
|
-
description: "List all projects with their IDs, labels, and
|
|
10
|
+
description: "List all projects with their IDs, labels, and creation and modification times"
|
|
10
11
|
}, async () => {
|
|
11
12
|
const ml = ctx.requireMl();
|
|
12
13
|
await ml.projectList.refreshState();
|
|
@@ -14,7 +15,6 @@ function registerProjectTools(server, ctx) {
|
|
|
14
15
|
return textResult(projects.map((p) => ({
|
|
15
16
|
projectId: p.id,
|
|
16
17
|
label: p.meta.label,
|
|
17
|
-
opened: p.opened,
|
|
18
18
|
created: p.created.toISOString(),
|
|
19
19
|
lastModified: p.lastModified.toISOString()
|
|
20
20
|
})));
|
|
@@ -22,43 +22,26 @@ function registerProjectTools(server, ctx) {
|
|
|
22
22
|
server.registerTool("create_project", {
|
|
23
23
|
title: "Create Project",
|
|
24
24
|
annotations: hints.additive,
|
|
25
|
-
description: "Create a new, empty project and return its ID.
|
|
25
|
+
description: "Create a new, empty project and return its ID.",
|
|
26
26
|
inputSchema: z.object({ label: z.string().describe("Project name") })
|
|
27
27
|
}, async ({ label }) => {
|
|
28
28
|
const projectId = await ctx.requireMl().createProject({ label });
|
|
29
29
|
await ctx.callbacks.onProjectCreated?.(projectId);
|
|
30
30
|
return textResult({ projectId });
|
|
31
31
|
});
|
|
32
|
-
server.registerTool("open_project", {
|
|
33
|
-
title: "Open Project",
|
|
34
|
-
annotations: hints.idempotent,
|
|
35
|
-
description: "Open a project for editing. Required before working with blocks.",
|
|
36
|
-
inputSchema: z.object({ projectId: projectIdInput.describe("Project ID from list_projects or create_project") })
|
|
37
|
-
}, async ({ projectId }) => {
|
|
38
|
-
const entry = await ctx.resolveProject(projectId);
|
|
39
|
-
await ctx.requireMl().openProject(entry.id);
|
|
40
|
-
await ctx.callbacks.onProjectOpened?.(projectId);
|
|
41
|
-
return textResult({ ok: true });
|
|
42
|
-
});
|
|
43
|
-
server.registerTool("close_project", {
|
|
44
|
-
title: "Close Project",
|
|
45
|
-
annotations: hints.idempotent,
|
|
46
|
-
description: "Close an opened project, releasing its resources in the application. Nothing is deleted.",
|
|
47
|
-
inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") })
|
|
48
|
-
}, async ({ projectId }) => {
|
|
49
|
-
const entry = await ctx.resolveProject(projectId);
|
|
50
|
-
await ctx.requireMl().closeProject(entry.id);
|
|
51
|
-
await ctx.callbacks.onProjectClosed?.(projectId);
|
|
52
|
-
return textResult({ ok: true });
|
|
53
|
-
});
|
|
54
32
|
server.registerTool("delete_project", {
|
|
55
33
|
title: "Delete Project",
|
|
56
34
|
annotations: hints.destructive,
|
|
57
|
-
description: "Delete a project permanently.
|
|
35
|
+
description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent or by the user in the application.",
|
|
58
36
|
inputSchema: z.object({ projectId: projectIdInput.describe("Project ID") })
|
|
59
37
|
}, async ({ projectId }) => {
|
|
60
38
|
const entry = await ctx.resolveProject(projectId);
|
|
61
|
-
|
|
39
|
+
try {
|
|
40
|
+
await ctx.requireMl().deleteProject(entry.id, { refuseIfHeldBy: (holder) => holder !== ctx.projectHolder });
|
|
41
|
+
} catch (e) {
|
|
42
|
+
if (!isProjectInUseError(e)) throw e;
|
|
43
|
+
return errorResult(`Project ${projectId} was not deleted: it is still in use by another agent or by the user in the application.`);
|
|
44
|
+
}
|
|
62
45
|
await ctx.callbacks.onProjectDeleted?.(projectId);
|
|
63
46
|
return textResult({ ok: true });
|
|
64
47
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projects.js","names":[],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"projects.js","names":[],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { isProjectInUseError } from \"@milaboratories/pl-middle-layer\";\nimport { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerProjectTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"list_projects\",\n {\n title: \"List Projects\",\n annotations: hints.read,\n description: \"List all projects with their IDs, labels, and creation and modification times\",\n },\n async () => {\n const ml = ctx.requireMl();\n await ml.projectList.refreshState();\n const projects = await ml.projectList.awaitStableValue();\n return textResult(\n projects.map((p) => ({\n projectId: p.id,\n label: p.meta.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n },\n );\n\n server.registerTool(\n \"create_project\",\n {\n title: \"Create Project\",\n annotations: hints.additive,\n description: \"Create a new, empty project and return its ID.\",\n inputSchema: z.object({ label: z.string().describe(\"Project name\") }),\n },\n async ({ label }) => {\n const projectId = await ctx.requireMl().createProject({ label });\n await ctx.callbacks.onProjectCreated?.(projectId);\n return textResult({ projectId });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description:\n \"Delete a project permanently, with all its blocks and results. Refused while the project \" +\n \"is in use by another agent or by the user in the application.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n try {\n // This server's own holds, kept or of calls still running, end with the delete: a deleted\n // project is not snapshotted. Anyone else's hold refuses it.\n await ctx.requireMl().deleteProject(entry.id, {\n refuseIfHeldBy: (holder) => holder !== ctx.projectHolder,\n });\n } catch (e: unknown) {\n if (!isProjectInUseError(e)) throw e;\n return errorResult(\n `Project ${projectId} was not deleted: it is still in use by another agent or by the ` +\n \"user in the application.\",\n );\n }\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,qBAAqB,QAAuB,KAAwB;CAClF,OAAO,aACL,iBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;CACf,GACA,YAAY;EACV,MAAM,KAAK,IAAI,UAAU;EACzB,MAAM,GAAG,YAAY,aAAa;EAClC,MAAM,WAAW,MAAM,GAAG,YAAY,iBAAiB;EACvD,OAAO,WACL,SAAS,KAAK,OAAO;GACnB,WAAW,EAAE;GACb,OAAO,EAAE,KAAK;GACd,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C,EAAE,CACJ;CACF,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;EACb,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,cAAc,EAAE,CAAC;CACtE,GACA,OAAO,EAAE,YAAY;EACnB,MAAM,YAAY,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,EAAE,MAAM,CAAC;EAC/D,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,UAAU,CAAC;CACjC,CACF;CAEA,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EAEF,aAAa,EAAE,OAAO,EAAE,WAAW,eAAe,SAAS,YAAY,EAAE,CAAC;CAC5E,GACA,OAAO,EAAE,gBAAgB;EACvB,MAAM,QAAQ,MAAM,IAAI,eAAe,SAAS;EAChD,IAAI;GAGF,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,IAAI,EAC5C,iBAAiB,WAAW,WAAW,IAAI,cAC7C,CAAC;EACH,SAAS,GAAY;GACnB,IAAI,CAAC,oBAAoB,CAAC,GAAG,MAAM;GACnC,OAAO,YACL,WAAW,UAAU,yFAEvB;EACF;EACA,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAO,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
|
package/dist/tools/sandbox.cjs
CHANGED
|
@@ -10,32 +10,130 @@ async function getRuntime() {
|
|
|
10
10
|
}
|
|
11
11
|
return sharedRuntime;
|
|
12
12
|
}
|
|
13
|
+
/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */
|
|
14
|
+
const EXPRESSION_FILE = "transform.js";
|
|
15
|
+
const SINGLE_EXPRESSION_HINT = "A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()";
|
|
16
|
+
/**
|
|
17
|
+
* The classes of the errors built into the JavaScript of the sandbox. Only these names are used as
|
|
18
|
+
* the class of a failure: code can give an error any name, data included.
|
|
19
|
+
*/
|
|
20
|
+
const BUILT_IN_ERRORS = /* @__PURE__ */ new Set([
|
|
21
|
+
"Error",
|
|
22
|
+
"AggregateError",
|
|
23
|
+
"EvalError",
|
|
24
|
+
"InternalError",
|
|
25
|
+
"RangeError",
|
|
26
|
+
"ReferenceError",
|
|
27
|
+
"SyntaxError",
|
|
28
|
+
"TypeError",
|
|
29
|
+
"URIError"
|
|
30
|
+
]);
|
|
31
|
+
/**
|
|
32
|
+
* What kind of failure an error is, in words that hold nothing of the code or its data: the name of
|
|
33
|
+
* a built-in error class, or `Error` for any other name.
|
|
34
|
+
*/
|
|
35
|
+
function errorClassOf(name) {
|
|
36
|
+
return BUILT_IN_ERRORS.has(name) ? name : "Error";
|
|
37
|
+
}
|
|
38
|
+
/** The class of the failure of an evaluation that threw a value that is not an error. */
|
|
39
|
+
const THROWN_VALUE = "Thrown value";
|
|
40
|
+
/** The class of the failure of an evaluation that ran out of time. */
|
|
41
|
+
const TIMEOUT = "timeout";
|
|
42
|
+
/**
|
|
43
|
+
* Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the
|
|
44
|
+
* agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.
|
|
45
|
+
*/
|
|
46
|
+
var SandboxError = class extends Error {
|
|
47
|
+
/** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */
|
|
48
|
+
errorClass;
|
|
49
|
+
constructor(message, errorClass) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "SandboxError";
|
|
52
|
+
this.errorClass = errorClass;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object
|
|
57
|
+
* `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file
|
|
58
|
+
* when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes
|
|
59
|
+
* as itself: a primitive, or an object that went through JSON.
|
|
60
|
+
*/
|
|
61
|
+
function parseThrown(dumped) {
|
|
62
|
+
if (typeof dumped === "object" && dumped !== null && "name" in dumped && "message" in dumped) {
|
|
63
|
+
const { name, message } = dumped;
|
|
64
|
+
if (typeof name === "string" && typeof message === "string") {
|
|
65
|
+
const label = name === "" ? "Error" : name;
|
|
66
|
+
const text = message === "" ? label : `${label}: ${message}`;
|
|
67
|
+
const errorClass = errorClassOf(name);
|
|
68
|
+
if (name === "SyntaxError" && "fileName" in dumped && typeof dumped.fileName === "string") return {
|
|
69
|
+
text,
|
|
70
|
+
errorClass,
|
|
71
|
+
syntaxErrorFile: dumped.fileName
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
text,
|
|
75
|
+
errorClass
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const errorClass = THROWN_VALUE;
|
|
80
|
+
if (typeof dumped === "string") return {
|
|
81
|
+
text: `${THROWN_VALUE}: ${dumped}`,
|
|
82
|
+
errorClass
|
|
83
|
+
};
|
|
84
|
+
if (typeof dumped === "object" && dumped !== null) {
|
|
85
|
+
const json = JSON.stringify(dumped, (_key, value) => typeof value === "bigint" ? `${value}n` : value);
|
|
86
|
+
return {
|
|
87
|
+
text: `${THROWN_VALUE}: ${json}`,
|
|
88
|
+
errorClass
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
text: `${THROWN_VALUE}: ${String(dumped)}`,
|
|
93
|
+
errorClass
|
|
94
|
+
};
|
|
95
|
+
}
|
|
13
96
|
/**
|
|
14
97
|
* Evaluate a JS expression in a QuickJS sandbox.
|
|
15
98
|
* Variables from `context` are injected as globals.
|
|
16
99
|
* Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
|
|
100
|
+
*
|
|
101
|
+
* A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
|
|
102
|
+
* with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than
|
|
103
|
+
* `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.
|
|
17
104
|
*/
|
|
18
105
|
async function safeEval(expression, context, timeout) {
|
|
19
106
|
const runtime = await getRuntime();
|
|
20
107
|
const deadline = Date.now() + timeout;
|
|
21
|
-
|
|
108
|
+
let timedOut = false;
|
|
109
|
+
runtime.setInterruptHandler(() => {
|
|
110
|
+
if (Date.now() > deadline) timedOut = true;
|
|
111
|
+
return timedOut;
|
|
112
|
+
});
|
|
113
|
+
const timeoutMessage = `Evaluation timed out after ${timeout} ms`;
|
|
22
114
|
const vm = runtime.newContext();
|
|
115
|
+
/** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */
|
|
116
|
+
const takeThrown = (error) => {
|
|
117
|
+
const dumped = vm.dump(error);
|
|
118
|
+
if (error.alive) error.dispose();
|
|
119
|
+
return timedOut ? void 0 : parseThrown(dumped);
|
|
120
|
+
};
|
|
23
121
|
try {
|
|
24
122
|
const contextJson = JSON.stringify(context);
|
|
25
123
|
const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});
|
|
26
124
|
${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).join("\n")}`;
|
|
27
125
|
const setupResult = vm.evalCode(setup, "setup.js", { type: "global" });
|
|
28
126
|
if (setupResult.error) {
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
throw new
|
|
127
|
+
const thrown = takeThrown(setupResult.error);
|
|
128
|
+
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
129
|
+
throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
|
|
32
130
|
}
|
|
33
131
|
setupResult.value.dispose();
|
|
34
|
-
const result = vm.evalCode(`JSON.stringify((${expression}))`,
|
|
132
|
+
const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
|
|
35
133
|
if (result.error) {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
throw new
|
|
134
|
+
const thrown = takeThrown(result.error);
|
|
135
|
+
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
136
|
+
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : thrown.text, thrown.errorClass);
|
|
39
137
|
}
|
|
40
138
|
const json = vm.getString(result.value);
|
|
41
139
|
result.value.dispose();
|
|
@@ -45,6 +143,10 @@ ${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).j
|
|
|
45
143
|
vm.dispose();
|
|
46
144
|
}
|
|
47
145
|
}
|
|
146
|
+
exports.SandboxError = SandboxError;
|
|
147
|
+
exports.THROWN_VALUE = THROWN_VALUE;
|
|
148
|
+
exports.TIMEOUT = TIMEOUT;
|
|
149
|
+
exports.errorClassOf = errorClassOf;
|
|
48
150
|
exports.safeEval = safeEval;
|
|
49
151
|
|
|
50
152
|
//# sourceMappingURL=sandbox.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.cjs","names":["getQuickJS"],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout
|
|
1
|
+
{"version":3,"file":"sandbox.cjs","names":["getQuickJS"],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than\n * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + timeout;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${timeout} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n // Inject context variables via JSON\n const contextJson = JSON.stringify(context);\n const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});\n${Object.keys(context)\n .map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`)\n .join(\"\\n\")}`;\n const setupResult = vm.evalCode(setup, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);\n }\n setupResult.value.dispose();\n\n // Evaluate the expression\n const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n const json = vm.getString(result.value);\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n"],"mappings":"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"}
|
package/dist/tools/sandbox.js
CHANGED
|
@@ -10,32 +10,130 @@ async function getRuntime() {
|
|
|
10
10
|
}
|
|
11
11
|
return sharedRuntime;
|
|
12
12
|
}
|
|
13
|
+
/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */
|
|
14
|
+
const EXPRESSION_FILE = "transform.js";
|
|
15
|
+
const SINGLE_EXPRESSION_HINT = "A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()";
|
|
16
|
+
/**
|
|
17
|
+
* The classes of the errors built into the JavaScript of the sandbox. Only these names are used as
|
|
18
|
+
* the class of a failure: code can give an error any name, data included.
|
|
19
|
+
*/
|
|
20
|
+
const BUILT_IN_ERRORS = /* @__PURE__ */ new Set([
|
|
21
|
+
"Error",
|
|
22
|
+
"AggregateError",
|
|
23
|
+
"EvalError",
|
|
24
|
+
"InternalError",
|
|
25
|
+
"RangeError",
|
|
26
|
+
"ReferenceError",
|
|
27
|
+
"SyntaxError",
|
|
28
|
+
"TypeError",
|
|
29
|
+
"URIError"
|
|
30
|
+
]);
|
|
31
|
+
/**
|
|
32
|
+
* What kind of failure an error is, in words that hold nothing of the code or its data: the name of
|
|
33
|
+
* a built-in error class, or `Error` for any other name.
|
|
34
|
+
*/
|
|
35
|
+
function errorClassOf(name) {
|
|
36
|
+
return BUILT_IN_ERRORS.has(name) ? name : "Error";
|
|
37
|
+
}
|
|
38
|
+
/** The class of the failure of an evaluation that threw a value that is not an error. */
|
|
39
|
+
const THROWN_VALUE = "Thrown value";
|
|
40
|
+
/** The class of the failure of an evaluation that ran out of time. */
|
|
41
|
+
const TIMEOUT = "timeout";
|
|
42
|
+
/**
|
|
43
|
+
* Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the
|
|
44
|
+
* agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.
|
|
45
|
+
*/
|
|
46
|
+
var SandboxError = class extends Error {
|
|
47
|
+
/** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */
|
|
48
|
+
errorClass;
|
|
49
|
+
constructor(message, errorClass) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.name = "SandboxError";
|
|
52
|
+
this.errorClass = errorClass;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object
|
|
57
|
+
* `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file
|
|
58
|
+
* when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes
|
|
59
|
+
* as itself: a primitive, or an object that went through JSON.
|
|
60
|
+
*/
|
|
61
|
+
function parseThrown(dumped) {
|
|
62
|
+
if (typeof dumped === "object" && dumped !== null && "name" in dumped && "message" in dumped) {
|
|
63
|
+
const { name, message } = dumped;
|
|
64
|
+
if (typeof name === "string" && typeof message === "string") {
|
|
65
|
+
const label = name === "" ? "Error" : name;
|
|
66
|
+
const text = message === "" ? label : `${label}: ${message}`;
|
|
67
|
+
const errorClass = errorClassOf(name);
|
|
68
|
+
if (name === "SyntaxError" && "fileName" in dumped && typeof dumped.fileName === "string") return {
|
|
69
|
+
text,
|
|
70
|
+
errorClass,
|
|
71
|
+
syntaxErrorFile: dumped.fileName
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
text,
|
|
75
|
+
errorClass
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const errorClass = THROWN_VALUE;
|
|
80
|
+
if (typeof dumped === "string") return {
|
|
81
|
+
text: `${THROWN_VALUE}: ${dumped}`,
|
|
82
|
+
errorClass
|
|
83
|
+
};
|
|
84
|
+
if (typeof dumped === "object" && dumped !== null) {
|
|
85
|
+
const json = JSON.stringify(dumped, (_key, value) => typeof value === "bigint" ? `${value}n` : value);
|
|
86
|
+
return {
|
|
87
|
+
text: `${THROWN_VALUE}: ${json}`,
|
|
88
|
+
errorClass
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
text: `${THROWN_VALUE}: ${String(dumped)}`,
|
|
93
|
+
errorClass
|
|
94
|
+
};
|
|
95
|
+
}
|
|
13
96
|
/**
|
|
14
97
|
* Evaluate a JS expression in a QuickJS sandbox.
|
|
15
98
|
* Variables from `context` are injected as globals.
|
|
16
99
|
* Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
|
|
100
|
+
*
|
|
101
|
+
* A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
|
|
102
|
+
* with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than
|
|
103
|
+
* `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.
|
|
17
104
|
*/
|
|
18
105
|
async function safeEval(expression, context, timeout) {
|
|
19
106
|
const runtime = await getRuntime();
|
|
20
107
|
const deadline = Date.now() + timeout;
|
|
21
|
-
|
|
108
|
+
let timedOut = false;
|
|
109
|
+
runtime.setInterruptHandler(() => {
|
|
110
|
+
if (Date.now() > deadline) timedOut = true;
|
|
111
|
+
return timedOut;
|
|
112
|
+
});
|
|
113
|
+
const timeoutMessage = `Evaluation timed out after ${timeout} ms`;
|
|
22
114
|
const vm = runtime.newContext();
|
|
115
|
+
/** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */
|
|
116
|
+
const takeThrown = (error) => {
|
|
117
|
+
const dumped = vm.dump(error);
|
|
118
|
+
if (error.alive) error.dispose();
|
|
119
|
+
return timedOut ? void 0 : parseThrown(dumped);
|
|
120
|
+
};
|
|
23
121
|
try {
|
|
24
122
|
const contextJson = JSON.stringify(context);
|
|
25
123
|
const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});
|
|
26
124
|
${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).join("\n")}`;
|
|
27
125
|
const setupResult = vm.evalCode(setup, "setup.js", { type: "global" });
|
|
28
126
|
if (setupResult.error) {
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
throw new
|
|
127
|
+
const thrown = takeThrown(setupResult.error);
|
|
128
|
+
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
129
|
+
throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
|
|
32
130
|
}
|
|
33
131
|
setupResult.value.dispose();
|
|
34
|
-
const result = vm.evalCode(`JSON.stringify((${expression}))`,
|
|
132
|
+
const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
|
|
35
133
|
if (result.error) {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
throw new
|
|
134
|
+
const thrown = takeThrown(result.error);
|
|
135
|
+
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
136
|
+
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : thrown.text, thrown.errorClass);
|
|
39
137
|
}
|
|
40
138
|
const json = vm.getString(result.value);
|
|
41
139
|
result.value.dispose();
|
|
@@ -45,6 +143,6 @@ ${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).j
|
|
|
45
143
|
vm.dispose();
|
|
46
144
|
}
|
|
47
145
|
}
|
|
48
|
-
export { safeEval };
|
|
146
|
+
export { SandboxError, THROWN_VALUE, TIMEOUT, errorClassOf, safeEval };
|
|
49
147
|
|
|
50
148
|
//# sourceMappingURL=sandbox.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout
|
|
1
|
+
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than\n * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + timeout;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${timeout} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n // Inject context variables via JSON\n const contextJson = JSON.stringify(context);\n const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});\n${Object.keys(context)\n .map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`)\n .join(\"\\n\")}`;\n const setupResult = vm.evalCode(setup, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);\n }\n setupResult.value.dispose();\n\n // Evaluate the expression\n const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n const json = vm.getString(result.value);\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n"],"mappings":"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"}
|
|
@@ -14,7 +14,11 @@ function registerScreenshotTool(server, ctx) {
|
|
|
14
14
|
const base64Png = await ctx.callbacks.captureScreenshot();
|
|
15
15
|
if (savePath) {
|
|
16
16
|
const absPath = (0, node_path.resolve)(savePath);
|
|
17
|
-
|
|
17
|
+
try {
|
|
18
|
+
await (0, node_fs_promises.writeFile)(absPath, Buffer.from(base64Png, "base64"), { flag: "wx" });
|
|
19
|
+
} catch (e) {
|
|
20
|
+
return saveFailedResult(e);
|
|
21
|
+
}
|
|
18
22
|
return { content: [{
|
|
19
23
|
type: "image",
|
|
20
24
|
data: base64Png,
|
|
@@ -31,6 +35,10 @@ function registerScreenshotTool(server, ctx) {
|
|
|
31
35
|
}] };
|
|
32
36
|
});
|
|
33
37
|
}
|
|
38
|
+
/** The result of a screenshot that could not be saved: the error of the file system, as it is. */
|
|
39
|
+
function saveFailedResult(error) {
|
|
40
|
+
return require_types.errorResult(`Could not save the screenshot: ${error instanceof Error ? error.message : String(error)}`, "Check that the folder exists and is writable and that no file exists at the path; the screenshot is not overwritten.");
|
|
41
|
+
}
|
|
34
42
|
exports.registerScreenshotTool = registerScreenshotTool;
|
|
35
43
|
|
|
36
44
|
//# sourceMappingURL=screenshot.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"screenshot.cjs","names":["hints","z","errorResult","resolve","writeFile"],"sources":["../../src/tools/screenshot.ts"],"sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport
|
|
1
|
+
{"version":3,"file":"screenshot.cjs","names":["hints","z","errorResult","resolve","writeFile"],"sources":["../../src/tools/screenshot.ts"],"sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints } from \"./types\";\n\nexport function registerScreenshotTool(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"capture_screenshot\",\n {\n title: \"Capture Screenshot\",\n annotations: hints.additive,\n description:\n \"Capture a screenshot of the current application window. Optionally save to a file.\",\n inputSchema: z.object({\n savePath: z\n .string()\n .optional()\n .describe(\n \"Absolute file path to save the screenshot as PNG. If omitted, returns the image inline only.\",\n ),\n }),\n },\n async ({ savePath }) => {\n if (!ctx.callbacks.captureScreenshot) {\n return errorResult(\n \"Screenshot capture is not available.\",\n \"Make sure the MCP server is running inside Platforma Desktop and MCP connected properly. If everything is fine check Electron logs with get_app_log\",\n );\n }\n const base64Png = await ctx.callbacks.captureScreenshot();\n\n if (savePath) {\n const absPath = resolve(savePath);\n try {\n await writeFile(absPath, Buffer.from(base64Png, \"base64\"), { flag: \"wx\" });\n } catch (e: unknown) {\n return saveFailedResult(e);\n }\n return {\n content: [\n { type: \"image\" as const, data: base64Png, mimeType: \"image/png\" },\n { type: \"text\" as const, text: `Screenshot saved to ${absPath}` },\n ],\n };\n }\n\n return {\n content: [{ type: \"image\" as const, data: base64Png, mimeType: \"image/png\" }],\n };\n },\n );\n}\n\n/** The result of a screenshot that could not be saved: the error of the file system, as it is. */\nfunction saveFailedResult(error: unknown) {\n return errorResult(\n `Could not save the screenshot: ${error instanceof Error ? error.message : String(error)}`,\n \"Check that the folder exists and is writable and that no file exists at the path; the screenshot is not overwritten.\",\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,uBAAuB,QAAuB,KAAwB;CACpF,OAAO,aACL,sBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;EACF,aAAaC,IAAAA,EAAE,OAAO,EACpB,UAAUA,IAAAA,EACP,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SACC,8FACF,EACJ,CAAC;CACH,GACA,OAAO,EAAE,eAAe;EACtB,IAAI,CAAC,IAAI,UAAU,mBACjB,OAAOC,cAAAA,YACL,wCACA,qJACF;EAEF,MAAM,YAAY,MAAM,IAAI,UAAU,kBAAkB;EAExD,IAAI,UAAU;GACZ,MAAM,WAAA,GAAUC,UAAAA,QAAAA,CAAQ,QAAQ;GAChC,IAAI;IACF,OAAA,GAAMC,iBAAAA,UAAAA,CAAU,SAAS,OAAO,KAAK,WAAW,QAAQ,GAAG,EAAE,MAAM,KAAK,CAAC;GAC3E,SAAS,GAAY;IACnB,OAAO,iBAAiB,CAAC;GAC3B;GACA,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAkB,MAAM;IAAW,UAAU;GAAY,GACjE;IAAE,MAAM;IAAiB,MAAM,uBAAuB;GAAU,CAClE,EACF;EACF;EAEA,OAAO,EACL,SAAS,CAAC;GAAE,MAAM;GAAkB,MAAM;GAAW,UAAU;EAAY,CAAC,EAC9E;CACF,CACF;AACF;;AAGA,SAAS,iBAAiB,OAAgB;CACxC,OAAOF,cAAAA,YACL,kCAAkC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KACvF,sHACF;AACF"}
|