@milaboratories/pl-mcp-server 52.1.0 → 53.1.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 +31 -0
- package/dist/instructions.cjs +2 -1
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +2 -1
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/server-log.cjs +365 -0
- package/dist/server-log.cjs.map +1 -0
- package/dist/server-log.js +363 -0
- package/dist/server-log.js.map +1 -0
- package/dist/server.cjs +49 -15
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +12 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +49 -15
- package/dist/server.js.map +1 -1
- package/dist/tools/await.cjs +4 -6
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +5 -7
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +23 -0
- package/dist/tools/block-api.cjs.map +1 -0
- package/dist/tools/block-api.js +22 -0
- package/dist/tools/block-api.js.map +1 -0
- package/dist/tools/block-params.cjs +21 -0
- package/dist/tools/block-params.cjs.map +1 -0
- package/dist/tools/block-params.js +21 -0
- package/dist/tools/block-params.js.map +1 -0
- package/dist/tools/block-state.cjs +2 -2
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +3 -3
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/blocks.cjs +78 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +78 -21
- 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 +1 -1
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +2 -2
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/logs.cjs.map +1 -1
- 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.map +1 -1
- 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 +5 -4
- package/src/instructions.ts +2 -1
- package/src/server-log.test.ts +859 -0
- package/src/server-log.ts +495 -0
- package/src/server.logging.test.ts +380 -0
- package/src/server.request-failure.test.ts +49 -0
- package/src/server.test.ts +4 -2
- package/src/server.ts +70 -15
- package/src/test/recording-logger.ts +33 -0
- package/src/tools/await.ts +7 -10
- package/src/tools/block-action-context.ts +2 -3
- package/src/tools/block-api.ts +24 -0
- package/src/tools/block-params.ts +29 -0
- package/src/tools/block-state.ts +5 -6
- package/src/tools/blocks.test.ts +148 -0
- package/src/tools/blocks.ts +162 -34
- package/src/tools/connection.ts +2 -3
- package/src/tools/data-query.ts +5 -6
- package/src/tools/logs.ts +2 -3
- package/src/tools/ping.ts +2 -3
- package/src/tools/projects.ts +2 -3
- 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 +65 -2
- package/src/tools/ui-interaction.ts +2 -3
|
@@ -179,7 +179,7 @@ function registerDataQueryTools(server, ctx) {
|
|
|
179
179
|
}, transformTimeout);
|
|
180
180
|
return require_types.textResult(result);
|
|
181
181
|
} catch (e) {
|
|
182
|
-
return require_types.
|
|
182
|
+
return require_types.transformFailedResult(e, "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.");
|
|
183
183
|
}
|
|
184
184
|
return require_types.textResult({
|
|
185
185
|
offset,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-query.cjs","names":["readAnnotation","Annotation","pTableValue","hints","z","projectIdInput","blockIdInput","errorResult","textResult","safeEval"],"sources":["../../src/tools/data-query.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/server\";\nimport type {\n PFrameHandle,\n PTableHandle,\n PTableColumnSpec,\n PTableVector,\n} from \"@milaboratories/pl-middle-layer\";\nimport {\n Annotation,\n pTableValue,\n readAnnotation,\n PFrameDriver,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext } from \"./types\";\nimport { safeEval } from \"./sandbox\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nconst HEX_HASH_RE = /^[a-f0-9]{64}$/;\n\n/**\n * Try to resolve a 64-char hex handle as PTable, then PFrame.\n * Returns a summary object or the original string if neither works.\n */\nasync function resolveHandle(\n handle: string,\n driver: PFrameDriver,\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (cache.has(handle)) return cache.get(handle);\n\n // Try PTable first (has rows — more useful info)\n try {\n const spec = await driver.getSpec(handle as PTableHandle);\n const shape = await driver.getShape(handle as PTableHandle);\n const summary: Record<string, unknown> = {\n _type: \"PTable\",\n handle,\n rows: shape.rows,\n columnCount: spec.length,\n columns: spec.slice(0, maxColumns).map((s: PTableColumnSpec, idx: number) => ({\n index: idx,\n type: s.type,\n name: s.spec.name,\n valueType: s.type === \"column\" ? s.spec.valueType : s.spec.type,\n label: readAnnotation(s.spec, Annotation.Label),\n })),\n };\n if (spec.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PTable\n }\n\n // Try PFrame\n try {\n const columns = await driver.listColumns(handle as PFrameHandle);\n const summary: Record<string, unknown> = {\n _type: \"PFrame\",\n handle,\n columnCount: columns.length,\n columns: columns.slice(0, maxColumns).map((c) => ({\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n })),\n };\n if (columns.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PFrame either\n }\n\n cache.set(handle, handle);\n return handle;\n}\n\n/**\n * Recursively walk a value tree, replacing 64-char hex handles\n * with PFrame/PTable summaries (column specs + row count).\n */\nasync function resolveHandlesInValue(\n value: unknown,\n driver: Parameters<typeof resolveHandle>[1],\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (value === null || value === undefined) return value;\n if (typeof value === \"string\") {\n return HEX_HASH_RE.test(value) ? resolveHandle(value, driver, maxColumns, cache) : value;\n }\n if (typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return Promise.all(value.map((v) => resolveHandlesInValue(v, driver, maxColumns, cache)));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = await resolveHandlesInValue(v, driver, maxColumns, cache);\n }\n return out;\n}\n\n/** Converts a PTableVector column to a JSON-serializable array using the SDK helper. */\nfunction vectorToJson(vector: PTableVector, rows: number): (string | number | null)[] {\n const result: (string | number | null)[] = [];\n for (let i = 0; i < rows; i++) {\n result.push(pTableValue(vector, i));\n }\n return result;\n}\n\nexport function registerDataQueryTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_outputs\",\n {\n title: \"Get Block Outputs\",\n annotations: hints.read,\n description:\n \"Get block output values as a JSON map. \" +\n \"PFrame/PTable handles are resolved inline to summaries with column specs and row counts. \" +\n \"Use this to discover block results and available data before querying tables.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n maxColumns: z\n .number()\n .optional()\n .default(30)\n .describe(\"Max columns to show per PFrame/PTable summary (default 30).\"),\n }),\n },\n async ({ projectId, blockId, maxColumns }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;\n const driver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const cache = new Map<string, unknown>();\n\n const result: Record<string, unknown> = {};\n for (const [key, output] of Object.entries(outputs)) {\n if (!output?.ok || output.value == null) {\n result[key] = { ok: output?.ok ?? false };\n continue;\n }\n result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);\n }\n\n return textResult(result);\n },\n );\n\n server.registerTool(\n \"list_columns\",\n {\n title: \"List Columns\",\n annotations: hints.read,\n description:\n \"List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.\",\n inputSchema: z.object({\n pFrameHandle: z\n .string()\n .describe(\"PFrame handle (64-char hex hash from get_block_outputs)\"),\n }),\n },\n async ({ pFrameHandle }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);\n return textResult(\n columns.map((c) => ({\n columnId: c.columnId,\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n visibility: readAnnotation(c.spec, Annotation.Table.Visibility),\n axes: c.spec.axesSpec.map((a) => ({\n name: a.name,\n type: a.type,\n label: readAnnotation(a, Annotation.Label),\n })),\n })),\n );\n },\n );\n\n server.registerTool(\n \"query_table\",\n {\n title: \"Query Table\",\n annotations: hints.read,\n description:\n \"Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. \" +\n \"Use `transform` to process results server-side and return only what you need.\",\n inputSchema: z.object({\n pTableHandle: z\n .string()\n .describe(\"PTable handle (64-char hex hash from get_block_outputs)\"),\n columns: z\n .array(z.number())\n .optional()\n .describe(\n \"Column indices to retrieve (default: all). Use get_block_outputs to see column indices.\",\n ),\n offset: z.number().optional().default(0).describe(\"Row offset (default 0)\"),\n limit: z.number().optional().default(50).describe(\"Number of rows to return (default 50).\"),\n maxLimit: z\n .number()\n .optional()\n .default(1000)\n .describe(\"Upper bound for limit (default 1000). Increase for large exports.\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against query results. \" +\n \"Available variables: `rows` (array of row arrays), `columns` (column headers), `offset`, `rowCount`. \" +\n \"Example: `rows.map(r => r[0])` — extract first column only.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(5000)\n .describe(\"Timeout in ms for transform evaluation (default 5000).\"),\n }),\n },\n async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const handle = pTableHandle as PTableHandle;\n\n let spec;\n try {\n spec = await pFrameDriver.getSpec(handle);\n } catch (err) {\n return textResult({ error: `getSpec failed: ${err}` });\n }\n\n const effectiveLimit = Math.min(limit, maxLimit);\n const range = { offset, length: effectiveLimit };\n\n // If no columns specified, get all\n const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);\n\n let vectors: PTableVector[];\n try {\n vectors = await pFrameDriver.getData(handle, columnIndices, range);\n } catch (err) {\n return textResult({\n error: `getData failed: ${err}`,\n columnIndices,\n range,\n });\n }\n\n const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;\n const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));\n const rows: unknown[][] = [];\n for (let r = 0; r < actualRows; r++) {\n rows.push(columnVectors.map((col) => col[r]));\n }\n\n const columnHeaders = columnIndices.map((idx: number) => {\n const s = spec[idx];\n return {\n index: idx,\n type: s.type,\n name: s.type === \"column\" ? s.spec.name : s.spec.name,\n label: readAnnotation(s.spec, Annotation.Label),\n };\n });\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n rows,\n columns: columnHeaders,\n offset,\n rowCount: actualRows,\n },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return errorResult(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`,\n \"Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.\",\n );\n }\n }\n\n return textResult({\n offset,\n rowCount: actualRows,\n columns: columnHeaders,\n rows,\n });\n },\n );\n}\n"],"mappings":";;;;;;AAmBA,MAAM,cAAc;;;;;AAMpB,eAAe,cACb,QACA,QACA,YACA,OACkB;CAClB,IAAI,MAAM,IAAI,MAAM,GAAG,OAAO,MAAM,IAAI,MAAM;CAG9C,IAAI;EACF,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAsB;EAExD,MAAM,UAAmC;GACvC,OAAO;GACP;GACA,OAAM,MAJY,OAAO,SAAS,MAAsB,EAAA,CAI5C;GACZ,aAAa,KAAK;GAClB,SAAS,KAAK,MAAM,GAAG,UAAU,CAAC,CAAC,KAAK,GAAqB,SAAiB;IAC5E,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,KAAK;IACb,WAAW,EAAE,SAAS,WAAW,EAAE,KAAK,YAAY,EAAE,KAAK;IAC3D,QAAA,GAAOA,gCAAAA,eAAAA,CAAe,EAAE,MAAMC,gCAAAA,WAAW,KAAK;GAChD,EAAE;EACJ;EACA,IAAI,KAAK,SAAS,YAAY;GAC5B,QAAQ,YAAY;GACpB,QAAQ,UAAU;EACpB;EACA,MAAM,IAAI,QAAQ,OAAO;EACzB,OAAO;CACT,QAAQ,CAER;CAGA,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,YAAY,MAAsB;EAC/D,MAAM,UAAmC;GACvC,OAAO;GACP;GACA,aAAa,QAAQ;GACrB,SAAS,QAAQ,MAAM,GAAG,UAAU,CAAC,CA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z","projectIdInput","blockIdInput","errorResult","textResult","safeEval","transformFailedResult"],"sources":["../../src/tools/data-query.ts"],"sourcesContent":["import type {\n PFrameHandle,\n PTableHandle,\n PTableColumnSpec,\n PTableVector,\n} from \"@milaboratories/pl-middle-layer\";\nimport {\n Annotation,\n pTableValue,\n readAnnotation,\n PFrameDriver,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { safeEval } from \"./sandbox\";\nimport { errorResult, hints, textResult, transformFailedResult } from \"./types\";\n\nconst HEX_HASH_RE = /^[a-f0-9]{64}$/;\n\n/**\n * Try to resolve a 64-char hex handle as PTable, then PFrame.\n * Returns a summary object or the original string if neither works.\n */\nasync function resolveHandle(\n handle: string,\n driver: PFrameDriver,\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (cache.has(handle)) return cache.get(handle);\n\n // Try PTable first (has rows — more useful info)\n try {\n const spec = await driver.getSpec(handle as PTableHandle);\n const shape = await driver.getShape(handle as PTableHandle);\n const summary: Record<string, unknown> = {\n _type: \"PTable\",\n handle,\n rows: shape.rows,\n columnCount: spec.length,\n columns: spec.slice(0, maxColumns).map((s: PTableColumnSpec, idx: number) => ({\n index: idx,\n type: s.type,\n name: s.spec.name,\n valueType: s.type === \"column\" ? s.spec.valueType : s.spec.type,\n label: readAnnotation(s.spec, Annotation.Label),\n })),\n };\n if (spec.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PTable\n }\n\n // Try PFrame\n try {\n const columns = await driver.listColumns(handle as PFrameHandle);\n const summary: Record<string, unknown> = {\n _type: \"PFrame\",\n handle,\n columnCount: columns.length,\n columns: columns.slice(0, maxColumns).map((c) => ({\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n })),\n };\n if (columns.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PFrame either\n }\n\n cache.set(handle, handle);\n return handle;\n}\n\n/**\n * Recursively walk a value tree, replacing 64-char hex handles\n * with PFrame/PTable summaries (column specs + row count).\n */\nasync function resolveHandlesInValue(\n value: unknown,\n driver: Parameters<typeof resolveHandle>[1],\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (value === null || value === undefined) return value;\n if (typeof value === \"string\") {\n return HEX_HASH_RE.test(value) ? resolveHandle(value, driver, maxColumns, cache) : value;\n }\n if (typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return Promise.all(value.map((v) => resolveHandlesInValue(v, driver, maxColumns, cache)));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = await resolveHandlesInValue(v, driver, maxColumns, cache);\n }\n return out;\n}\n\n/** Converts a PTableVector column to a JSON-serializable array using the SDK helper. */\nfunction vectorToJson(vector: PTableVector, rows: number): (string | number | null)[] {\n const result: (string | number | null)[] = [];\n for (let i = 0; i < rows; i++) {\n result.push(pTableValue(vector, i));\n }\n return result;\n}\n\nexport function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_outputs\",\n {\n title: \"Get Block Outputs\",\n annotations: hints.read,\n description:\n \"Get block output values as a JSON map. \" +\n \"PFrame/PTable handles are resolved inline to summaries with column specs and row counts. \" +\n \"Use this to discover block results and available data before querying tables.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n maxColumns: z\n .number()\n .optional()\n .default(30)\n .describe(\"Max columns to show per PFrame/PTable summary (default 30).\"),\n }),\n },\n async ({ projectId, blockId, maxColumns }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;\n const driver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const cache = new Map<string, unknown>();\n\n const result: Record<string, unknown> = {};\n for (const [key, output] of Object.entries(outputs)) {\n if (!output?.ok || output.value == null) {\n result[key] = { ok: output?.ok ?? false };\n continue;\n }\n result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);\n }\n\n return textResult(result);\n },\n );\n\n server.registerTool(\n \"list_columns\",\n {\n title: \"List Columns\",\n annotations: hints.read,\n description:\n \"List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.\",\n inputSchema: z.object({\n pFrameHandle: z\n .string()\n .describe(\"PFrame handle (64-char hex hash from get_block_outputs)\"),\n }),\n },\n async ({ pFrameHandle }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);\n return textResult(\n columns.map((c) => ({\n columnId: c.columnId,\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n visibility: readAnnotation(c.spec, Annotation.Table.Visibility),\n axes: c.spec.axesSpec.map((a) => ({\n name: a.name,\n type: a.type,\n label: readAnnotation(a, Annotation.Label),\n })),\n })),\n );\n },\n );\n\n server.registerTool(\n \"query_table\",\n {\n title: \"Query Table\",\n annotations: hints.read,\n description:\n \"Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. \" +\n \"Use `transform` to process results server-side and return only what you need.\",\n inputSchema: z.object({\n pTableHandle: z\n .string()\n .describe(\"PTable handle (64-char hex hash from get_block_outputs)\"),\n columns: z\n .array(z.number())\n .optional()\n .describe(\n \"Column indices to retrieve (default: all). Use get_block_outputs to see column indices.\",\n ),\n offset: z.number().optional().default(0).describe(\"Row offset (default 0)\"),\n limit: z.number().optional().default(50).describe(\"Number of rows to return (default 50).\"),\n maxLimit: z\n .number()\n .optional()\n .default(1000)\n .describe(\"Upper bound for limit (default 1000). Increase for large exports.\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against query results. \" +\n \"Available variables: `rows` (array of row arrays), `columns` (column headers), `offset`, `rowCount`. \" +\n \"Example: `rows.map(r => r[0])` — extract first column only.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(5000)\n .describe(\"Timeout in ms for transform evaluation (default 5000).\"),\n }),\n },\n async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const handle = pTableHandle as PTableHandle;\n\n let spec;\n try {\n spec = await pFrameDriver.getSpec(handle);\n } catch (err) {\n return textResult({ error: `getSpec failed: ${err}` });\n }\n\n const effectiveLimit = Math.min(limit, maxLimit);\n const range = { offset, length: effectiveLimit };\n\n // If no columns specified, get all\n const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);\n\n let vectors: PTableVector[];\n try {\n vectors = await pFrameDriver.getData(handle, columnIndices, range);\n } catch (err) {\n return textResult({\n error: `getData failed: ${err}`,\n columnIndices,\n range,\n });\n }\n\n const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;\n const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));\n const rows: unknown[][] = [];\n for (let r = 0; r < actualRows; r++) {\n rows.push(columnVectors.map((col) => col[r]));\n }\n\n const columnHeaders = columnIndices.map((idx: number) => {\n const s = spec[idx];\n return {\n index: idx,\n type: s.type,\n name: s.type === \"column\" ? s.spec.name : s.spec.name,\n label: readAnnotation(s.spec, Annotation.Label),\n };\n });\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n rows,\n columns: columnHeaders,\n offset,\n rowCount: actualRows,\n },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.\",\n );\n }\n }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GACF,CAAC;EACH;EAEA,MAAM,aAAa,QAAQ,SAAS,IAAI,QAAQ,EAAE,CAAC,KAAK,SAAS;EACjE,MAAM,gBAAgB,QAAQ,KAAK,MAAM,aAAa,GAAG,UAAU,CAAC;EACpE,MAAM,OAAoB,CAAC;EAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,YAAY,KAC9B,KAAK,KAAK,cAAc,KAAK,QAAQ,IAAI,EAAE,CAAC;EAG9C,MAAM,gBAAgB,cAAc,KAAK,QAAgB;GACvD,MAAM,IAAI,KAAK;GACf,OAAO;IACL,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,SAAS,WAAW,EAAE,KAAK,OAAO,EAAE,KAAK;IACjD,QAAA,GAAOR,gCAAAA,eAAAA,CAAe,EAAE,MAAMC,gCAAAA,WAAW,KAAK;GAChD;EACF,CAAC;EAED,IAAI,WACF,IAAI;GACF,MAAM,SAAS,MAAMQ,gBAAAA,SACnB,WACA;IACE;IACA,SAAS;IACT;IACA,UAAU;GACZ,GACA,gBACF;GACA,OAAOD,cAAAA,WAAW,MAAM;EAC1B,SAAS,GAAY;GACnB,OAAOE,cAAAA,sBACL,GACA,wFACF;EACF;EAGF,OAAOF,cAAAA,WAAW;GAChB;GACA,UAAU;GACV,SAAS;GACT;EACF,CAAC;CACH,CACF;AACF"}
|
package/dist/tools/data-query.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { errorResult, hints, textResult } from "./types.js";
|
|
1
|
+
import { errorResult, hints, textResult, transformFailedResult } from "./types.js";
|
|
2
2
|
import { blockIdInput, projectIdInput } from "./ids.js";
|
|
3
3
|
import { safeEval } from "./sandbox.js";
|
|
4
4
|
import { z } from "zod";
|
|
@@ -179,7 +179,7 @@ function registerDataQueryTools(server, ctx) {
|
|
|
179
179
|
}, transformTimeout);
|
|
180
180
|
return textResult(result);
|
|
181
181
|
} catch (e) {
|
|
182
|
-
return
|
|
182
|
+
return transformFailedResult(e, "Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.");
|
|
183
183
|
}
|
|
184
184
|
return textResult({
|
|
185
185
|
offset,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-query.js","names":[],"sources":["../../src/tools/data-query.ts"],"sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/server\";\nimport type {\n PFrameHandle,\n PTableHandle,\n PTableColumnSpec,\n PTableVector,\n} from \"@milaboratories/pl-middle-layer\";\nimport {\n Annotation,\n pTableValue,\n readAnnotation,\n PFrameDriver,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext } from \"./types\";\nimport { safeEval } from \"./sandbox\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nconst HEX_HASH_RE = /^[a-f0-9]{64}$/;\n\n/**\n * Try to resolve a 64-char hex handle as PTable, then PFrame.\n * Returns a summary object or the original string if neither works.\n */\nasync function resolveHandle(\n handle: string,\n driver: PFrameDriver,\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (cache.has(handle)) return cache.get(handle);\n\n // Try PTable first (has rows — more useful info)\n try {\n const spec = await driver.getSpec(handle as PTableHandle);\n const shape = await driver.getShape(handle as PTableHandle);\n const summary: Record<string, unknown> = {\n _type: \"PTable\",\n handle,\n rows: shape.rows,\n columnCount: spec.length,\n columns: spec.slice(0, maxColumns).map((s: PTableColumnSpec, idx: number) => ({\n index: idx,\n type: s.type,\n name: s.spec.name,\n valueType: s.type === \"column\" ? s.spec.valueType : s.spec.type,\n label: readAnnotation(s.spec, Annotation.Label),\n })),\n };\n if (spec.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PTable\n }\n\n // Try PFrame\n try {\n const columns = await driver.listColumns(handle as PFrameHandle);\n const summary: Record<string, unknown> = {\n _type: \"PFrame\",\n handle,\n columnCount: columns.length,\n columns: columns.slice(0, maxColumns).map((c) => ({\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n })),\n };\n if (columns.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PFrame either\n }\n\n cache.set(handle, handle);\n return handle;\n}\n\n/**\n * Recursively walk a value tree, replacing 64-char hex handles\n * with PFrame/PTable summaries (column specs + row count).\n */\nasync function resolveHandlesInValue(\n value: unknown,\n driver: Parameters<typeof resolveHandle>[1],\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (value === null || value === undefined) return value;\n if (typeof value === \"string\") {\n return HEX_HASH_RE.test(value) ? resolveHandle(value, driver, maxColumns, cache) : value;\n }\n if (typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return Promise.all(value.map((v) => resolveHandlesInValue(v, driver, maxColumns, cache)));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = await resolveHandlesInValue(v, driver, maxColumns, cache);\n }\n return out;\n}\n\n/** Converts a PTableVector column to a JSON-serializable array using the SDK helper. */\nfunction vectorToJson(vector: PTableVector, rows: number): (string | number | null)[] {\n const result: (string | number | null)[] = [];\n for (let i = 0; i < rows; i++) {\n result.push(pTableValue(vector, i));\n }\n return result;\n}\n\nexport function registerDataQueryTools(server: McpServer, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_outputs\",\n {\n title: \"Get Block Outputs\",\n annotations: hints.read,\n description:\n \"Get block output values as a JSON map. \" +\n \"PFrame/PTable handles are resolved inline to summaries with column specs and row counts. \" +\n \"Use this to discover block results and available data before querying tables.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n maxColumns: z\n .number()\n .optional()\n .default(30)\n .describe(\"Max columns to show per PFrame/PTable summary (default 30).\"),\n }),\n },\n async ({ projectId, blockId, maxColumns }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;\n const driver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const cache = new Map<string, unknown>();\n\n const result: Record<string, unknown> = {};\n for (const [key, output] of Object.entries(outputs)) {\n if (!output?.ok || output.value == null) {\n result[key] = { ok: output?.ok ?? false };\n continue;\n }\n result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);\n }\n\n return textResult(result);\n },\n );\n\n server.registerTool(\n \"list_columns\",\n {\n title: \"List Columns\",\n annotations: hints.read,\n description:\n \"List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.\",\n inputSchema: z.object({\n pFrameHandle: z\n .string()\n .describe(\"PFrame handle (64-char hex hash from get_block_outputs)\"),\n }),\n },\n async ({ pFrameHandle }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);\n return textResult(\n columns.map((c) => ({\n columnId: c.columnId,\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n visibility: readAnnotation(c.spec, Annotation.Table.Visibility),\n axes: c.spec.axesSpec.map((a) => ({\n name: a.name,\n type: a.type,\n label: readAnnotation(a, Annotation.Label),\n })),\n })),\n );\n },\n );\n\n server.registerTool(\n \"query_table\",\n {\n title: \"Query Table\",\n annotations: hints.read,\n description:\n \"Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. \" +\n \"Use `transform` to process results server-side and return only what you need.\",\n inputSchema: z.object({\n pTableHandle: z\n .string()\n .describe(\"PTable handle (64-char hex hash from get_block_outputs)\"),\n columns: z\n .array(z.number())\n .optional()\n .describe(\n \"Column indices to retrieve (default: all). Use get_block_outputs to see column indices.\",\n ),\n offset: z.number().optional().default(0).describe(\"Row offset (default 0)\"),\n limit: z.number().optional().default(50).describe(\"Number of rows to return (default 50).\"),\n maxLimit: z\n .number()\n .optional()\n .default(1000)\n .describe(\"Upper bound for limit (default 1000). Increase for large exports.\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against query results. \" +\n \"Available variables: `rows` (array of row arrays), `columns` (column headers), `offset`, `rowCount`. \" +\n \"Example: `rows.map(r => r[0])` — extract first column only.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(5000)\n .describe(\"Timeout in ms for transform evaluation (default 5000).\"),\n }),\n },\n async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const handle = pTableHandle as PTableHandle;\n\n let spec;\n try {\n spec = await pFrameDriver.getSpec(handle);\n } catch (err) {\n return textResult({ error: `getSpec failed: ${err}` });\n }\n\n const effectiveLimit = Math.min(limit, maxLimit);\n const range = { offset, length: effectiveLimit };\n\n // If no columns specified, get all\n const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);\n\n let vectors: PTableVector[];\n try {\n vectors = await pFrameDriver.getData(handle, columnIndices, range);\n } catch (err) {\n return textResult({\n error: `getData failed: ${err}`,\n columnIndices,\n range,\n });\n }\n\n const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;\n const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));\n const rows: unknown[][] = [];\n for (let r = 0; r < actualRows; r++) {\n rows.push(columnVectors.map((col) => col[r]));\n }\n\n const columnHeaders = columnIndices.map((idx: number) => {\n const s = spec[idx];\n return {\n index: idx,\n type: s.type,\n name: s.type === \"column\" ? s.spec.name : s.spec.name,\n label: readAnnotation(s.spec, Annotation.Label),\n };\n });\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n rows,\n columns: columnHeaders,\n offset,\n rowCount: actualRows,\n },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return errorResult(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`,\n \"Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.\",\n );\n }\n }\n\n return textResult({\n offset,\n rowCount: actualRows,\n columns: columnHeaders,\n rows,\n });\n },\n );\n}\n"],"mappings":";;;;;;AAmBA,MAAM,cAAc;;;;;AAMpB,eAAe,cACb,QACA,QACA,YACA,OACkB;CAClB,IAAI,MAAM,IAAI,MAAM,GAAG,OAAO,MAAM,IAAI,MAAM;CAG9C,IAAI;EACF,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAsB;EAExD,MAAM,UAAmC;GACvC,OAAO;GACP;GACA,OAAM,MAJY,OAAO,SAAS,MAAsB,EAAA,CAI5C;GACZ,aAAa,KAAK;GAClB,SAAS,KAAK,MAAM,GAAG,UAAU,CAAC,CAAC,KAAK,GAAqB,SAAiB;IAC5E,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,KAAK;IACb,WAAW,EAAE,SAAS,WAAW,EAAE,KAAK,YAAY,EAAE,KAAK;IAC3D,OAAO,eAAe,EAAE,MAAM,WAAW,KAAK;GAChD,EAAE;EACJ;EACA,IAAI,KAAK,SAAS,YAAY;GAC5B,QAAQ,YAAY;GACpB,QAAQ,UAAU;EACpB;EACA,MAAM,IAAI,QAAQ,OAAO;EACzB,OAAO;CACT,QAAQ,CAER;CAGA,IAAI;EACF,MAAM,UAAU,MAAM,OAAO,YAAY,MAAsB;EAC/D,MAAM,UAAmC;GACvC,OAAO;GACP;GACA,aAAa,QAAQ;GACrB,SAAS,QAAQ,MAAM,GAAG,UAAU,CAAC,CAAC,KAAK,OAAO;IAChD,MAAM,EAAE,KAAK;IACb,WAAW,EAAE,KAAK;IAClB,OAAO,eAAe,EAAE,MAAM,WAAW,KAAK;GAChD,EAAE;EACJ;EACA,IAAI,QAAQ,SAAS,YAAY;GAC/B,QAAQ,YAAY;GACpB,QAAQ,UAAU;EACpB;EACA,MAAM,IAAI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IAAI,EAAE,CAAC;EAG9C,MAAM,gBAAgB,cAAc,KAAK,QAAgB;GACvD,MAAM,IAAI,KAAK;GACf,OAAO;IACL,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,SAAS,WAAW,EAAE,KAAK,OAAO,EAAE,KAAK;IACjD,OAAO,eAAe,EAAE,MAAM,WAAW,KAAK;GAChD;EACF,CAAC;EAED,IAAI,WACF,IAAI;GACF,MAAM,SAAS,MAAM,SACnB,WACA;IACE;IACA,SAAS;IACT;IACA,UAAU;GACZ,GACA,gBACF;GACA,OAAO,WAAW,MAAM;EAC1B,SAAS,GAAY;GACnB,OAAO,YACL,qBAAqB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAC9D,wFACF;EACF;EAGF,OAAO,WAAW;GAChB;GACA,UAAU;GACV,SAAS;GACT;EACF,CAAC;CACH,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"data-query.js","names":[],"sources":["../../src/tools/data-query.ts"],"sourcesContent":["import type {\n PFrameHandle,\n PTableHandle,\n PTableColumnSpec,\n PTableVector,\n} from \"@milaboratories/pl-middle-layer\";\nimport {\n Annotation,\n pTableValue,\n readAnnotation,\n PFrameDriver,\n} from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { safeEval } from \"./sandbox\";\nimport { errorResult, hints, textResult, transformFailedResult } from \"./types\";\n\nconst HEX_HASH_RE = /^[a-f0-9]{64}$/;\n\n/**\n * Try to resolve a 64-char hex handle as PTable, then PFrame.\n * Returns a summary object or the original string if neither works.\n */\nasync function resolveHandle(\n handle: string,\n driver: PFrameDriver,\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (cache.has(handle)) return cache.get(handle);\n\n // Try PTable first (has rows — more useful info)\n try {\n const spec = await driver.getSpec(handle as PTableHandle);\n const shape = await driver.getShape(handle as PTableHandle);\n const summary: Record<string, unknown> = {\n _type: \"PTable\",\n handle,\n rows: shape.rows,\n columnCount: spec.length,\n columns: spec.slice(0, maxColumns).map((s: PTableColumnSpec, idx: number) => ({\n index: idx,\n type: s.type,\n name: s.spec.name,\n valueType: s.type === \"column\" ? s.spec.valueType : s.spec.type,\n label: readAnnotation(s.spec, Annotation.Label),\n })),\n };\n if (spec.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PTable\n }\n\n // Try PFrame\n try {\n const columns = await driver.listColumns(handle as PFrameHandle);\n const summary: Record<string, unknown> = {\n _type: \"PFrame\",\n handle,\n columnCount: columns.length,\n columns: columns.slice(0, maxColumns).map((c) => ({\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n })),\n };\n if (columns.length > maxColumns) {\n summary.truncated = true;\n summary.showing = maxColumns;\n }\n cache.set(handle, summary);\n return summary;\n } catch {\n // not a PFrame either\n }\n\n cache.set(handle, handle);\n return handle;\n}\n\n/**\n * Recursively walk a value tree, replacing 64-char hex handles\n * with PFrame/PTable summaries (column specs + row count).\n */\nasync function resolveHandlesInValue(\n value: unknown,\n driver: Parameters<typeof resolveHandle>[1],\n maxColumns: number,\n cache: Map<string, unknown>,\n): Promise<unknown> {\n if (value === null || value === undefined) return value;\n if (typeof value === \"string\") {\n return HEX_HASH_RE.test(value) ? resolveHandle(value, driver, maxColumns, cache) : value;\n }\n if (typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n return Promise.all(value.map((v) => resolveHandlesInValue(v, driver, maxColumns, cache)));\n }\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = await resolveHandlesInValue(v, driver, maxColumns, cache);\n }\n return out;\n}\n\n/** Converts a PTableVector column to a JSON-serializable array using the SDK helper. */\nfunction vectorToJson(vector: PTableVector, rows: number): (string | number | null)[] {\n const result: (string | number | null)[] = [];\n for (let i = 0; i < rows; i++) {\n result.push(pTableValue(vector, i));\n }\n return result;\n}\n\nexport function registerDataQueryTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_outputs\",\n {\n title: \"Get Block Outputs\",\n annotations: hints.read,\n description:\n \"Get block output values as a JSON map. \" +\n \"PFrame/PTable handles are resolved inline to summaries with column specs and row counts. \" +\n \"Use this to discover block results and available data before querying tables.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n maxColumns: z\n .number()\n .optional()\n .default(30)\n .describe(\"Max columns to show per PFrame/PTable summary (default 30).\"),\n }),\n },\n async ({ projectId, blockId, maxColumns }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n const outputs = state.outputs as Record<string, { ok?: boolean; value?: unknown }>;\n const driver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const cache = new Map<string, unknown>();\n\n const result: Record<string, unknown> = {};\n for (const [key, output] of Object.entries(outputs)) {\n if (!output?.ok || output.value == null) {\n result[key] = { ok: output?.ok ?? false };\n continue;\n }\n result[key] = await resolveHandlesInValue(output.value, driver, maxColumns, cache);\n }\n\n return textResult(result);\n },\n );\n\n server.registerTool(\n \"list_columns\",\n {\n title: \"List Columns\",\n annotations: hints.read,\n description:\n \"List all columns in a PFrame with their specs. Use get_block_outputs first to find the PFrame handle.\",\n inputSchema: z.object({\n pFrameHandle: z\n .string()\n .describe(\"PFrame handle (64-char hex hash from get_block_outputs)\"),\n }),\n },\n async ({ pFrameHandle }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const columns = await pFrameDriver.listColumns(pFrameHandle as PFrameHandle);\n return textResult(\n columns.map((c) => ({\n columnId: c.columnId,\n name: c.spec.name,\n valueType: c.spec.valueType,\n label: readAnnotation(c.spec, Annotation.Label),\n visibility: readAnnotation(c.spec, Annotation.Table.Visibility),\n axes: c.spec.axesSpec.map((a) => ({\n name: a.name,\n type: a.type,\n label: readAnnotation(a, Annotation.Label),\n })),\n })),\n );\n },\n );\n\n server.registerTool(\n \"query_table\",\n {\n title: \"Query Table\",\n annotations: hints.read,\n description:\n \"Query data from a PTable. Returns rows as arrays of values. Use get_block_outputs first to find the PTable handle. \" +\n \"Use `transform` to process results server-side and return only what you need.\",\n inputSchema: z.object({\n pTableHandle: z\n .string()\n .describe(\"PTable handle (64-char hex hash from get_block_outputs)\"),\n columns: z\n .array(z.number())\n .optional()\n .describe(\n \"Column indices to retrieve (default: all). Use get_block_outputs to see column indices.\",\n ),\n offset: z.number().optional().default(0).describe(\"Row offset (default 0)\"),\n limit: z.number().optional().default(50).describe(\"Number of rows to return (default 50).\"),\n maxLimit: z\n .number()\n .optional()\n .default(1000)\n .describe(\"Upper bound for limit (default 1000). Increase for large exports.\"),\n transform: z\n .string()\n .optional()\n .describe(\n \"JS expression evaluated server-side against query results. \" +\n \"Available variables: `rows` (array of row arrays), `columns` (column headers), `offset`, `rowCount`. \" +\n \"Example: `rows.map(r => r[0])` — extract first column only.\",\n ),\n transformTimeout: z\n .number()\n .optional()\n .default(5000)\n .describe(\"Timeout in ms for transform evaluation (default 5000).\"),\n }),\n },\n async ({ pTableHandle, columns, offset, limit, maxLimit, transform, transformTimeout }) => {\n const pFrameDriver = ctx.requireMl().internalDriverKit.pFrameDriver;\n const handle = pTableHandle as PTableHandle;\n\n let spec;\n try {\n spec = await pFrameDriver.getSpec(handle);\n } catch (err) {\n return textResult({ error: `getSpec failed: ${err}` });\n }\n\n const effectiveLimit = Math.min(limit, maxLimit);\n const range = { offset, length: effectiveLimit };\n\n // If no columns specified, get all\n const columnIndices = columns ?? spec.map((_: PTableColumnSpec, i: number) => i);\n\n let vectors: PTableVector[];\n try {\n vectors = await pFrameDriver.getData(handle, columnIndices, range);\n } catch (err) {\n return textResult({\n error: `getData failed: ${err}`,\n columnIndices,\n range,\n });\n }\n\n const actualRows = vectors.length > 0 ? vectors[0].data.length : 0;\n const columnVectors = vectors.map((v) => vectorToJson(v, actualRows));\n const rows: unknown[][] = [];\n for (let r = 0; r < actualRows; r++) {\n rows.push(columnVectors.map((col) => col[r]));\n }\n\n const columnHeaders = columnIndices.map((idx: number) => {\n const s = spec[idx];\n return {\n index: idx,\n type: s.type,\n name: s.type === \"column\" ? s.spec.name : s.spec.name,\n label: readAnnotation(s.spec, Annotation.Label),\n };\n });\n\n if (transform) {\n try {\n const result = await safeEval(\n transform,\n {\n rows,\n columns: columnHeaders,\n offset,\n rowCount: actualRows,\n },\n transformTimeout,\n );\n return textResult(result);\n } catch (e: unknown) {\n return transformFailedResult(\n e,\n \"Check your JS expression syntax. Available variables: rows, columns, offset, rowCount.\",\n );\n }\n }\n\n return textResult({\n offset,\n rowCount: actualRows,\n columns: columnHeaders,\n rows,\n });\n },\n );\n}\n"],"mappings":";;;;;;AAkBA,MAAM,cAAc;;;;;AAMpB,eAAe,cACb,QACA,QACA,YACA,OACkB;CAClB,IAAI,MAAM,IAAI,MAAM,GAAG,OAAO,MAAM,IAAI,MAAM;CAG9C,IAAI;EACF,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAsB;EAExD,MAAM,UAAmC;GACvC,OAAO;GACP;GACA,OAAM,MAJY,OAAO,SAAS,MAAsB,EAAA,CAI5C;GACZ,aAAa,KAAK;GAClB,SAAS,KAAK,MAAM,GAAG,UAAU,CAAC,CAAC,KAAK,GAAqB,SAAiB;IAC5E,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,KAAK;IACb,WAAW,EAAE,SAAS,WAAW,EAAE,KAAK,YAAY,EAAE,KAAK;IAC3D,OAAO,eAAe,EAAE,MAAM,WAAW,KAAK;GAChD,EAAE;EACJ;EACA,IAAI,KAAK,SAAS,YAAY;GAC5B,QAAQ,YAAY;GACpB,QAAQ,UAAU;EACpB;EACA,MAAM,IAAI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B,MAAc,CAAC;EAE/E,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,aAAa,QAAQ,QAAQ,eAAe,KAAK;EACnE,SAAS,KAAK;GACZ,OAAO,WAAW;IAChB,OAAO,mBAAmB;IAC1B;IACA;GACF,CAAC;EACH;EAEA,MAAM,aAAa,QAAQ,SAAS,IAAI,QAAQ,EAAE,CAAC,KAAK,SAAS;EACjE,MAAM,gBAAgB,QAAQ,KAAK,MAAM,aAAa,GAAG,UAAU,CAAC;EACpE,MAAM,OAAoB,CAAC;EAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,YAAY,KAC9B,KAAK,KAAK,cAAc,KAAK,QAAQ,IAAI,EAAE,CAAC;EAG9C,MAAM,gBAAgB,cAAc,KAAK,QAAgB;GACvD,MAAM,IAAI,KAAK;GACf,OAAO;IACL,OAAO;IACP,MAAM,EAAE;IACR,MAAM,EAAE,SAAS,WAAW,EAAE,KAAK,OAAO,EAAE,KAAK;IACjD,OAAO,eAAe,EAAE,MAAM,WAAW,KAAK;GAChD;EACF,CAAC;EAED,IAAI,WACF,IAAI;GACF,MAAM,SAAS,MAAM,SACnB,WACA;IACE;IACA,SAAS;IACT;IACA,UAAU;GACZ,GACA,gBACF;GACA,OAAO,WAAW,MAAM;EAC1B,SAAS,GAAY;GACnB,OAAO,sBACL,GACA,wFACF;EACF;EAGF,OAAO,WAAW;GAChB;GACA,UAAU;GACV,SAAS;GACT;EACF,CAAC;CACH,CACF;AACF"}
|
package/dist/tools/logs.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs.cjs","names":["hints","z","projectIdInput","blockIdInput","errorResult","isAnyLogHandle","textResult"],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"logs.cjs","names":["hints","z","projectIdInput","blockIdInput","errorResult","isAnyLogHandle","textResult"],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import { isAnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport type { AnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerLogTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_logs\",\n {\n title: \"Get Block Logs\",\n annotations: hints.read,\n description:\n \"Read execution logs for a block. Extracts log handles from block outputs and reads log content. Returns logs keyed by sample/run ID.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n lines: z.number().optional().default(100).describe(\"Number of lines per log (default 100)\"),\n sampleId: z\n .string()\n .optional()\n .describe(\"Specific sample/key to read logs for (reads all if omitted)\"),\n }),\n },\n async ({ projectId, blockId, lines, sampleId }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n // Scan all outputs for log handles (log+ready:// or log+live://)\n const outputs = state.outputs as Record<\n string,\n { ok?: boolean; value?: { data?: { key: string[]; value: unknown }[] } }\n >;\n const logEntries: { outputKey: string; key: string[]; handle: AnyLogHandle }[] = [];\n for (const [outputKey, output] of Object.entries(outputs)) {\n if (!output?.ok || !output.value?.data) continue;\n for (const entry of output.value.data) {\n if (isAnyLogHandle(entry.value)) {\n logEntries.push({ outputKey, key: entry.key, handle: entry.value });\n }\n }\n }\n\n if (logEntries.length === 0) {\n return errorResult(\n \"No log handles found in block outputs.\",\n \"This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.\",\n );\n }\n\n const logDriver = ctx.requireMl().driverKit.logDriver;\n const results: Record<string, string> = {};\n\n for (const entry of logEntries) {\n const key = entry.key.join(\"/\");\n if (sampleId && !entry.key.includes(sampleId)) continue;\n try {\n const response = await logDriver.lastLines(entry.handle, lines);\n if (response.shouldUpdateHandle) {\n results[key] = \"[log handle stale — block may still be running, retry later]\";\n } else {\n results[key] = new TextDecoder().decode(response.data);\n }\n } catch (err) {\n results[key] = `Error reading log: ${err}`;\n }\n }\n\n return textResult(results);\n },\n );\n\n server.registerTool(\n \"get_app_log\",\n {\n title: \"Get Application Log\",\n annotations: hints.read,\n description: \"Read recent lines from the application log. Useful for debugging errors.\",\n inputSchema: z.object({\n lines: z.number().optional().default(50).describe(\"Number of lines to return (default 50)\"),\n search: z.string().optional().describe(\"Filter lines containing this substring\"),\n }),\n },\n async ({ lines, search }) => {\n if (!ctx.callbacks.readAppLog) {\n return errorResult(\n \"App log reading is not available.\",\n \"This feature requires the desktop app integration.\",\n );\n }\n const log = await ctx.callbacks.readAppLog(lines, search);\n return textResult({ log });\n },\n );\n}\n"],"mappings":";;;;;AAOA,SAAgB,iBAAiB,QAAuB,KAAwB;CAC9E,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;EACF,aAAaC,IAAAA,EAAE,OAAO;GACpB,WAAWC,YAAAA,eAAe,SAAS,YAAY;GAC/C,SAASC,YAAAA,aAAa,SAAS,UAAU;GACzC,OAAOF,IAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,SAAS,uCAAuC;GAC1F,UAAUA,IAAAA,EACP,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,6DAA6D;EAC3E,CAAC;CACH,GACA,OAAO,EAAE,WAAW,SAAS,OAAO,eAAe;EAEjD,MAAM,QAAQ,OAAM,MADE,IAAI,iBAAiB,SAAS,EAAA,CACxB,cAAc,OAAO,CAAC,CAAC,SAAS;EAC5D,IAAI,CAAC,MAAM,SACT,OAAOG,cAAAA,YACL,6BACA,qHACF;EAGF,MAAM,UAAU,MAAM;EAItB,MAAM,aAA2E,CAAC;EAClF,KAAK,MAAM,CAAC,WAAW,WAAW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O,MAAM;EACxD,OAAOE,cAAAA,WAAW,EAAE,IAAI,CAAC;CAC3B,CACF;AACF"}
|
package/dist/tools/logs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs.js","names":[],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"logs.js","names":[],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import { isAnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport type { AnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerLogTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_logs\",\n {\n title: \"Get Block Logs\",\n annotations: hints.read,\n description:\n \"Read execution logs for a block. Extracts log handles from block outputs and reads log content. Returns logs keyed by sample/run ID.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n lines: z.number().optional().default(100).describe(\"Number of lines per log (default 100)\"),\n sampleId: z\n .string()\n .optional()\n .describe(\"Specific sample/key to read logs for (reads all if omitted)\"),\n }),\n },\n async ({ projectId, blockId, lines, sampleId }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n // Scan all outputs for log handles (log+ready:// or log+live://)\n const outputs = state.outputs as Record<\n string,\n { ok?: boolean; value?: { data?: { key: string[]; value: unknown }[] } }\n >;\n const logEntries: { outputKey: string; key: string[]; handle: AnyLogHandle }[] = [];\n for (const [outputKey, output] of Object.entries(outputs)) {\n if (!output?.ok || !output.value?.data) continue;\n for (const entry of output.value.data) {\n if (isAnyLogHandle(entry.value)) {\n logEntries.push({ outputKey, key: entry.key, handle: entry.value });\n }\n }\n }\n\n if (logEntries.length === 0) {\n return errorResult(\n \"No log handles found in block outputs.\",\n \"This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.\",\n );\n }\n\n const logDriver = ctx.requireMl().driverKit.logDriver;\n const results: Record<string, string> = {};\n\n for (const entry of logEntries) {\n const key = entry.key.join(\"/\");\n if (sampleId && !entry.key.includes(sampleId)) continue;\n try {\n const response = await logDriver.lastLines(entry.handle, lines);\n if (response.shouldUpdateHandle) {\n results[key] = \"[log handle stale — block may still be running, retry later]\";\n } else {\n results[key] = new TextDecoder().decode(response.data);\n }\n } catch (err) {\n results[key] = `Error reading log: ${err}`;\n }\n }\n\n return textResult(results);\n },\n );\n\n server.registerTool(\n \"get_app_log\",\n {\n title: \"Get Application Log\",\n annotations: hints.read,\n description: \"Read recent lines from the application log. Useful for debugging errors.\",\n inputSchema: z.object({\n lines: z.number().optional().default(50).describe(\"Number of lines to return (default 50)\"),\n search: z.string().optional().describe(\"Filter lines containing this substring\"),\n }),\n },\n async ({ lines, search }) => {\n if (!ctx.callbacks.readAppLog) {\n return errorResult(\n \"App log reading is not available.\",\n \"This feature requires the desktop app integration.\",\n );\n }\n const log = await ctx.callbacks.readAppLog(lines, search);\n return textResult({ log });\n },\n );\n}\n"],"mappings":";;;;;AAOA,SAAgB,iBAAiB,QAAuB,KAAwB;CAC9E,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EACF,aAAa,EAAE,OAAO;GACpB,WAAW,eAAe,SAAS,YAAY;GAC/C,SAAS,aAAa,SAAS,UAAU;GACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,SAAS,uCAAuC;GAC1F,UAAU,EACP,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,6DAA6D;EAC3E,CAAC;CACH,GACA,OAAO,EAAE,WAAW,SAAS,OAAO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AAwC;EACjF,CAAC;CACH,GACA,OAAO,EAAE,OAAO,aAAa;EAC3B,IAAI,CAAC,IAAI,UAAU,YACjB,OAAO,YACL,qCACA,oDACF;EAEF,MAAM,MAAM,MAAM,IAAI,UAAU,WAAW,OAAO,MAAM;EACxD,OAAO,WAAW,EAAE,IAAI,CAAC;CAC3B,CACF;AACF"}
|
package/dist/tools/ping.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.cjs","names":["hints","textResult"],"sources":["../../src/tools/ping.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"ping.cjs","names":["hints","textResult"],"sources":["../../src/tools/ping.ts"],"sourcesContent":["import type { ToolContext, ToolRegistrar } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerPingTool(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"ping\",\n {\n title: \"Ping\",\n annotations: hints.read,\n description:\n \"Check that the MCP server responds. Returns `connected`: whether the application is connected to a backend server. Needs no connection.\",\n },\n async () => {\n return textResult({ status: \"ok\", connected: !!ctx.getMl() });\n },\n );\n}\n"],"mappings":";;AAGA,SAAgB,iBAAiB,QAAuB,KAAwB;CAC9E,OAAO,aACL,QACA;EACE,OAAO;EACP,aAAaA,cAAAA,MAAM;EACnB,aACE;CACJ,GACA,YAAY;EACV,OAAOC,cAAAA,WAAW;GAAE,QAAQ;GAAM,WAAW,CAAC,CAAC,IAAI,MAAM;EAAE,CAAC;CAC9D,CACF;AACF"}
|
package/dist/tools/ping.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ping.js","names":[],"sources":["../../src/tools/ping.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"ping.js","names":[],"sources":["../../src/tools/ping.ts"],"sourcesContent":["import type { ToolContext, ToolRegistrar } from \"./types\";\nimport { hints, textResult } from \"./types\";\n\nexport function registerPingTool(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"ping\",\n {\n title: \"Ping\",\n annotations: hints.read,\n description:\n \"Check that the MCP server responds. Returns `connected`: whether the application is connected to a backend server. Needs no connection.\",\n },\n async () => {\n return textResult({ status: \"ok\", connected: !!ctx.getMl() });\n },\n );\n}\n"],"mappings":";;AAGA,SAAgB,iBAAiB,QAAuB,KAAwB;CAC9E,OAAO,aACL,QACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;CACJ,GACA,YAAY;EACV,OAAO,WAAW;GAAE,QAAQ;GAAM,WAAW,CAAC,CAAC,IAAI,MAAM;EAAE,CAAC;CAC9D,CACF;AACF"}
|
|
@@ -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"],"sources":["../../src/tools/projects.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { 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 status\",\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 opened: p.opened,\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:\n \"Create a new, empty project and return its ID. Call open_project before adding blocks to it.\",\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 \"open_project\",\n {\n title: \"Open Project\",\n annotations: hints.idempotent,\n description: \"Open a project for editing. Required before working with blocks.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID from list_projects or create_project\"),\n }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().openProject(entry.id);\n await ctx.callbacks.onProjectOpened?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"close_project\",\n {\n title: \"Close Project\",\n annotations: hints.idempotent,\n description:\n \"Close an opened project, releasing its resources in the application. Nothing is deleted.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().closeProject(entry.id);\n await ctx.callbacks.onProjectClosed?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description: \"Delete a project permanently. The project must be closed first.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().deleteProject(entry.id);\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;AAKA,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,QAAQ,EAAE;GACV,SAAS,EAAE,QAAQ,YAAY;GAC/B,cAAc,EAAE,aAAa,YAAY;EAC3C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,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,MAAM,IAAI,UAAU,CAAC,CAAC,cAAc,MAAM,EAAE;EAC5C,MAAM,IAAI,UAAU,mBAAmB,SAAS;EAChD,OAAOF,cAAAA,WAAW,EAAE,IAAI,KAAK,CAAC;CAChC,CACF;AACF"}
|
|
@@ -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 { z } from \"zod\";\nimport { projectIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { 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 status\",\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 opened: p.opened,\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:\n \"Create a new, empty project and return its ID. Call open_project before adding blocks to it.\",\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 \"open_project\",\n {\n title: \"Open Project\",\n annotations: hints.idempotent,\n description: \"Open a project for editing. Required before working with blocks.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID from list_projects or create_project\"),\n }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().openProject(entry.id);\n await ctx.callbacks.onProjectOpened?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"close_project\",\n {\n title: \"Close Project\",\n annotations: hints.idempotent,\n description:\n \"Close an opened project, releasing its resources in the application. Nothing is deleted.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().closeProject(entry.id);\n await ctx.callbacks.onProjectClosed?.(projectId);\n return textResult({ ok: true });\n },\n );\n\n server.registerTool(\n \"delete_project\",\n {\n title: \"Delete Project\",\n annotations: hints.destructive,\n description: \"Delete a project permanently. The project must be closed first.\",\n inputSchema: z.object({ projectId: projectIdInput.describe(\"Project ID\") }),\n },\n async ({ projectId }) => {\n const entry = await ctx.resolveProject(projectId);\n await ctx.requireMl().deleteProject(entry.id);\n await ctx.callbacks.onProjectDeleted?.(projectId);\n return textResult({ ok: true });\n },\n );\n}\n"],"mappings":";;;;AAKA,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,QAAQ,EAAE;GACV,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,aACE;EACF,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,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O,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":";;;AAGA,IAAI;AAEJ,eAAe,aAAsC;CACnD,IAAI,CAAC,eAAe;EAElB,iBAAgB,OAAA,GADMA,mBAAAA,WAAAA,CAAW,EAAA,CACT,WAAW;EACnC,cAAc,eAAe,QAAgB;EAC7C,cAAc,gBAAgB,MAAU;CAC1C;CACA,OAAO;AACT;;AAGA,MAAM,kBAAkB;AAExB,MAAM,yBACJ;;;;;AAMF,MAAM,kCAAuC,IAAI,IAAI;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAgB,aAAa,MAAsB;CACjD,OAAO,gBAAgB,IAAI,IAAI,IAAI,OAAO;AAC5C;;AAGA,MAAa,eAAe;;AAG5B,MAAa,UAAU;;;;;AAMvB,IAAa,eAAb,cAAkC,MAAM;;CAEtC;CAEA,YAAY,SAAiB,YAAoB;EAC/C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;;;;;;AAkBA,SAAS,YAAY,QAAyB;CAC5C,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,UAAU,UAAU,aAAa,QAAQ;EAC5F,MAAM,EAAE,MAAM,YAAY;EAC1B,IAAI,OAAO,SAAS,Y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