@executor-js/execution 1.4.31 → 1.4.33

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.
@@ -15,6 +15,47 @@ var withToolResultDefinitions = (definitions) => ({
15
15
  ...definitions ?? {},
16
16
  ToolError: TOOL_ERROR_TYPESCRIPT
17
17
  });
18
+ var BUILTIN_TOOL_DESCRIPTIONS = /* @__PURE__ */ new Map([
19
+ [
20
+ "search",
21
+ {
22
+ path: "search",
23
+ name: "search",
24
+ description: "Search available Executor tools.",
25
+ inputTypeScript: "{ query: string; namespace?: string; limit?: number; offset?: number; }",
26
+ outputTypeScript: "{ items: ToolDiscoveryResult[]; total: number; hasMore: boolean; nextOffset: number | null; }",
27
+ typeScriptDefinitions: {
28
+ ToolDiscoveryResult: "{ path: string; name: string; description?: string; sourceId: string; score: number; }"
29
+ }
30
+ }
31
+ ],
32
+ [
33
+ "executor.sources.list",
34
+ {
35
+ path: "executor.sources.list",
36
+ name: "executor.sources.list",
37
+ description: "List configured and built-in Executor sources.",
38
+ inputTypeScript: "{ query?: string; limit?: number; offset?: number; }",
39
+ outputTypeScript: "{ items: ExecutorSourceListItem[]; total: number; hasMore: boolean; nextOffset: number | null; }",
40
+ typeScriptDefinitions: {
41
+ ExecutorSourceListItem: "{ id: string; name: string; kind: string; runtime?: boolean; canRemove?: boolean; canRefresh?: boolean; toolCount: number; }"
42
+ }
43
+ }
44
+ ],
45
+ [
46
+ "describe.tool",
47
+ {
48
+ path: "describe.tool",
49
+ name: "describe.tool",
50
+ description: "Describe a tool's compact TypeScript input and output shapes.",
51
+ inputTypeScript: "{ path: string; }",
52
+ outputTypeScript: "DescribedTool",
53
+ typeScriptDefinitions: {
54
+ DescribedTool: "{ path: string; name: string; description?: string; inputTypeScript?: string; outputTypeScript?: string; typeScriptDefinitions?: { [k: string]: string; }; }"
55
+ }
56
+ }
57
+ ]
58
+ ]);
18
59
  var newCorrelationId = () => {
19
60
  return Math.floor(Math.random() * 4294967296).toString(16).padStart(8, "0");
20
61
  };
@@ -318,6 +359,8 @@ var listExecutorSources = Effect.fn("executor.sources.list")(function* (executor
318
359
  });
319
360
  var describeTool = Effect.fn("executor.tools.describe")(function* (executor, path) {
320
361
  yield* Effect.annotateCurrentSpan({ "mcp.tool.name": path });
362
+ const builtin = BUILTIN_TOOL_DESCRIPTIONS.get(path);
363
+ if (builtin) return builtin;
321
364
  const schema = yield* executor.tools.schema(path);
322
365
  if (schema === null) {
323
366
  return { path, name: path };
@@ -690,4 +733,4 @@ export {
690
733
  formatPausedExecution,
691
734
  createExecutionEngine
692
735
  };
693
- //# sourceMappingURL=chunk-OLPHXJSA.js.map
736
+ //# sourceMappingURL=chunk-NJPJNVEN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/tool-invoker.ts","../src/description.ts","../src/engine.ts"],"sourcesContent":["import * as Data from \"effect/Data\";\n\nexport class ExecutionToolError extends Data.TaggedError(\"ExecutionToolError\")<{\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n// `CodeExecutionError` lives in `@executor-js/codemode-core` — the `CodeExecutor`\n// interface uses it as the default error channel, so the runtime packages\n// can import the same class directly.\nexport { CodeExecutionError } from \"@executor-js/codemode-core\";\n","import { Effect, Predicate } from \"effect\";\nimport * as Cause from \"effect/Cause\";\nimport type {\n Executor,\n ToolId,\n Tool,\n ToolSchema,\n InvokeOptions,\n Source,\n} from \"@executor-js/sdk/core\";\nimport { isToolResult, ToolResult } from \"@executor-js/sdk/core\";\nimport type { SandboxToolInvoker } from \"@executor-js/codemode-core\";\nimport { ExecutionToolError } from \"./errors\";\n\nconst OPAQUE_DEFECT_MESSAGE = \"Internal tool error\";\nconst TOOL_ERROR_TYPESCRIPT =\n \"{ code: string; message: string; status?: number; details?: unknown; retryable?: boolean }\";\n\nconst wrapOutputTypeScript = (outputTypeScript?: string): string =>\n `{ ok: true; data: ${outputTypeScript ?? \"unknown\"} } | { ok: false; error: ToolError }`;\n\nconst withToolResultDefinitions = (\n definitions?: Record<string, string>,\n): Record<string, string> => ({\n ...(definitions ?? {}),\n ToolError: TOOL_ERROR_TYPESCRIPT,\n});\n\ntype DescribedTool = {\n readonly path: string;\n readonly name: string;\n readonly description?: string;\n readonly inputTypeScript?: string;\n readonly outputTypeScript?: string;\n readonly typeScriptDefinitions?: Record<string, string>;\n};\n\nconst BUILTIN_TOOL_DESCRIPTIONS: ReadonlyMap<string, DescribedTool> = new Map<\n string,\n DescribedTool\n>([\n [\n \"search\",\n {\n path: \"search\",\n name: \"search\",\n description: \"Search available Executor tools.\",\n inputTypeScript: \"{ query: string; namespace?: string; limit?: number; offset?: number; }\",\n outputTypeScript:\n \"{ items: ToolDiscoveryResult[]; total: number; hasMore: boolean; nextOffset: number | null; }\",\n typeScriptDefinitions: {\n ToolDiscoveryResult:\n \"{ path: string; name: string; description?: string; sourceId: string; score: number; }\",\n },\n },\n ],\n [\n \"executor.sources.list\",\n {\n path: \"executor.sources.list\",\n name: \"executor.sources.list\",\n description: \"List configured and built-in Executor sources.\",\n inputTypeScript: \"{ query?: string; limit?: number; offset?: number; }\",\n outputTypeScript:\n \"{ items: ExecutorSourceListItem[]; total: number; hasMore: boolean; nextOffset: number | null; }\",\n typeScriptDefinitions: {\n ExecutorSourceListItem:\n \"{ id: string; name: string; kind: string; runtime?: boolean; canRemove?: boolean; canRefresh?: boolean; toolCount: number; }\",\n },\n },\n ],\n [\n \"describe.tool\",\n {\n path: \"describe.tool\",\n name: \"describe.tool\",\n description: \"Describe a tool's compact TypeScript input and output shapes.\",\n inputTypeScript: \"{ path: string; }\",\n outputTypeScript: \"DescribedTool\",\n typeScriptDefinitions: {\n DescribedTool:\n \"{ path: string; name: string; description?: string; inputTypeScript?: string; outputTypeScript?: string; typeScriptDefinitions?: { [k: string]: string; }; }\",\n },\n },\n ],\n]);\n\nconst newCorrelationId = (): string => {\n // 8-hex-char correlation id; enough entropy to disambiguate within a\n // single deployment without leaking host process info.\n return Math.floor(Math.random() * 0x1_0000_0000)\n .toString(16)\n .padStart(8, \"0\");\n};\n\nconst validationIssues = (value: unknown): readonly unknown[] | null => {\n if (typeof value !== \"object\" || value === null) return null;\n const issues = (value as { readonly issues?: unknown }).issues;\n return Array.isArray(issues) ? issues : null;\n};\n\nconst expectedToolFailure = (\n value: unknown,\n): { readonly code: string; readonly message: string; readonly details?: unknown } | null => {\n if (Predicate.isTagged(value, \"ToolNotFoundError\") && \"toolId\" in value) {\n const suggestions =\n \"suggestions\" in value && Array.isArray(value.suggestions) ? value.suggestions : undefined;\n return {\n code: \"tool_not_found\",\n message: `Tool not found: ${String(value.toolId)}`,\n details: { toolId: value.toolId, ...(suggestions ? { suggestions } : {}) },\n };\n }\n if (Predicate.isTagged(value, \"ToolBlockedError\") && \"toolId\" in value) {\n return {\n code: \"tool_blocked\",\n message: `Tool blocked by policy: ${String(value.toolId)}`,\n details: value,\n };\n }\n if (Predicate.isTagged(value, \"ToolInvocationError\")) {\n const issues = validationIssues((value as { readonly cause?: unknown }).cause);\n if (issues) {\n return {\n code: \"invalid_tool_arguments\",\n message: \"Tool arguments did not match the input schema.\",\n details: { issues },\n };\n }\n }\n return null;\n};\n\n/**\n * Extract the source namespace from a tool path. Tool paths look like\n * \"<sourceId>.<op>\" or \"<sourceId>.<group>.<op>\" — we take the first\n * segment as a cheap, non-lookup stand-in for the source id so the span\n * attribute is always populated without hitting `executor.sources.list()`\n * per call.\n */\nconst extractSourceNamespace = (path: string): string => {\n const idx = path.indexOf(\".\");\n return idx === -1 ? path : path.slice(0, idx);\n};\n\n/**\n * Bridges QuickJS `tools.someSource.someOp(args)` calls into\n * `executor.tools.invoke(toolId, args)`.\n *\n * Wrapped in `Effect.fn(\"mcp.tool.dispatch\")` so every tool call becomes a\n * span in the Effect tracer. Attributes:\n * - `mcp.tool.name` — full tool path (e.g. \"github.repos.get\")\n * - `mcp.tool.source_id` — first segment of the path (namespace)\n *\n * `mcp.tool.kind` (openapi | mcp | graphql | code) is NOT annotated here\n * because it would require a `sources.list()` lookup on every invocation.\n * Callers that already know the source kind can annotate at their own span.\n */\nexport const makeExecutorToolInvoker = (\n executor: Executor,\n options: { readonly invokeOptions: InvokeOptions },\n): SandboxToolInvoker => ({\n invoke: Effect.fn(\"mcp.tool.dispatch\")(function* ({ path, args }) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.tool.name\": path,\n \"mcp.tool.source_id\": extractSourceNamespace(path),\n });\n\n const result = yield* executor.tools.invoke(path as ToolId, args, options.invokeOptions).pipe(\n Effect.catchCause((cause) => {\n const err = cause.reasons.find(Cause.isFailReason)?.error;\n const expected = expectedToolFailure(err);\n if (expected) {\n return Effect.succeed(ToolResult.fail(expected));\n }\n if (isElicitationDeclinedError(err)) {\n return Effect.fail(\n new ExecutionToolError({\n message: `Tool \"${err.toolId}\" requires approval but the request was ${err.action === \"cancel\" ? \"cancelled\" : \"declined\"} by the user.`,\n cause: err,\n }),\n );\n }\n // Any other failure here is an infra/plugin defect. Emit an\n // opaque generic with a correlation id so internal context (URLs\n // with tokens, DB connection strings, file paths in stacks)\n // can't leak through Error.message into the sandbox. The full\n // cause is logged with the same correlation id so operators can\n // still trace the failure.\n const correlationId = newCorrelationId();\n return Effect.logError(\"tool dispatch failed\", cause).pipe(\n Effect.annotateLogs({\n \"executor.correlation_id\": correlationId,\n \"mcp.tool.name\": path,\n }),\n Effect.flatMap(() =>\n Effect.fail(\n new ExecutionToolError({\n message: `${OPAQUE_DEFECT_MESSAGE} [${correlationId}]`,\n cause: err ?? cause,\n }),\n ),\n ),\n );\n }),\n );\n\n // Strict: plugins emit ToolResult<T>. Anything else is treated as a\n // raw success value and wrapped — keeps the sandbox-facing contract\n // uniform without forcing every tiny test plugin to import\n // `ToolResult.ok`.\n if (isToolResult(result)) {\n return result;\n }\n return { ok: true, data: result };\n }),\n});\n\nconst isElicitationDeclinedError = (\n value: unknown,\n): value is {\n readonly _tag: \"ElicitationDeclinedError\";\n readonly toolId: string;\n readonly action: \"cancel\" | \"decline\";\n} =>\n Predicate.isTagged(value, \"ElicitationDeclinedError\") &&\n value !== null &&\n typeof value === \"object\" &&\n \"toolId\" in value &&\n typeof value.toolId === \"string\" &&\n \"action\" in value &&\n (value.action === \"cancel\" || value.action === \"decline\");\n\nexport type ToolDiscoveryResult = {\n readonly path: string;\n readonly name: string;\n readonly description?: string;\n readonly sourceId: string;\n readonly score: number;\n};\n\nexport type ExecutorSourceListItem = {\n readonly id: string;\n readonly name: string;\n readonly kind: string;\n readonly runtime?: boolean;\n readonly canRemove?: boolean;\n readonly canRefresh?: boolean;\n readonly toolCount: number;\n};\n\n/**\n * Page of results from a list-style discovery tool. Shared by\n * `tools.search` and `tools.executor.sources.list` so the model sees one\n * consistent shape:\n *\n * - `items` — the page (slice).\n * - `total` — count after filtering, before pagination. The model\n * can use this to detect truncation.\n * - `hasMore` — convenience flag for `(offset + items.length) < total`.\n * - `nextOffset` — concrete offset for the next page when `hasMore`,\n * `null` otherwise. Pre-computing it removes a class of\n * off-by-one mistakes when the model paginates.\n */\nexport type PagedResult<T> = {\n readonly items: readonly T[];\n readonly total: number;\n readonly hasMore: boolean;\n readonly nextOffset: number | null;\n};\n\nconst paginate = <T>(all: readonly T[], offset: number, limit: number): PagedResult<T> => {\n const total = all.length;\n const start = Math.min(Math.max(offset, 0), total);\n const items = all.slice(start, start + limit);\n const consumed = start + items.length;\n const hasMore = consumed < total;\n return {\n items,\n total,\n hasMore,\n nextOffset: hasMore ? consumed : null,\n };\n};\n\ntype SearchableTool = Pick<Tool, \"id\" | \"sourceId\" | \"name\" | \"description\">;\n\ntype PreparedField = {\n readonly raw: string;\n readonly tokens: readonly string[];\n};\n\nconst SEARCH_FIELD_WEIGHTS = {\n path: 12,\n sourceId: 8,\n name: 10,\n description: 5,\n} as const;\n\nconst normalizeSearchText = (value: string): string =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_./:-]+/g, \" \")\n .toLowerCase()\n .trim();\n\nconst tokenizeSearchText = (value: string): string[] =>\n normalizeSearchText(value)\n .split(/[^a-z0-9]+/)\n .map((token) => token.trim())\n .filter(Boolean);\n\nconst prepareField = (value?: string): PreparedField => ({\n raw: normalizeSearchText(value ?? \"\"),\n tokens: tokenizeSearchText(value ?? \"\"),\n});\n\nconst scorePreparedField = (\n query: string,\n queryTokens: readonly string[],\n field: PreparedField,\n weight: number,\n): {\n readonly score: number;\n readonly matchedTokens: ReadonlySet<string>;\n readonly exactPhraseMatch: boolean;\n} => {\n if (field.raw.length === 0) {\n return {\n score: 0,\n matchedTokens: new Set<string>(),\n exactPhraseMatch: false,\n };\n }\n\n let score = 0;\n const matchedTokens = new Set<string>();\n const exactPhraseMatch = query.length > 0 && field.raw.includes(query);\n\n if (query.length > 0) {\n if (field.raw === query) {\n score += weight * 14;\n } else if (field.raw.startsWith(query)) {\n score += weight * 9;\n } else if (exactPhraseMatch) {\n score += weight * 6;\n }\n }\n\n for (const token of queryTokens) {\n if (field.tokens.includes(token)) {\n score += weight * 4;\n matchedTokens.add(token);\n continue;\n }\n\n if (\n field.tokens.some((candidate) => candidate.startsWith(token) || token.startsWith(candidate))\n ) {\n score += weight * 2;\n matchedTokens.add(token);\n continue;\n }\n\n if (field.raw.includes(token)) {\n score += weight;\n matchedTokens.add(token);\n }\n }\n\n return {\n score,\n matchedTokens,\n exactPhraseMatch,\n };\n};\n\nconst matchesNamespace = (tool: SearchableTool, namespace?: string): boolean => {\n if (!namespace || normalizeSearchText(namespace).length === 0) {\n return true;\n }\n\n const namespaceTokens = tokenizeSearchText(namespace);\n if (namespaceTokens.length === 0) {\n return true;\n }\n\n const sourceTokens = tokenizeSearchText(tool.sourceId);\n const pathTokens = tokenizeSearchText(tool.id);\n\n const isPrefixMatch = (tokens: readonly string[]): boolean =>\n namespaceTokens.every((token, index) => tokens[index] === token);\n\n return isPrefixMatch(sourceTokens) || isPrefixMatch(pathTokens);\n};\n\nconst scoreToolMatch = (tool: SearchableTool, query: string): ToolDiscoveryResult | null => {\n const normalizedQuery = normalizeSearchText(query);\n const queryTokens = tokenizeSearchText(query);\n\n if (normalizedQuery.length === 0 || queryTokens.length === 0) {\n return null;\n }\n\n const path = prepareField(tool.id);\n const sourceId = prepareField(tool.sourceId);\n const name = prepareField(tool.name);\n const description = prepareField(tool.description);\n\n const fieldScores = [\n scorePreparedField(normalizedQuery, queryTokens, path, SEARCH_FIELD_WEIGHTS.path),\n scorePreparedField(normalizedQuery, queryTokens, sourceId, SEARCH_FIELD_WEIGHTS.sourceId),\n scorePreparedField(normalizedQuery, queryTokens, name, SEARCH_FIELD_WEIGHTS.name),\n scorePreparedField(normalizedQuery, queryTokens, description, SEARCH_FIELD_WEIGHTS.description),\n ];\n\n const matchedTokens = new Set<string>();\n let score = 0;\n let exactPhraseMatch = false;\n\n for (const fieldScore of fieldScores) {\n score += fieldScore.score;\n exactPhraseMatch ||= fieldScore.exactPhraseMatch;\n for (const token of fieldScore.matchedTokens) {\n matchedTokens.add(token);\n }\n }\n\n if (matchedTokens.size === 0) {\n return null;\n }\n\n const coverage = matchedTokens.size / queryTokens.length;\n const minimumCoverage = queryTokens.length <= 2 ? 1 : 0.6;\n\n if (coverage < minimumCoverage && !exactPhraseMatch) {\n return null;\n }\n\n if (coverage === 1) {\n score += 25;\n } else {\n score += Math.round(coverage * 10);\n }\n\n if (path.tokens[0] === queryTokens[0] || name.tokens[0] === queryTokens[0]) {\n score += 8;\n }\n\n if (\n normalizeSearchText(tool.id) === normalizedQuery ||\n normalizeSearchText(tool.name) === normalizedQuery\n ) {\n score += 20;\n }\n\n return {\n path: tool.id,\n name: tool.name,\n description: tool.description,\n sourceId: tool.sourceId,\n score,\n };\n};\n\n/** What `tools.search()` calls inside the sandbox. */\nexport const searchTools = Effect.fn(\"executor.tools.search\")(function* (\n executor: Executor,\n query: string,\n limit = 12,\n options?: { readonly namespace?: string; readonly offset?: number },\n) {\n const offset = options?.offset ?? 0;\n yield* Effect.annotateCurrentSpan({\n \"executor.search.query_length\": query.length,\n \"executor.search.limit\": limit,\n \"executor.search.offset\": offset,\n ...(options?.namespace ? { \"executor.search.namespace\": options.namespace } : {}),\n });\n\n const empty: PagedResult<ToolDiscoveryResult> = {\n items: [],\n total: 0,\n hasMore: false,\n nextOffset: null,\n };\n\n if (normalizeSearchText(query).length === 0) {\n return empty;\n }\n\n const all = yield* executor.tools.list({ includeAnnotations: false }).pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list tools for search\",\n cause,\n }),\n ),\n );\n const ranked = all\n .filter((tool: Tool) => matchesNamespace(tool, options?.namespace))\n .map((tool: Tool) => scoreToolMatch(tool, query))\n .filter(Predicate.isNotNull)\n .sort((left, right) => right.score - left.score || left.path.localeCompare(right.path));\n\n const page = paginate(ranked, offset, limit);\n\n yield* Effect.annotateCurrentSpan({\n \"executor.search.candidate_count\": all.length,\n \"executor.search.match_count\": ranked.length,\n \"executor.search.result_count\": page.items.length,\n \"executor.search.has_more\": page.hasMore,\n });\n return page;\n});\n\n/** What `tools.executor.sources.list()` calls inside the sandbox. */\nexport const listExecutorSources = Effect.fn(\"executor.sources.list\")(function* (\n executor: Executor,\n options?: {\n readonly query?: string;\n readonly limit?: number;\n readonly offset?: number;\n },\n) {\n const normalizedQuery = normalizeSearchText(options?.query ?? \"\");\n const limit = options?.limit ?? 50;\n const offset = options?.offset ?? 0;\n const sources = yield* executor.sources.list().pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list executor sources\",\n cause,\n }),\n ),\n );\n\n const filtered =\n normalizedQuery.length === 0\n ? sources\n : sources.filter((source: Source) => {\n const haystack = normalizeSearchText([source.id, source.name, source.kind].join(\" \"));\n return tokenizeSearchText(normalizedQuery).every((token) => haystack.includes(token));\n });\n\n // Single query for all tools, then count per source in memory.\n const allTools = yield* executor.tools.list({ includeAnnotations: false }).pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list tools for source counts\",\n cause,\n }),\n ),\n );\n const toolCountBySource = new Map<string, number>();\n for (const tool of allTools) {\n toolCountBySource.set(tool.sourceId, (toolCountBySource.get(tool.sourceId) ?? 0) + 1);\n }\n\n const sortedWithCounts = filtered\n .map(\n (source: Source) =>\n ({\n id: source.id,\n name: source.name,\n kind: source.kind,\n runtime: source.runtime,\n canRemove: source.canRemove,\n canRefresh: source.canRefresh,\n toolCount: toolCountBySource.get(source.id) ?? 0,\n }) satisfies ExecutorSourceListItem,\n )\n .sort((left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id));\n\n const page = paginate(sortedWithCounts, offset, limit);\n\n yield* Effect.annotateCurrentSpan({\n \"executor.sources.candidate_count\": sources.length,\n \"executor.sources.match_count\": sortedWithCounts.length,\n \"executor.sources.result_count\": page.items.length,\n \"executor.sources.has_more\": page.hasMore,\n });\n return page;\n});\n\n/** What `tools.describe.tool()` calls inside the sandbox. */\nexport const describeTool = Effect.fn(\"executor.tools.describe\")(function* (\n executor: Executor,\n path: string,\n) {\n yield* Effect.annotateCurrentSpan({ \"mcp.tool.name\": path });\n\n const builtin = BUILTIN_TOOL_DESCRIPTIONS.get(path);\n if (builtin) return builtin;\n\n // Single tools.schema() call — it already fetches the tool row\n // internally. No need to also call tools.list() just for name/description.\n const schema: ToolSchema | null = yield* executor.tools.schema(path);\n\n // tools.schema() returns null if the tool doesn't exist. Fall back to\n // a minimal stub so callers can still render something.\n if (schema === null) {\n return { path, name: path };\n }\n\n // The schema's id is the tool path; name/description come from the\n // tool row which tools.schema() already loaded.\n return {\n path,\n name: schema.name ?? path,\n description: schema.description,\n inputTypeScript: schema.inputTypeScript,\n outputTypeScript: wrapOutputTypeScript(schema.outputTypeScript),\n typeScriptDefinitions: withToolResultDefinitions(schema.typeScriptDefinitions),\n };\n});\n","import { Effect } from \"effect\";\nimport type { Executor, Source } from \"@executor-js/sdk/core\";\n\n/**\n * Builds a tool description dynamically.\n *\n * Structure:\n * 1. Workflow (top — critical, least likely to be truncated)\n * 2. Available namespaces (bottom)\n */\nexport const buildExecuteDescription = (executor: Executor): Effect.Effect<string> =>\n Effect.gen(function* () {\n const sources: readonly Source[] = yield* executor.sources.list().pipe(\n // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: ExecutionEngine.getDescription currently exposes no error channel; engine typed-error widening is covered separately\n Effect.orDie,\n Effect.withSpan(\"executor.sources.list\"),\n );\n\n const description = yield* Effect.sync(() => formatDescription(sources)).pipe(\n Effect.withSpan(\"schema.compile.description\", {\n attributes: { \"executor.source_count\": sources.length },\n }),\n );\n\n yield* Effect.annotateCurrentSpan({\n \"executor.source_count\": sources.length,\n \"schema.kind\": \"execute\",\n });\n\n return description;\n }).pipe(Effect.withSpan(\"schema.describe.execute\"));\n\nconst formatDescription = (sources: readonly Source[]): string => {\n const lines: string[] = [\n \"Execute TypeScript in a sandboxed runtime with access to configured API tools.\",\n \"\",\n \"## Workflow\",\n \"\",\n '1. `const { items: matches } = await tools.search({ query: \"<intent + key nouns>\", limit: 12 });`',\n '2. `const path = matches[0]?.path; if (!path) return \"No matching tools found.\";`',\n \"3. `const details = await tools.describe.tool({ path });`\",\n \"4. Use `details.inputTypeScript` / `details.outputTypeScript` and `details.typeScriptDefinitions` for compact shapes.\",\n \"5. Use `tools.executor.sources.list()` when you need configured source inventory.\",\n \"6. Call the tool: `const result = await tools.<path>(input);`\",\n \"\",\n \"## Rules\",\n \"\",\n \"- `tools.search()` returns paginated, ranked matches: `{ items, total, hasMore, nextOffset }`. Best-first. Use short intent phrases like `github issues`, `repo details`, or `create calendar event`.\",\n '- When you already know the namespace, narrow with `tools.search({ namespace: \"github\", query: \"issues\" })`.',\n \"- `tools.executor.sources.list()` returns the same paged shape: `{ items: [{ id, toolCount, ... }], total, hasMore, nextOffset }`.\",\n \"- Tool calls return a value union: `{ ok: true, data }` for success or `{ ok: false, error: { code, message, status?, details?, retryable? } }` for expected tool/domain failures. Branch on `result.ok`.\",\n \"- If `hasMore` is true and you didn't find what you need, fetch the next page: `tools.search({ query, offset: nextOffset, limit })`. Same `offset` parameter on `tools.executor.sources.list({ offset, limit })`.\",\n \"- Always use the namespace prefix when calling tools: `tools.<namespace>.<tool>(args)`. Example: `tools.home_assistant_rest_api.states.getState(...)` — not `tools.states.getState(...)`.\",\n \"- The `tools` object is a lazy proxy — `Object.keys(tools)` won't work. Use `tools.search()` or `tools.executor.sources.list()` instead.\",\n '- Pass an object to system tools, e.g. `tools.search({ query: \"...\" })`, `tools.executor.sources.list()`, and `tools.describe.tool({ path })`.',\n \"- `tools.describe.tool()` returns compact TypeScript shapes. Use `inputTypeScript`, `outputTypeScript`, and `typeScriptDefinitions`.\",\n \"- For tools that return large collections (e.g. `getStates`, `getAll`), filter results in code rather than calling per-item tools.\",\n \"- Do not use `fetch` — all API calls go through `tools.*`.\",\n \"- If execution pauses for interaction, resume it with the returned `resumePayload`.\",\n \"- TypeScript type syntax (`: T`, `as T`, generics, interfaces, type aliases) is stripped before execution — feel free to write idiomatic TypeScript using the shapes from `tools.describe.tool()`. Decorators and `enum` are not supported.\",\n ];\n\n if (sources.length > 0) {\n lines.push(\"\");\n lines.push(\"## Available namespaces\");\n lines.push(\"\");\n const sorted = [...sources].sort((a, b) => a.id.localeCompare(b.id)).slice(0, 50);\n for (const source of sorted) {\n lines.push(`- \\`${source.id}\\``);\n }\n if (sources.length > sorted.length) {\n lines.push(`- ... ${sources.length - sorted.length} more`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { Deferred, Effect, Fiber, Predicate, Queue } from \"effect\";\nimport type * as Cause from \"effect/Cause\";\n\nimport type {\n Executor,\n InvokeOptions,\n ElicitationResponse,\n ElicitationHandler,\n ElicitationContext,\n} from \"@executor-js/sdk/core\";\nimport { CodeExecutionError } from \"@executor-js/codemode-core\";\nimport type { CodeExecutor, ExecuteResult, SandboxToolInvoker } from \"@executor-js/codemode-core\";\n\nimport {\n makeExecutorToolInvoker,\n searchTools,\n listExecutorSources,\n describeTool,\n} from \"./tool-invoker\";\nimport { ExecutionToolError } from \"./errors\";\nimport { buildExecuteDescription } from \"./description\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ExecutionEngineConfig<E extends Cause.YieldableError = CodeExecutionError> = {\n readonly executor: Executor;\n readonly codeExecutor: CodeExecutor<E>;\n};\n\nexport type ExecutionResult =\n | { readonly status: \"completed\"; readonly result: ExecuteResult }\n | { readonly status: \"paused\"; readonly execution: PausedExecution };\n\nexport type PausedExecution = {\n readonly id: string;\n readonly elicitationContext: ElicitationContext;\n};\n\n/** Internal representation with Effect runtime state for pause/resume. */\ntype InternalPausedExecution<E> = PausedExecution & {\n readonly response: Deferred.Deferred<typeof ElicitationResponse.Type>;\n readonly fiber: Fiber.Fiber<ExecuteResult, E>;\n readonly pauseQueue: Queue.Queue<InternalPausedExecution<E>>;\n};\n\nexport type ResumeResponse = {\n readonly action: \"accept\" | \"decline\" | \"cancel\";\n readonly content?: Record<string, unknown>;\n};\n\n// ---------------------------------------------------------------------------\n// Result formatting\n// ---------------------------------------------------------------------------\n\nconst MAX_PREVIEW_CHARS = 30_000;\n\nconst truncate = (value: string, max: number): string =>\n value.length > max\n ? `${value.slice(0, max)}\\n... [truncated ${value.length - max} chars]`\n : value;\n\nexport const formatExecuteResult = (\n result: ExecuteResult,\n): {\n text: string;\n structured: Record<string, unknown>;\n isError: boolean;\n} => {\n const resultText =\n result.result != null\n ? typeof result.result === \"string\"\n ? result.result\n : JSON.stringify(result.result, null, 2)\n : null;\n\n const logText = result.logs && result.logs.length > 0 ? result.logs.join(\"\\n\") : null;\n\n if (result.error) {\n const parts = [`Error: ${result.error}`, ...(logText ? [`\\nLogs:\\n${logText}`] : [])];\n return {\n text: truncate(parts.join(\"\\n\"), MAX_PREVIEW_CHARS),\n structured: { status: \"error\", error: result.error, logs: result.logs ?? [] },\n isError: true,\n };\n }\n\n const parts = [\n ...(resultText ? [truncate(resultText, MAX_PREVIEW_CHARS)] : [\"(no result)\"]),\n ...(logText ? [`\\nLogs:\\n${logText}`] : []),\n ];\n return {\n text: parts.join(\"\\n\"),\n structured: { status: \"completed\", result: result.result ?? null, logs: result.logs ?? [] },\n isError: false,\n };\n};\n\nexport const formatPausedExecution = (\n paused: PausedExecution,\n): {\n text: string;\n structured: Record<string, unknown>;\n} => {\n const req = paused.elicitationContext.request;\n const lines: string[] = [`Execution paused: ${req.message}`];\n const isUrlElicitation = Predicate.isTagged(req, \"UrlElicitation\");\n const isFormElicitation = Predicate.isTagged(req, \"FormElicitation\");\n const requestedSchema = isFormElicitation ? req.requestedSchema : undefined;\n const hasRequestedSchema =\n requestedSchema !== undefined && Object.keys(requestedSchema).length > 0;\n const instructions = isUrlElicitation\n ? `The user needs to open this URL in a browser and complete the flow. After the user finishes, call the resume tool with executionId \"${paused.id}\" and action \"accept\".`\n : hasRequestedSchema\n ? `Ask the user for values matching requestedSchema. Then call the resume tool with executionId \"${paused.id}\", action \"accept\", and content matching requestedSchema. If the user declines, call resume with action \"decline\" or \"cancel\".`\n : `This is a model-side confirmation gate; there is no browser form to open. Ask the user whether to approve the paused tool call. If the user approves, call the resume tool with executionId \"${paused.id}\" and action \"accept\". If the user declines, call resume with action \"decline\" or \"cancel\".`;\n\n if (isUrlElicitation) {\n lines.push(`\\nOpen this URL in a browser:\\n${req.url}`);\n lines.push('\\nAfter the browser flow, call the resume tool with action \"accept\".');\n } else if (hasRequestedSchema) {\n lines.push(\n \"\\nAsk the user for a response matching the requested schema, then call the resume tool.\",\n );\n lines.push(`\\nRequested schema:\\n${JSON.stringify(requestedSchema, null, 2)}`);\n } else {\n lines.push(\n '\\nThis is a model-side confirmation gate; no browser form is waiting. Ask the user whether to approve, then call the resume tool with action \"accept\", \"decline\", or \"cancel\".',\n );\n }\n\n lines.push(`\\nexecutionId: ${paused.id}`);\n lines.push(`\\ninstructions: ${instructions}`);\n\n return {\n text: lines.join(\"\\n\"),\n structured: {\n status: \"waiting_for_interaction\",\n executionId: paused.id,\n interaction: {\n kind: isUrlElicitation ? \"url\" : \"form\",\n message: req.message,\n instructions,\n toolId: String(paused.elicitationContext.toolId),\n args: paused.elicitationContext.args,\n ...(isUrlElicitation ? { url: req.url } : {}),\n ...(isFormElicitation ? { requestedSchema: req.requestedSchema } : {}),\n },\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Full invoker (base + discover + describe)\n// ---------------------------------------------------------------------------\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readOptionalLimit = (value: unknown, toolName: string): number | ExecutionToolError => {\n if (value === undefined) {\n return 12;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n return new ExecutionToolError({\n message: `${toolName} limit must be a positive number when provided`,\n });\n }\n\n return Math.floor(value);\n};\n\nconst readOptionalOffset = (value: unknown, toolName: string): number | ExecutionToolError => {\n if (value === undefined) {\n return 0;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return new ExecutionToolError({\n message: `${toolName} offset must be a non-negative number when provided`,\n });\n }\n\n return Math.floor(value);\n};\n\nconst makeFullInvoker = (executor: Executor, invokeOptions: InvokeOptions): SandboxToolInvoker => {\n const base = makeExecutorToolInvoker(executor, { invokeOptions });\n return {\n invoke: ({ path, args }) => {\n if (path === \"search\") {\n if (!isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message:\n \"tools.search expects an object: { query?: string; namespace?: string; limit?: number; offset?: number }\",\n }),\n );\n }\n\n if (args.query !== undefined && typeof args.query !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.search query must be a string when provided\",\n }),\n );\n }\n\n if (args.namespace !== undefined && typeof args.namespace !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.search namespace must be a string when provided\",\n }),\n );\n }\n\n const limit = readOptionalLimit(args.limit, \"tools.search\");\n if (Predicate.isTagged(limit, \"ExecutionToolError\")) {\n return Effect.fail(limit);\n }\n\n const offset = readOptionalOffset(args.offset, \"tools.search\");\n if (Predicate.isTagged(offset, \"ExecutionToolError\")) {\n return Effect.fail(offset);\n }\n\n return searchTools(executor, args.query ?? \"\", limit, {\n namespace: args.namespace,\n offset,\n }).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: { \"mcp.tool.name\": path, \"executor.tool.builtin\": true },\n }),\n );\n }\n if (path === \"executor.sources.list\") {\n if (args !== undefined && !isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message:\n \"tools.executor.sources.list expects an object: { query?: string; limit?: number; offset?: number }\",\n }),\n );\n }\n\n if (isRecord(args) && args.query !== undefined && typeof args.query !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.executor.sources.list query must be a string when provided\",\n }),\n );\n }\n\n const limit = readOptionalLimit(\n isRecord(args) ? args.limit : undefined,\n \"tools.executor.sources.list\",\n );\n if (Predicate.isTagged(limit, \"ExecutionToolError\")) {\n return Effect.fail(limit);\n }\n\n const offset = readOptionalOffset(\n isRecord(args) ? args.offset : undefined,\n \"tools.executor.sources.list\",\n );\n if (Predicate.isTagged(offset, \"ExecutionToolError\")) {\n return Effect.fail(offset);\n }\n\n return listExecutorSources(executor, {\n query: isRecord(args) && typeof args.query === \"string\" ? args.query : undefined,\n limit,\n offset,\n }).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: { \"mcp.tool.name\": path, \"executor.tool.builtin\": true },\n }),\n );\n }\n if (path === \"describe.tool\") {\n if (!isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.describe.tool expects an object: { path: string }\",\n }),\n );\n }\n\n if (typeof args.path !== \"string\" || args.path.trim().length === 0) {\n return Effect.fail(new ExecutionToolError({ message: \"describe.tool requires a path\" }));\n }\n\n if (\"includeSchemas\" in args) {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.describe.tool no longer accepts includeSchemas\",\n }),\n );\n }\n\n return describeTool(executor, args.path).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: {\n \"mcp.tool.name\": path,\n \"executor.tool.builtin\": true,\n \"executor.tool.target_path\": args.path,\n },\n }),\n );\n }\n return base.invoke({ path, args });\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Execution Engine\n// ---------------------------------------------------------------------------\n\nexport type ExecutionEngine<E extends Cause.YieldableError = CodeExecutionError> = {\n /**\n * Execute code with elicitation handled inline by the provided handler.\n * Use this when the host supports elicitation (e.g. MCP with elicitation capability).\n *\n * Fails with the code executor's typed error `E` (defaults to\n * `CodeExecutionError`). Runtimes surface their own `Data.TaggedError`\n * subclass, which flows through here unchanged.\n */\n readonly execute: (\n code: string,\n options: { readonly onElicitation: ElicitationHandler },\n ) => Effect.Effect<ExecuteResult, E>;\n\n /**\n * Execute code, intercepting the first elicitation as a pause point.\n * Use this when the host doesn't support inline elicitation.\n * Returns either a completed result or a paused execution that can be resumed.\n */\n readonly executeWithPause: (code: string) => Effect.Effect<ExecutionResult, E>;\n\n /**\n * Resume a paused execution. Returns a completed result, a new pause, or\n * null if the executionId was not found.\n */\n readonly resume: (\n executionId: string,\n response: ResumeResponse,\n ) => Effect.Effect<ExecutionResult | null, E>;\n\n /**\n * Inspect a paused execution without resuming it. Returns null if the id is\n * unknown or has already been resumed.\n */\n readonly getPausedExecution: (executionId: string) => Effect.Effect<PausedExecution | null>;\n\n /**\n * Get the dynamic tool description (workflow + namespaces).\n */\n readonly getDescription: Effect.Effect<string>;\n};\n\nexport const createExecutionEngine = <E extends Cause.YieldableError = CodeExecutionError>(\n config: ExecutionEngineConfig<E>,\n): ExecutionEngine<E> => {\n const { executor, codeExecutor } = config;\n const pausedExecutions = new Map<string, InternalPausedExecution<E>>();\n let nextId = 0;\n\n /**\n * Race a running fiber against the pause queue. Returns when either\n * the fiber completes or an elicitation handler fires (whichever\n * comes first). Re-used by both executeWithPause and resume.\n *\n * `Effect.raceFirst` (not `Effect.race`) — `race` has prefer-success\n * semantics in Effect v4 (\"first successful result\"), which means a\n * fiber failure waits indefinitely for the pause Deferred to succeed.\n * For a fast `codeExecutor.execute` failure (e.g. a syntax error\n * inside the dynamic worker) the pause signal never fires, so the\n * outer Effect hangs until the upstream client gives up. `raceFirst`\n * settles on whichever side completes first, success or failure.\n */\n const awaitCompletionOrPause = (\n fiber: Fiber.Fiber<ExecuteResult, E>,\n pauseQueue: Queue.Queue<InternalPausedExecution<E>>,\n ): Effect.Effect<ExecutionResult, E> =>\n Effect.raceFirst(\n Fiber.join(fiber).pipe(\n Effect.map((result): ExecutionResult => ({ status: \"completed\", result })),\n ),\n Queue.take(pauseQueue).pipe(\n Effect.map((paused): ExecutionResult => ({ status: \"paused\", execution: paused })),\n ),\n );\n\n /**\n * Start an execution in pause/resume mode.\n *\n * The sandbox is forked as a daemon because paused executions can outlive the\n * caller scope that returned the first pause, such as an HTTP request handler.\n */\n const startPausableExecution = Effect.fn(\"mcp.execute\")(function* (code: string) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.mode\": \"pausable\",\n \"mcp.execute.code_length\": code.length,\n });\n\n // Queue preserves pauses that arrive before the previous approval has\n // returned to the caller, which can happen with concurrent tool calls.\n const pauseQueue = yield* Queue.unbounded<InternalPausedExecution<E>>();\n\n // Will be set once the fiber is forked.\n let fiber: Fiber.Fiber<ExecuteResult, E>;\n\n const elicitationHandler: ElicitationHandler = (ctx) =>\n Effect.gen(function* () {\n const responseDeferred = yield* Deferred.make<typeof ElicitationResponse.Type>();\n const id = `exec_${++nextId}`;\n\n const paused: InternalPausedExecution<E> = {\n id,\n elicitationContext: ctx,\n response: responseDeferred,\n fiber: fiber!,\n pauseQueue,\n };\n pausedExecutions.set(id, paused);\n\n yield* Queue.offer(pauseQueue, paused);\n\n // Suspend until resume() completes responseDeferred.\n return yield* Deferred.await(responseDeferred);\n });\n\n const invoker = makeFullInvoker(executor, { onElicitation: elicitationHandler });\n fiber = yield* Effect.forkDetach(\n codeExecutor.execute(code, invoker).pipe(Effect.withSpan(\"executor.code.exec\")),\n );\n\n return (yield* awaitCompletionOrPause(fiber, pauseQueue)) as ExecutionResult;\n });\n\n /**\n * Resume a paused execution. Completes the response Deferred to unblock the\n * fiber, then races completion against the next queued or future pause.\n */\n const resumeExecution = Effect.fn(\"mcp.execute.resume\")(function* (\n executionId: string,\n response: ResumeResponse,\n ) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.resume.action\": response.action,\n });\n\n const paused = pausedExecutions.get(executionId);\n if (!paused) return null;\n pausedExecutions.delete(executionId);\n\n yield* Deferred.succeed(paused.response, {\n action: response.action as typeof ElicitationResponse.Type.action,\n content: response.content,\n });\n\n return (yield* awaitCompletionOrPause(paused.fiber, paused.pauseQueue)) as ExecutionResult;\n });\n\n /**\n * Inline-elicitation execute path. Wrapped so every call produces an\n * `mcp.execute` span with the inner `executor.code.exec` as a child.\n */\n const runInlineExecution = Effect.fn(\"mcp.execute\")(function* (\n code: string,\n options: { readonly onElicitation: ElicitationHandler },\n ) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.mode\": \"inline\",\n \"mcp.execute.code_length\": code.length,\n });\n const invoker = makeFullInvoker(executor, {\n onElicitation: options.onElicitation,\n });\n return yield* codeExecutor.execute(code, invoker).pipe(Effect.withSpan(\"executor.code.exec\"));\n });\n\n return {\n execute: runInlineExecution,\n executeWithPause: startPausableExecution,\n resume: resumeExecution,\n getPausedExecution: (executionId) =>\n Effect.sync(() => pausedExecutions.get(executionId) ?? null),\n getDescription: buildExecuteDescription(executor),\n };\n};\n"],"mappings":";AAAA,YAAY,UAAU;AAUtB,SAAS,0BAA0B;AAR5B,IAAM,qBAAN,cAAsC,iBAAY,oBAAoB,EAG1E;AAAC;;;ACLJ,SAAS,QAAQ,iBAAiB;AAClC,YAAY,WAAW;AASvB,SAAS,cAAc,kBAAkB;AAIzC,IAAM,wBAAwB;AAC9B,IAAM,wBACJ;AAEF,IAAM,uBAAuB,CAAC,qBAC5B,qBAAqB,oBAAoB,SAAS;AAEpD,IAAM,4BAA4B,CAChC,iBAC4B;AAAA,EAC5B,GAAI,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AAC;AAMD,QAAM,kBAAkBA,QAAO,GAAG,oBAAoB,EAAE,WACtD,aACA,UACA;AACA,WAAOA,QAAO,oBAAoB;AAAA,MAChC,6BAA6B,SAAS;AAAA,IACxC,CAAC;AAED,UAAM,SAAS,iBAAiB,IAAI,WAAW;AAC/C,QAAI,CAAC,OAAQ,QAAO;AACpB,qBAAiB,OAAO,WAAW;AAEnC,WAAO,SAAS,QAAQ,OAAO,UAAU;AAAA,MACvC,QAAQ,SAAS;AAAA,MACjB,SAAS,SAAS;AAAA,IACpB,CAAC;AAED,WAAQ,OAAO,uBAAuB,OAAO,OAAO,OAAO,UAAU;AAAA,EACvE,CAAC;AAMD,QAAM,qBAAqBA,QAAO,GAAG,aAAa,EAAE,WAClD,MACA,SACA;AACA,WAAOA,QAAO,oBAAoB;AAAA,MAChC,oBAAoB;AAAA,MACpB,2BAA2B,KAAK;AAAA,IAClC,CAAC;AACD,UAAM,UAAU,gBAAgB,UAAU;AAAA,MACxC,eAAe,QAAQ;AAAA,IACzB,CAAC;AACD,WAAO,OAAO,aAAa,QAAQ,MAAM,OAAO,EAAE,KAAKA,QAAO,SAAS,oBAAoB,CAAC;AAAA,EAC9F,CAAC;AAED,SAAO;AAAA,IACL,SAAS;AAAA,IACT,kBAAkB;AAAA,IAClB,QAAQ;AAAA,IACR,oBAAoB,CAAC,gBACnBA,QAAO,KAAK,MAAM,iBAAiB,IAAI,WAAW,KAAK,IAAI;AAAA,IAC7D,gBAAgB,wBAAwB,QAAQ;AAAA,EAClD;AACF;","names":["Effect","Effect","Predicate","parts","Predicate","Effect"]}
package/dist/core.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  listExecutorSources,
9
9
  makeExecutorToolInvoker,
10
10
  searchTools
11
- } from "./chunk-OLPHXJSA.js";
11
+ } from "./chunk-NJPJNVEN.js";
12
12
  export {
13
13
  ExecutionToolError,
14
14
  buildExecuteDescription,
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createExecutionEngine,
5
5
  formatExecuteResult,
6
6
  formatPausedExecution
7
- } from "./chunk-OLPHXJSA.js";
7
+ } from "./chunk-NJPJNVEN.js";
8
8
 
9
9
  // src/promise.ts
10
10
  import { Effect } from "effect";
@@ -2,6 +2,14 @@ import { Effect } from "effect";
2
2
  import type { Executor, InvokeOptions } from "@executor-js/sdk/core";
3
3
  import type { SandboxToolInvoker } from "@executor-js/codemode-core";
4
4
  import { ExecutionToolError } from "./errors";
5
+ type DescribedTool = {
6
+ readonly path: string;
7
+ readonly name: string;
8
+ readonly description?: string;
9
+ readonly inputTypeScript?: string;
10
+ readonly outputTypeScript?: string;
11
+ readonly typeScriptDefinitions?: Record<string, string>;
12
+ };
5
13
  /**
6
14
  * Bridges QuickJS `tools.someSource.someOp(args)` calls into
7
15
  * `executor.tools.invoke(toolId, args)`.
@@ -73,19 +81,6 @@ export declare const listExecutorSources: (executor: Executor, options?: {
73
81
  toolCount: number;
74
82
  }>, ExecutionToolError, never>;
75
83
  /** What `tools.describe.tool()` calls inside the sandbox. */
76
- export declare const describeTool: (executor: Executor, path: string) => Effect.Effect<{
77
- path: string;
78
- name: string;
79
- description?: undefined;
80
- inputTypeScript?: undefined;
81
- outputTypeScript?: undefined;
82
- typeScriptDefinitions?: undefined;
83
- } | {
84
- path: string;
85
- name: string;
86
- description: string | undefined;
87
- inputTypeScript: string | undefined;
88
- outputTypeScript: string;
89
- typeScriptDefinitions: Record<string, string>;
90
- }, import("@executor-js/sdk/core").StorageFailure, never>;
84
+ export declare const describeTool: (executor: Executor, path: string) => Effect.Effect<DescribedTool, import("@executor-js/sdk/core").StorageFailure, never>;
85
+ export {};
91
86
  //# sourceMappingURL=tool-invoker.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-invoker.d.ts","sourceRoot":"","sources":["../src/tool-invoker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,MAAM,QAAQ,CAAC;AAE3C,OAAO,KAAK,EACV,QAAQ,EAIR,aAAa,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9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CACpC,CAAC;AAoMF,sDAAsD;AACtD,eAAO,MAAM,WAAW;yBAIW,MAAM;sBAAoB,MAAM;4FA6CjE,CAAC;AAEH,qEAAqE;AACrE,eAAO,MAAM,mBAAmB;qBAGX,MAAM;qBACN,MAAM;sBACL,MAAM;;;;;;;;;8BA+D1B,CAAC;AAEH,6DAA6D;AAC7D,eAAO,MAAM,YAAY,2HA6BvB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@executor-js/execution",
3
- "version": "1.4.31",
3
+ "version": "1.4.33",
4
4
  "homepage": "https://github.com/RhysSullivan/executor/tree/main/packages/core/execution",
5
5
  "bugs": {
6
6
  "url": "https://github.com/RhysSullivan/executor/issues"
@@ -39,13 +39,13 @@
39
39
  "typecheck:slow": "bunx tsc --noEmit -p tsconfig.json"
40
40
  },
41
41
  "dependencies": {
42
- "@executor-js/codemode-core": "1.4.31",
43
- "@executor-js/sdk": "1.4.31",
42
+ "@executor-js/codemode-core": "1.4.33",
43
+ "@executor-js/sdk": "1.4.33",
44
44
  "effect": "4.0.0-beta.59"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@effect/vitest": "4.0.0-beta.59",
48
- "@executor-js/runtime-quickjs": "1.4.31",
48
+ "@executor-js/runtime-quickjs": "1.4.33",
49
49
  "@types/node": "^24.3.1",
50
50
  "bun-types": "^1.2.22",
51
51
  "tsup": "^8.5.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/tool-invoker.ts","../src/description.ts","../src/engine.ts"],"sourcesContent":["import * as Data from \"effect/Data\";\n\nexport class ExecutionToolError extends Data.TaggedError(\"ExecutionToolError\")<{\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n// `CodeExecutionError` lives in `@executor-js/codemode-core` — the `CodeExecutor`\n// interface uses it as the default error channel, so the runtime packages\n// can import the same class directly.\nexport { CodeExecutionError } from \"@executor-js/codemode-core\";\n","import { Effect, Predicate } from \"effect\";\nimport * as Cause from \"effect/Cause\";\nimport type {\n Executor,\n ToolId,\n Tool,\n ToolSchema,\n InvokeOptions,\n Source,\n} from \"@executor-js/sdk/core\";\nimport { isToolResult, ToolResult } from \"@executor-js/sdk/core\";\nimport type { SandboxToolInvoker } from \"@executor-js/codemode-core\";\nimport { ExecutionToolError } from \"./errors\";\n\nconst OPAQUE_DEFECT_MESSAGE = \"Internal tool error\";\nconst TOOL_ERROR_TYPESCRIPT =\n \"{ code: string; message: string; status?: number; details?: unknown; retryable?: boolean }\";\n\nconst wrapOutputTypeScript = (outputTypeScript?: string): string =>\n `{ ok: true; data: ${outputTypeScript ?? \"unknown\"} } | { ok: false; error: ToolError }`;\n\nconst withToolResultDefinitions = (\n definitions?: Record<string, string>,\n): Record<string, string> => ({\n ...(definitions ?? {}),\n ToolError: TOOL_ERROR_TYPESCRIPT,\n});\n\nconst newCorrelationId = (): string => {\n // 8-hex-char correlation id; enough entropy to disambiguate within a\n // single deployment without leaking host process info.\n return Math.floor(Math.random() * 0x1_0000_0000)\n .toString(16)\n .padStart(8, \"0\");\n};\n\nconst validationIssues = (value: unknown): readonly unknown[] | null => {\n if (typeof value !== \"object\" || value === null) return null;\n const issues = (value as { readonly issues?: unknown }).issues;\n return Array.isArray(issues) ? issues : null;\n};\n\nconst expectedToolFailure = (\n value: unknown,\n): { readonly code: string; readonly message: string; readonly details?: unknown } | null => {\n if (Predicate.isTagged(value, \"ToolNotFoundError\") && \"toolId\" in value) {\n const suggestions =\n \"suggestions\" in value && Array.isArray(value.suggestions) ? value.suggestions : undefined;\n return {\n code: \"tool_not_found\",\n message: `Tool not found: ${String(value.toolId)}`,\n details: { toolId: value.toolId, ...(suggestions ? { suggestions } : {}) },\n };\n }\n if (Predicate.isTagged(value, \"ToolBlockedError\") && \"toolId\" in value) {\n return {\n code: \"tool_blocked\",\n message: `Tool blocked by policy: ${String(value.toolId)}`,\n details: value,\n };\n }\n if (Predicate.isTagged(value, \"ToolInvocationError\")) {\n const issues = validationIssues((value as { readonly cause?: unknown }).cause);\n if (issues) {\n return {\n code: \"invalid_tool_arguments\",\n message: \"Tool arguments did not match the input schema.\",\n details: { issues },\n };\n }\n }\n return null;\n};\n\n/**\n * Extract the source namespace from a tool path. Tool paths look like\n * \"<sourceId>.<op>\" or \"<sourceId>.<group>.<op>\" — we take the first\n * segment as a cheap, non-lookup stand-in for the source id so the span\n * attribute is always populated without hitting `executor.sources.list()`\n * per call.\n */\nconst extractSourceNamespace = (path: string): string => {\n const idx = path.indexOf(\".\");\n return idx === -1 ? path : path.slice(0, idx);\n};\n\n/**\n * Bridges QuickJS `tools.someSource.someOp(args)` calls into\n * `executor.tools.invoke(toolId, args)`.\n *\n * Wrapped in `Effect.fn(\"mcp.tool.dispatch\")` so every tool call becomes a\n * span in the Effect tracer. Attributes:\n * - `mcp.tool.name` — full tool path (e.g. \"github.repos.get\")\n * - `mcp.tool.source_id` — first segment of the path (namespace)\n *\n * `mcp.tool.kind` (openapi | mcp | graphql | code) is NOT annotated here\n * because it would require a `sources.list()` lookup on every invocation.\n * Callers that already know the source kind can annotate at their own span.\n */\nexport const makeExecutorToolInvoker = (\n executor: Executor,\n options: { readonly invokeOptions: InvokeOptions },\n): SandboxToolInvoker => ({\n invoke: Effect.fn(\"mcp.tool.dispatch\")(function* ({ path, args }) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.tool.name\": path,\n \"mcp.tool.source_id\": extractSourceNamespace(path),\n });\n\n const result = yield* executor.tools.invoke(path as ToolId, args, options.invokeOptions).pipe(\n Effect.catchCause((cause) => {\n const err = cause.reasons.find(Cause.isFailReason)?.error;\n const expected = expectedToolFailure(err);\n if (expected) {\n return Effect.succeed(ToolResult.fail(expected));\n }\n if (isElicitationDeclinedError(err)) {\n return Effect.fail(\n new ExecutionToolError({\n message: `Tool \"${err.toolId}\" requires approval but the request was ${err.action === \"cancel\" ? \"cancelled\" : \"declined\"} by the user.`,\n cause: err,\n }),\n );\n }\n // Any other failure here is an infra/plugin defect. Emit an\n // opaque generic with a correlation id so internal context (URLs\n // with tokens, DB connection strings, file paths in stacks)\n // can't leak through Error.message into the sandbox. The full\n // cause is logged with the same correlation id so operators can\n // still trace the failure.\n const correlationId = newCorrelationId();\n return Effect.logError(\"tool dispatch failed\", cause).pipe(\n Effect.annotateLogs({\n \"executor.correlation_id\": correlationId,\n \"mcp.tool.name\": path,\n }),\n Effect.flatMap(() =>\n Effect.fail(\n new ExecutionToolError({\n message: `${OPAQUE_DEFECT_MESSAGE} [${correlationId}]`,\n cause: err ?? cause,\n }),\n ),\n ),\n );\n }),\n );\n\n // Strict: plugins emit ToolResult<T>. Anything else is treated as a\n // raw success value and wrapped — keeps the sandbox-facing contract\n // uniform without forcing every tiny test plugin to import\n // `ToolResult.ok`.\n if (isToolResult(result)) {\n return result;\n }\n return { ok: true, data: result };\n }),\n});\n\nconst isElicitationDeclinedError = (\n value: unknown,\n): value is {\n readonly _tag: \"ElicitationDeclinedError\";\n readonly toolId: string;\n readonly action: \"cancel\" | \"decline\";\n} =>\n Predicate.isTagged(value, \"ElicitationDeclinedError\") &&\n value !== null &&\n typeof value === \"object\" &&\n \"toolId\" in value &&\n typeof value.toolId === \"string\" &&\n \"action\" in value &&\n (value.action === \"cancel\" || value.action === \"decline\");\n\nexport type ToolDiscoveryResult = {\n readonly path: string;\n readonly name: string;\n readonly description?: string;\n readonly sourceId: string;\n readonly score: number;\n};\n\nexport type ExecutorSourceListItem = {\n readonly id: string;\n readonly name: string;\n readonly kind: string;\n readonly runtime?: boolean;\n readonly canRemove?: boolean;\n readonly canRefresh?: boolean;\n readonly toolCount: number;\n};\n\n/**\n * Page of results from a list-style discovery tool. Shared by\n * `tools.search` and `tools.executor.sources.list` so the model sees one\n * consistent shape:\n *\n * - `items` — the page (slice).\n * - `total` — count after filtering, before pagination. The model\n * can use this to detect truncation.\n * - `hasMore` — convenience flag for `(offset + items.length) < total`.\n * - `nextOffset` — concrete offset for the next page when `hasMore`,\n * `null` otherwise. Pre-computing it removes a class of\n * off-by-one mistakes when the model paginates.\n */\nexport type PagedResult<T> = {\n readonly items: readonly T[];\n readonly total: number;\n readonly hasMore: boolean;\n readonly nextOffset: number | null;\n};\n\nconst paginate = <T>(all: readonly T[], offset: number, limit: number): PagedResult<T> => {\n const total = all.length;\n const start = Math.min(Math.max(offset, 0), total);\n const items = all.slice(start, start + limit);\n const consumed = start + items.length;\n const hasMore = consumed < total;\n return {\n items,\n total,\n hasMore,\n nextOffset: hasMore ? consumed : null,\n };\n};\n\ntype SearchableTool = Pick<Tool, \"id\" | \"sourceId\" | \"name\" | \"description\">;\n\ntype PreparedField = {\n readonly raw: string;\n readonly tokens: readonly string[];\n};\n\nconst SEARCH_FIELD_WEIGHTS = {\n path: 12,\n sourceId: 8,\n name: 10,\n description: 5,\n} as const;\n\nconst normalizeSearchText = (value: string): string =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_./:-]+/g, \" \")\n .toLowerCase()\n .trim();\n\nconst tokenizeSearchText = (value: string): string[] =>\n normalizeSearchText(value)\n .split(/[^a-z0-9]+/)\n .map((token) => token.trim())\n .filter(Boolean);\n\nconst prepareField = (value?: string): PreparedField => ({\n raw: normalizeSearchText(value ?? \"\"),\n tokens: tokenizeSearchText(value ?? \"\"),\n});\n\nconst scorePreparedField = (\n query: string,\n queryTokens: readonly string[],\n field: PreparedField,\n weight: number,\n): {\n readonly score: number;\n readonly matchedTokens: ReadonlySet<string>;\n readonly exactPhraseMatch: boolean;\n} => {\n if (field.raw.length === 0) {\n return {\n score: 0,\n matchedTokens: new Set<string>(),\n exactPhraseMatch: false,\n };\n }\n\n let score = 0;\n const matchedTokens = new Set<string>();\n const exactPhraseMatch = query.length > 0 && field.raw.includes(query);\n\n if (query.length > 0) {\n if (field.raw === query) {\n score += weight * 14;\n } else if (field.raw.startsWith(query)) {\n score += weight * 9;\n } else if (exactPhraseMatch) {\n score += weight * 6;\n }\n }\n\n for (const token of queryTokens) {\n if (field.tokens.includes(token)) {\n score += weight * 4;\n matchedTokens.add(token);\n continue;\n }\n\n if (\n field.tokens.some((candidate) => candidate.startsWith(token) || token.startsWith(candidate))\n ) {\n score += weight * 2;\n matchedTokens.add(token);\n continue;\n }\n\n if (field.raw.includes(token)) {\n score += weight;\n matchedTokens.add(token);\n }\n }\n\n return {\n score,\n matchedTokens,\n exactPhraseMatch,\n };\n};\n\nconst matchesNamespace = (tool: SearchableTool, namespace?: string): boolean => {\n if (!namespace || normalizeSearchText(namespace).length === 0) {\n return true;\n }\n\n const namespaceTokens = tokenizeSearchText(namespace);\n if (namespaceTokens.length === 0) {\n return true;\n }\n\n const sourceTokens = tokenizeSearchText(tool.sourceId);\n const pathTokens = tokenizeSearchText(tool.id);\n\n const isPrefixMatch = (tokens: readonly string[]): boolean =>\n namespaceTokens.every((token, index) => tokens[index] === token);\n\n return isPrefixMatch(sourceTokens) || isPrefixMatch(pathTokens);\n};\n\nconst scoreToolMatch = (tool: SearchableTool, query: string): ToolDiscoveryResult | null => {\n const normalizedQuery = normalizeSearchText(query);\n const queryTokens = tokenizeSearchText(query);\n\n if (normalizedQuery.length === 0 || queryTokens.length === 0) {\n return null;\n }\n\n const path = prepareField(tool.id);\n const sourceId = prepareField(tool.sourceId);\n const name = prepareField(tool.name);\n const description = prepareField(tool.description);\n\n const fieldScores = [\n scorePreparedField(normalizedQuery, queryTokens, path, SEARCH_FIELD_WEIGHTS.path),\n scorePreparedField(normalizedQuery, queryTokens, sourceId, SEARCH_FIELD_WEIGHTS.sourceId),\n scorePreparedField(normalizedQuery, queryTokens, name, SEARCH_FIELD_WEIGHTS.name),\n scorePreparedField(normalizedQuery, queryTokens, description, SEARCH_FIELD_WEIGHTS.description),\n ];\n\n const matchedTokens = new Set<string>();\n let score = 0;\n let exactPhraseMatch = false;\n\n for (const fieldScore of fieldScores) {\n score += fieldScore.score;\n exactPhraseMatch ||= fieldScore.exactPhraseMatch;\n for (const token of fieldScore.matchedTokens) {\n matchedTokens.add(token);\n }\n }\n\n if (matchedTokens.size === 0) {\n return null;\n }\n\n const coverage = matchedTokens.size / queryTokens.length;\n const minimumCoverage = queryTokens.length <= 2 ? 1 : 0.6;\n\n if (coverage < minimumCoverage && !exactPhraseMatch) {\n return null;\n }\n\n if (coverage === 1) {\n score += 25;\n } else {\n score += Math.round(coverage * 10);\n }\n\n if (path.tokens[0] === queryTokens[0] || name.tokens[0] === queryTokens[0]) {\n score += 8;\n }\n\n if (\n normalizeSearchText(tool.id) === normalizedQuery ||\n normalizeSearchText(tool.name) === normalizedQuery\n ) {\n score += 20;\n }\n\n return {\n path: tool.id,\n name: tool.name,\n description: tool.description,\n sourceId: tool.sourceId,\n score,\n };\n};\n\n/** What `tools.search()` calls inside the sandbox. */\nexport const searchTools = Effect.fn(\"executor.tools.search\")(function* (\n executor: Executor,\n query: string,\n limit = 12,\n options?: { readonly namespace?: string; readonly offset?: number },\n) {\n const offset = options?.offset ?? 0;\n yield* Effect.annotateCurrentSpan({\n \"executor.search.query_length\": query.length,\n \"executor.search.limit\": limit,\n \"executor.search.offset\": offset,\n ...(options?.namespace ? { \"executor.search.namespace\": options.namespace } : {}),\n });\n\n const empty: PagedResult<ToolDiscoveryResult> = {\n items: [],\n total: 0,\n hasMore: false,\n nextOffset: null,\n };\n\n if (normalizeSearchText(query).length === 0) {\n return empty;\n }\n\n const all = yield* executor.tools.list({ includeAnnotations: false }).pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list tools for search\",\n cause,\n }),\n ),\n );\n const ranked = all\n .filter((tool: Tool) => matchesNamespace(tool, options?.namespace))\n .map((tool: Tool) => scoreToolMatch(tool, query))\n .filter(Predicate.isNotNull)\n .sort((left, right) => right.score - left.score || left.path.localeCompare(right.path));\n\n const page = paginate(ranked, offset, limit);\n\n yield* Effect.annotateCurrentSpan({\n \"executor.search.candidate_count\": all.length,\n \"executor.search.match_count\": ranked.length,\n \"executor.search.result_count\": page.items.length,\n \"executor.search.has_more\": page.hasMore,\n });\n return page;\n});\n\n/** What `tools.executor.sources.list()` calls inside the sandbox. */\nexport const listExecutorSources = Effect.fn(\"executor.sources.list\")(function* (\n executor: Executor,\n options?: {\n readonly query?: string;\n readonly limit?: number;\n readonly offset?: number;\n },\n) {\n const normalizedQuery = normalizeSearchText(options?.query ?? \"\");\n const limit = options?.limit ?? 50;\n const offset = options?.offset ?? 0;\n const sources = yield* executor.sources.list().pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list executor sources\",\n cause,\n }),\n ),\n );\n\n const filtered =\n normalizedQuery.length === 0\n ? sources\n : sources.filter((source: Source) => {\n const haystack = normalizeSearchText([source.id, source.name, source.kind].join(\" \"));\n return tokenizeSearchText(normalizedQuery).every((token) => haystack.includes(token));\n });\n\n // Single query for all tools, then count per source in memory.\n const allTools = yield* executor.tools.list({ includeAnnotations: false }).pipe(\n Effect.mapError(\n (cause) =>\n new ExecutionToolError({\n message: \"Failed to list tools for source counts\",\n cause,\n }),\n ),\n );\n const toolCountBySource = new Map<string, number>();\n for (const tool of allTools) {\n toolCountBySource.set(tool.sourceId, (toolCountBySource.get(tool.sourceId) ?? 0) + 1);\n }\n\n const sortedWithCounts = filtered\n .map(\n (source: Source) =>\n ({\n id: source.id,\n name: source.name,\n kind: source.kind,\n runtime: source.runtime,\n canRemove: source.canRemove,\n canRefresh: source.canRefresh,\n toolCount: toolCountBySource.get(source.id) ?? 0,\n }) satisfies ExecutorSourceListItem,\n )\n .sort((left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id));\n\n const page = paginate(sortedWithCounts, offset, limit);\n\n yield* Effect.annotateCurrentSpan({\n \"executor.sources.candidate_count\": sources.length,\n \"executor.sources.match_count\": sortedWithCounts.length,\n \"executor.sources.result_count\": page.items.length,\n \"executor.sources.has_more\": page.hasMore,\n });\n return page;\n});\n\n/** What `tools.describe.tool()` calls inside the sandbox. */\nexport const describeTool = Effect.fn(\"executor.tools.describe\")(function* (\n executor: Executor,\n path: string,\n) {\n yield* Effect.annotateCurrentSpan({ \"mcp.tool.name\": path });\n\n // Single tools.schema() call — it already fetches the tool row\n // internally. No need to also call tools.list() just for name/description.\n const schema: ToolSchema | null = yield* executor.tools.schema(path);\n\n // tools.schema() returns null if the tool doesn't exist. Fall back to\n // a minimal stub so callers can still render something.\n if (schema === null) {\n return { path, name: path };\n }\n\n // The schema's id is the tool path; name/description come from the\n // tool row which tools.schema() already loaded.\n return {\n path,\n name: schema.name ?? path,\n description: schema.description,\n inputTypeScript: schema.inputTypeScript,\n outputTypeScript: wrapOutputTypeScript(schema.outputTypeScript),\n typeScriptDefinitions: withToolResultDefinitions(schema.typeScriptDefinitions),\n };\n});\n","import { Effect } from \"effect\";\nimport type { Executor, Source } from \"@executor-js/sdk/core\";\n\n/**\n * Builds a tool description dynamically.\n *\n * Structure:\n * 1. Workflow (top — critical, least likely to be truncated)\n * 2. Available namespaces (bottom)\n */\nexport const buildExecuteDescription = (executor: Executor): Effect.Effect<string> =>\n Effect.gen(function* () {\n const sources: readonly Source[] = yield* executor.sources.list().pipe(\n // oxlint-disable-next-line executor/no-effect-escape-hatch -- boundary: ExecutionEngine.getDescription currently exposes no error channel; engine typed-error widening is covered separately\n Effect.orDie,\n Effect.withSpan(\"executor.sources.list\"),\n );\n\n const description = yield* Effect.sync(() => formatDescription(sources)).pipe(\n Effect.withSpan(\"schema.compile.description\", {\n attributes: { \"executor.source_count\": sources.length },\n }),\n );\n\n yield* Effect.annotateCurrentSpan({\n \"executor.source_count\": sources.length,\n \"schema.kind\": \"execute\",\n });\n\n return description;\n }).pipe(Effect.withSpan(\"schema.describe.execute\"));\n\nconst formatDescription = (sources: readonly Source[]): string => {\n const lines: string[] = [\n \"Execute TypeScript in a sandboxed runtime with access to configured API tools.\",\n \"\",\n \"## Workflow\",\n \"\",\n '1. `const { items: matches } = await tools.search({ query: \"<intent + key nouns>\", limit: 12 });`',\n '2. `const path = matches[0]?.path; if (!path) return \"No matching tools found.\";`',\n \"3. `const details = await tools.describe.tool({ path });`\",\n \"4. Use `details.inputTypeScript` / `details.outputTypeScript` and `details.typeScriptDefinitions` for compact shapes.\",\n \"5. Use `tools.executor.sources.list()` when you need configured source inventory.\",\n \"6. Call the tool: `const result = await tools.<path>(input);`\",\n \"\",\n \"## Rules\",\n \"\",\n \"- `tools.search()` returns paginated, ranked matches: `{ items, total, hasMore, nextOffset }`. Best-first. Use short intent phrases like `github issues`, `repo details`, or `create calendar event`.\",\n '- When you already know the namespace, narrow with `tools.search({ namespace: \"github\", query: \"issues\" })`.',\n \"- `tools.executor.sources.list()` returns the same paged shape: `{ items: [{ id, toolCount, ... }], total, hasMore, nextOffset }`.\",\n \"- Tool calls return a value union: `{ ok: true, data }` for success or `{ ok: false, error: { code, message, status?, details?, retryable? } }` for expected tool/domain failures. Branch on `result.ok`.\",\n \"- If `hasMore` is true and you didn't find what you need, fetch the next page: `tools.search({ query, offset: nextOffset, limit })`. Same `offset` parameter on `tools.executor.sources.list({ offset, limit })`.\",\n \"- Always use the namespace prefix when calling tools: `tools.<namespace>.<tool>(args)`. Example: `tools.home_assistant_rest_api.states.getState(...)` — not `tools.states.getState(...)`.\",\n \"- The `tools` object is a lazy proxy — `Object.keys(tools)` won't work. Use `tools.search()` or `tools.executor.sources.list()` instead.\",\n '- Pass an object to system tools, e.g. `tools.search({ query: \"...\" })`, `tools.executor.sources.list()`, and `tools.describe.tool({ path })`.',\n \"- `tools.describe.tool()` returns compact TypeScript shapes. Use `inputTypeScript`, `outputTypeScript`, and `typeScriptDefinitions`.\",\n \"- For tools that return large collections (e.g. `getStates`, `getAll`), filter results in code rather than calling per-item tools.\",\n \"- Do not use `fetch` — all API calls go through `tools.*`.\",\n \"- If execution pauses for interaction, resume it with the returned `resumePayload`.\",\n \"- TypeScript type syntax (`: T`, `as T`, generics, interfaces, type aliases) is stripped before execution — feel free to write idiomatic TypeScript using the shapes from `tools.describe.tool()`. Decorators and `enum` are not supported.\",\n ];\n\n if (sources.length > 0) {\n lines.push(\"\");\n lines.push(\"## Available namespaces\");\n lines.push(\"\");\n const sorted = [...sources].sort((a, b) => a.id.localeCompare(b.id)).slice(0, 50);\n for (const source of sorted) {\n lines.push(`- \\`${source.id}\\``);\n }\n if (sources.length > sorted.length) {\n lines.push(`- ... ${sources.length - sorted.length} more`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { Deferred, Effect, Fiber, Predicate, Queue } from \"effect\";\nimport type * as Cause from \"effect/Cause\";\n\nimport type {\n Executor,\n InvokeOptions,\n ElicitationResponse,\n ElicitationHandler,\n ElicitationContext,\n} from \"@executor-js/sdk/core\";\nimport { CodeExecutionError } from \"@executor-js/codemode-core\";\nimport type { CodeExecutor, ExecuteResult, SandboxToolInvoker } from \"@executor-js/codemode-core\";\n\nimport {\n makeExecutorToolInvoker,\n searchTools,\n listExecutorSources,\n describeTool,\n} from \"./tool-invoker\";\nimport { ExecutionToolError } from \"./errors\";\nimport { buildExecuteDescription } from \"./description\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ExecutionEngineConfig<E extends Cause.YieldableError = CodeExecutionError> = {\n readonly executor: Executor;\n readonly codeExecutor: CodeExecutor<E>;\n};\n\nexport type ExecutionResult =\n | { readonly status: \"completed\"; readonly result: ExecuteResult }\n | { readonly status: \"paused\"; readonly execution: PausedExecution };\n\nexport type PausedExecution = {\n readonly id: string;\n readonly elicitationContext: ElicitationContext;\n};\n\n/** Internal representation with Effect runtime state for pause/resume. */\ntype InternalPausedExecution<E> = PausedExecution & {\n readonly response: Deferred.Deferred<typeof ElicitationResponse.Type>;\n readonly fiber: Fiber.Fiber<ExecuteResult, E>;\n readonly pauseQueue: Queue.Queue<InternalPausedExecution<E>>;\n};\n\nexport type ResumeResponse = {\n readonly action: \"accept\" | \"decline\" | \"cancel\";\n readonly content?: Record<string, unknown>;\n};\n\n// ---------------------------------------------------------------------------\n// Result formatting\n// ---------------------------------------------------------------------------\n\nconst MAX_PREVIEW_CHARS = 30_000;\n\nconst truncate = (value: string, max: number): string =>\n value.length > max\n ? `${value.slice(0, max)}\\n... [truncated ${value.length - max} chars]`\n : value;\n\nexport const formatExecuteResult = (\n result: ExecuteResult,\n): {\n text: string;\n structured: Record<string, unknown>;\n isError: boolean;\n} => {\n const resultText =\n result.result != null\n ? typeof result.result === \"string\"\n ? result.result\n : JSON.stringify(result.result, null, 2)\n : null;\n\n const logText = result.logs && result.logs.length > 0 ? result.logs.join(\"\\n\") : null;\n\n if (result.error) {\n const parts = [`Error: ${result.error}`, ...(logText ? [`\\nLogs:\\n${logText}`] : [])];\n return {\n text: truncate(parts.join(\"\\n\"), MAX_PREVIEW_CHARS),\n structured: { status: \"error\", error: result.error, logs: result.logs ?? [] },\n isError: true,\n };\n }\n\n const parts = [\n ...(resultText ? [truncate(resultText, MAX_PREVIEW_CHARS)] : [\"(no result)\"]),\n ...(logText ? [`\\nLogs:\\n${logText}`] : []),\n ];\n return {\n text: parts.join(\"\\n\"),\n structured: { status: \"completed\", result: result.result ?? null, logs: result.logs ?? [] },\n isError: false,\n };\n};\n\nexport const formatPausedExecution = (\n paused: PausedExecution,\n): {\n text: string;\n structured: Record<string, unknown>;\n} => {\n const req = paused.elicitationContext.request;\n const lines: string[] = [`Execution paused: ${req.message}`];\n const isUrlElicitation = Predicate.isTagged(req, \"UrlElicitation\");\n const isFormElicitation = Predicate.isTagged(req, \"FormElicitation\");\n const requestedSchema = isFormElicitation ? req.requestedSchema : undefined;\n const hasRequestedSchema =\n requestedSchema !== undefined && Object.keys(requestedSchema).length > 0;\n const instructions = isUrlElicitation\n ? `The user needs to open this URL in a browser and complete the flow. After the user finishes, call the resume tool with executionId \"${paused.id}\" and action \"accept\".`\n : hasRequestedSchema\n ? `Ask the user for values matching requestedSchema. Then call the resume tool with executionId \"${paused.id}\", action \"accept\", and content matching requestedSchema. If the user declines, call resume with action \"decline\" or \"cancel\".`\n : `This is a model-side confirmation gate; there is no browser form to open. Ask the user whether to approve the paused tool call. If the user approves, call the resume tool with executionId \"${paused.id}\" and action \"accept\". If the user declines, call resume with action \"decline\" or \"cancel\".`;\n\n if (isUrlElicitation) {\n lines.push(`\\nOpen this URL in a browser:\\n${req.url}`);\n lines.push('\\nAfter the browser flow, call the resume tool with action \"accept\".');\n } else if (hasRequestedSchema) {\n lines.push(\n \"\\nAsk the user for a response matching the requested schema, then call the resume tool.\",\n );\n lines.push(`\\nRequested schema:\\n${JSON.stringify(requestedSchema, null, 2)}`);\n } else {\n lines.push(\n '\\nThis is a model-side confirmation gate; no browser form is waiting. Ask the user whether to approve, then call the resume tool with action \"accept\", \"decline\", or \"cancel\".',\n );\n }\n\n lines.push(`\\nexecutionId: ${paused.id}`);\n lines.push(`\\ninstructions: ${instructions}`);\n\n return {\n text: lines.join(\"\\n\"),\n structured: {\n status: \"waiting_for_interaction\",\n executionId: paused.id,\n interaction: {\n kind: isUrlElicitation ? \"url\" : \"form\",\n message: req.message,\n instructions,\n toolId: String(paused.elicitationContext.toolId),\n args: paused.elicitationContext.args,\n ...(isUrlElicitation ? { url: req.url } : {}),\n ...(isFormElicitation ? { requestedSchema: req.requestedSchema } : {}),\n },\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Full invoker (base + discover + describe)\n// ---------------------------------------------------------------------------\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst readOptionalLimit = (value: unknown, toolName: string): number | ExecutionToolError => {\n if (value === undefined) {\n return 12;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n return new ExecutionToolError({\n message: `${toolName} limit must be a positive number when provided`,\n });\n }\n\n return Math.floor(value);\n};\n\nconst readOptionalOffset = (value: unknown, toolName: string): number | ExecutionToolError => {\n if (value === undefined) {\n return 0;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return new ExecutionToolError({\n message: `${toolName} offset must be a non-negative number when provided`,\n });\n }\n\n return Math.floor(value);\n};\n\nconst makeFullInvoker = (executor: Executor, invokeOptions: InvokeOptions): SandboxToolInvoker => {\n const base = makeExecutorToolInvoker(executor, { invokeOptions });\n return {\n invoke: ({ path, args }) => {\n if (path === \"search\") {\n if (!isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message:\n \"tools.search expects an object: { query?: string; namespace?: string; limit?: number; offset?: number }\",\n }),\n );\n }\n\n if (args.query !== undefined && typeof args.query !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.search query must be a string when provided\",\n }),\n );\n }\n\n if (args.namespace !== undefined && typeof args.namespace !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.search namespace must be a string when provided\",\n }),\n );\n }\n\n const limit = readOptionalLimit(args.limit, \"tools.search\");\n if (Predicate.isTagged(limit, \"ExecutionToolError\")) {\n return Effect.fail(limit);\n }\n\n const offset = readOptionalOffset(args.offset, \"tools.search\");\n if (Predicate.isTagged(offset, \"ExecutionToolError\")) {\n return Effect.fail(offset);\n }\n\n return searchTools(executor, args.query ?? \"\", limit, {\n namespace: args.namespace,\n offset,\n }).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: { \"mcp.tool.name\": path, \"executor.tool.builtin\": true },\n }),\n );\n }\n if (path === \"executor.sources.list\") {\n if (args !== undefined && !isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message:\n \"tools.executor.sources.list expects an object: { query?: string; limit?: number; offset?: number }\",\n }),\n );\n }\n\n if (isRecord(args) && args.query !== undefined && typeof args.query !== \"string\") {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.executor.sources.list query must be a string when provided\",\n }),\n );\n }\n\n const limit = readOptionalLimit(\n isRecord(args) ? args.limit : undefined,\n \"tools.executor.sources.list\",\n );\n if (Predicate.isTagged(limit, \"ExecutionToolError\")) {\n return Effect.fail(limit);\n }\n\n const offset = readOptionalOffset(\n isRecord(args) ? args.offset : undefined,\n \"tools.executor.sources.list\",\n );\n if (Predicate.isTagged(offset, \"ExecutionToolError\")) {\n return Effect.fail(offset);\n }\n\n return listExecutorSources(executor, {\n query: isRecord(args) && typeof args.query === \"string\" ? args.query : undefined,\n limit,\n offset,\n }).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: { \"mcp.tool.name\": path, \"executor.tool.builtin\": true },\n }),\n );\n }\n if (path === \"describe.tool\") {\n if (!isRecord(args)) {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.describe.tool expects an object: { path: string }\",\n }),\n );\n }\n\n if (typeof args.path !== \"string\" || args.path.trim().length === 0) {\n return Effect.fail(new ExecutionToolError({ message: \"describe.tool requires a path\" }));\n }\n\n if (\"includeSchemas\" in args) {\n return Effect.fail(\n new ExecutionToolError({\n message: \"tools.describe.tool no longer accepts includeSchemas\",\n }),\n );\n }\n\n return describeTool(executor, args.path).pipe(\n Effect.withSpan(\"mcp.tool.dispatch\", {\n attributes: {\n \"mcp.tool.name\": path,\n \"executor.tool.builtin\": true,\n \"executor.tool.target_path\": args.path,\n },\n }),\n );\n }\n return base.invoke({ path, args });\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// Execution Engine\n// ---------------------------------------------------------------------------\n\nexport type ExecutionEngine<E extends Cause.YieldableError = CodeExecutionError> = {\n /**\n * Execute code with elicitation handled inline by the provided handler.\n * Use this when the host supports elicitation (e.g. MCP with elicitation capability).\n *\n * Fails with the code executor's typed error `E` (defaults to\n * `CodeExecutionError`). Runtimes surface their own `Data.TaggedError`\n * subclass, which flows through here unchanged.\n */\n readonly execute: (\n code: string,\n options: { readonly onElicitation: ElicitationHandler },\n ) => Effect.Effect<ExecuteResult, E>;\n\n /**\n * Execute code, intercepting the first elicitation as a pause point.\n * Use this when the host doesn't support inline elicitation.\n * Returns either a completed result or a paused execution that can be resumed.\n */\n readonly executeWithPause: (code: string) => Effect.Effect<ExecutionResult, E>;\n\n /**\n * Resume a paused execution. Returns a completed result, a new pause, or\n * null if the executionId was not found.\n */\n readonly resume: (\n executionId: string,\n response: ResumeResponse,\n ) => Effect.Effect<ExecutionResult | null, E>;\n\n /**\n * Inspect a paused execution without resuming it. Returns null if the id is\n * unknown or has already been resumed.\n */\n readonly getPausedExecution: (executionId: string) => Effect.Effect<PausedExecution | null>;\n\n /**\n * Get the dynamic tool description (workflow + namespaces).\n */\n readonly getDescription: Effect.Effect<string>;\n};\n\nexport const createExecutionEngine = <E extends Cause.YieldableError = CodeExecutionError>(\n config: ExecutionEngineConfig<E>,\n): ExecutionEngine<E> => {\n const { executor, codeExecutor } = config;\n const pausedExecutions = new Map<string, InternalPausedExecution<E>>();\n let nextId = 0;\n\n /**\n * Race a running fiber against the pause queue. Returns when either\n * the fiber completes or an elicitation handler fires (whichever\n * comes first). Re-used by both executeWithPause and resume.\n *\n * `Effect.raceFirst` (not `Effect.race`) — `race` has prefer-success\n * semantics in Effect v4 (\"first successful result\"), which means a\n * fiber failure waits indefinitely for the pause Deferred to succeed.\n * For a fast `codeExecutor.execute` failure (e.g. a syntax error\n * inside the dynamic worker) the pause signal never fires, so the\n * outer Effect hangs until the upstream client gives up. `raceFirst`\n * settles on whichever side completes first, success or failure.\n */\n const awaitCompletionOrPause = (\n fiber: Fiber.Fiber<ExecuteResult, E>,\n pauseQueue: Queue.Queue<InternalPausedExecution<E>>,\n ): Effect.Effect<ExecutionResult, E> =>\n Effect.raceFirst(\n Fiber.join(fiber).pipe(\n Effect.map((result): ExecutionResult => ({ status: \"completed\", result })),\n ),\n Queue.take(pauseQueue).pipe(\n Effect.map((paused): ExecutionResult => ({ status: \"paused\", execution: paused })),\n ),\n );\n\n /**\n * Start an execution in pause/resume mode.\n *\n * The sandbox is forked as a daemon because paused executions can outlive the\n * caller scope that returned the first pause, such as an HTTP request handler.\n */\n const startPausableExecution = Effect.fn(\"mcp.execute\")(function* (code: string) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.mode\": \"pausable\",\n \"mcp.execute.code_length\": code.length,\n });\n\n // Queue preserves pauses that arrive before the previous approval has\n // returned to the caller, which can happen with concurrent tool calls.\n const pauseQueue = yield* Queue.unbounded<InternalPausedExecution<E>>();\n\n // Will be set once the fiber is forked.\n let fiber: Fiber.Fiber<ExecuteResult, E>;\n\n const elicitationHandler: ElicitationHandler = (ctx) =>\n Effect.gen(function* () {\n const responseDeferred = yield* Deferred.make<typeof ElicitationResponse.Type>();\n const id = `exec_${++nextId}`;\n\n const paused: InternalPausedExecution<E> = {\n id,\n elicitationContext: ctx,\n response: responseDeferred,\n fiber: fiber!,\n pauseQueue,\n };\n pausedExecutions.set(id, paused);\n\n yield* Queue.offer(pauseQueue, paused);\n\n // Suspend until resume() completes responseDeferred.\n return yield* Deferred.await(responseDeferred);\n });\n\n const invoker = makeFullInvoker(executor, { onElicitation: elicitationHandler });\n fiber = yield* Effect.forkDetach(\n codeExecutor.execute(code, invoker).pipe(Effect.withSpan(\"executor.code.exec\")),\n );\n\n return (yield* awaitCompletionOrPause(fiber, pauseQueue)) as ExecutionResult;\n });\n\n /**\n * Resume a paused execution. Completes the response Deferred to unblock the\n * fiber, then races completion against the next queued or future pause.\n */\n const resumeExecution = Effect.fn(\"mcp.execute.resume\")(function* (\n executionId: string,\n response: ResumeResponse,\n ) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.resume.action\": response.action,\n });\n\n const paused = pausedExecutions.get(executionId);\n if (!paused) return null;\n pausedExecutions.delete(executionId);\n\n yield* Deferred.succeed(paused.response, {\n action: response.action as typeof ElicitationResponse.Type.action,\n content: response.content,\n });\n\n return (yield* awaitCompletionOrPause(paused.fiber, paused.pauseQueue)) as ExecutionResult;\n });\n\n /**\n * Inline-elicitation execute path. Wrapped so every call produces an\n * `mcp.execute` span with the inner `executor.code.exec` as a child.\n */\n const runInlineExecution = Effect.fn(\"mcp.execute\")(function* (\n code: string,\n options: { readonly onElicitation: ElicitationHandler },\n ) {\n yield* Effect.annotateCurrentSpan({\n \"mcp.execute.mode\": \"inline\",\n \"mcp.execute.code_length\": code.length,\n });\n const invoker = makeFullInvoker(executor, {\n onElicitation: options.onElicitation,\n });\n return yield* codeExecutor.execute(code, invoker).pipe(Effect.withSpan(\"executor.code.exec\"));\n });\n\n return {\n execute: runInlineExecution,\n executeWithPause: startPausableExecution,\n resume: resumeExecution,\n getPausedExecution: (executionId) =>\n Effect.sync(() => pausedExecutions.get(executionId) ?? null),\n getDescription: buildExecuteDescription(executor),\n };\n};\n"],"mappings":";AAAA,YAAY,UAAU;AAUtB,SAAS,0BAA0B;AAR5B,IAAM,qBAAN,cAAsC,iBAAY,oBAAoB,EAG1E;AAAC;;;ACLJ,SAAS,QAAQ,iBAAiB;AAClC,YAAY,WAAW;AASvB,SAAS,cAAc,kBAAkB;AAIzC,IAAM,wBAAwB;AAC9B,IAAM,wBACJ;AAEF,IAAM,uBAAuB,CAAC,qBAC5B,qBAAqB,oBAAoB,SA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