@orkestrel/toolbox 0.0.21 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/core/index.cjs +62 -53
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +28 -9
- package/dist/src/core/index.d.ts +28 -9
- package/dist/src/core/index.js +64 -56
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +14 -15
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.js +14 -15
- package/dist/src/server/index.js.map +1 -1
- package/package.json +19 -19
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/shapers.ts","../../../src/core/helpers.ts","../../../src/core/compilers.ts","../../../src/core/stores/MemoryDefinitionStore.ts","../../../src/core/stores/DatabaseDefinitionStore.ts","../../../src/core/databases/DatabaseResolver.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { WorkflowDefinition } from '@orkestrel/workflow'\nimport type { WorkflowSteps, WorkspaceOperation } from './types.js'\n\n// Toolbox constants — UPPER_SNAKE, `Object.freeze`d, every member exported.\n// Toolbox owns the workflow tool's authoring text/examples/depth bound and the workspace tool's\n// name/description. The current workflow text describes Toolbox's authoring layer over\n// `@orkestrel/workflow`'s named-function and runner-owned persistence APIs; the workspace text\n// describes the editing surface Toolbox composes over `@orkestrel/workspace`.\n\n/**\n * Holds the name {@link import('./factories.js').createAgentTool} advertises by default, `'agent'`\n * — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const AGENT_TOOL_NAME = 'agent'\n\n/**\n * Holds the maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may\n * reach, `8` — the bound {@link import('./factories.js').createAgentTool}'s depth/cycle guard\n * enforces.\n *\n * @remarks\n * Deliberately a separate constant from {@link MAX_WORKFLOW_CHAIN} (rather than the guards\n * sharing one reference): they bound different chains (workflow nesting against agent\n * delegation) that happen to share a value today, and keeping this bound decoupled means a\n * future change to one never silently shifts the other. Same numeric value by convention, not\n * by shared reference.\n */\nexport const AGENT_TOOL_DEPTH = 8\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createAgentTool} advertises in place of\n * {@link AGENT_TOOL_DESCRIPTION} — one sentence offering sub-agent delegation and pointing at\n * `describe` for the optional overrides.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const AGENT_TOOL_SUMMARY =\n\t\"Delegate a task to a sub-agent and return its result; each call runs one sub-agent turn to completion. Call describe('agent') for the optional provider/tools/system overrides.\"\n\n/**\n * Holds the description {@link import('./factories.js').createAgentTool} advertises — a short guide\n * covering the required task and optional provider, tools, and system overrides.\n */\nexport const AGENT_TOOL_DESCRIPTION = [\n\t'Delegate a task to a sub-agent and return its result. Every call runs ONE sub-agent turn to completion.',\n\t'',\n\t'Required:',\n\t' task - the instructions the sub-agent carries out.',\n\t'Optional overrides (default to the values this tool was configured with):',\n\t' provider - the registry key of the model/provider the sub-agent runs against.',\n\t' tools - registry keys of the tools loaded into the sub-agent (replaces the default list, not merged).',\n\t\" system - a system prompt seeding the sub-agent's context (replaces the default).\",\n\t'Example:',\n\tJSON.stringify({\n\t\ttask: 'Summarize the attached notes in three bullet points.',\n\t}),\n].join('\\n')\n\n/**\n * Holds the maximum nesting depth a workflow → agent → workflow chain may reach, `8` — the bound\n * {@link import('./factories.js').createAgentFunction} and\n * {@link import('./factories.js').createWorkflowTool}'s depth/cycle guards enforce.\n *\n * @remarks\n * Depth is zero-based and counts workflow tags after the root: the root plus eight nested\n * workflows is allowed, while a ninth nested workflow is rejected with this package's typed\n * `DEPTH` `ToolboxError`.\n */\nexport const MAX_WORKFLOW_CHAIN = 8\n\n/**\n * Holds the name {@link import('./factories.js').createWorkflowTool} advertises by default,\n * `'workflow'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under, and the name {@link import('./factories.js').createAgentFunction} binds the\n * depth/cycle-aware workflow tool under onto a wrapped agent's `context.tools`.\n *\n * @remarks\n * The propagation seam's well-known key: when\n * `createAgentFunction`'s `runner` option is supplied, it adds a `createWorkflowTool`-built tool\n * under this name to the agent's `context.tools`, so it can author and run a nested workflow\n * (bounded by {@link MAX_WORKFLOW_CHAIN}).\n */\nexport const WORKFLOW_TOOL_NAME = 'workflow'\n\n/**\n * Holds a complete flat authoring example — the primary way a small model authors a workflow\n * through {@link import('./factories.js').createWorkflowTool}: `{ name, steps: [{ name }] }`.\n *\n * @remarks\n * Each step becomes a one-task phase, in\n * order; a step's `name` is a registered behavior name (not a label) — the registry key its\n * task's `behavior` resolves against. The tool expands this\n * ({@link import('./helpers.js').expandSteps}) into a valid `WorkflowDefinition`\n * (`@orkestrel/workflow`). It is embedded verbatim in {@link WORKFLOW_TOOL_DESCRIPTION}.\n */\nexport const WORKFLOW_TOOL_FLAT_EXAMPLE: WorkflowSteps = Object.freeze({\n\tname: 'release',\n\tsteps: Object.freeze([Object.freeze({ name: 'compile' }), Object.freeze({ name: 'publish' })]),\n})\n\n/**\n * Holds a minimal nested authoring example — the advanced escape-hatch form a model can use instead\n * of the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).\n *\n * @remarks\n * The full nested form, documented in\n * {@link WORKFLOW_TOOL_DESCRIPTION} as the advanced alternative. It is embedded verbatim.\n */\nexport const WORKFLOW_TOOL_NESTED_EXAMPLE: WorkflowDefinition = Object.freeze({\n\tid: 'release',\n\tname: 'Release',\n\tphases: Object.freeze([\n\t\tObject.freeze({\n\t\t\tid: 'build',\n\t\t\tname: 'Build',\n\t\t\ttasks: Object.freeze([\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: 'compile',\n\t\t\t\t\tname: 'Compile',\n\t\t\t\t\tbehavior: 'compile',\n\t\t\t\t}),\n\t\t\t]),\n\t\t}),\n\t]),\n})\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createWorkflowTool} advertises in place of\n * {@link WORKFLOW_TOOL_DESCRIPTION} — one sentence offering multi-phase authoring and pointing at\n * `describe` for the authoring schema and its examples.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const WORKFLOW_TOOL_SUMMARY =\n\t\"Author and run a multi-phase workflow in one call — phases run in sequence, tasks within a phase run concurrently. Call describe('workflow') for the full authoring schema and examples.\"\n\n/**\n * Holds the description {@link import('./factories.js').createWorkflowTool} advertises — the flat\n * authoring form, its worked example, and the advanced nested definition form.\n */\nexport const WORKFLOW_TOOL_DESCRIPTION = [\n\t'Author and run a workflow (phases run sequentially, the tasks within a phase run concurrently) in one call.',\n\t'',\n\t'SIMPLEST way — a flat list of steps. Each step runs one registered behavior; steps run one after another:',\n\t' { \"name\": \"<workflow name>\", \"steps\": [ { \"name\": \"<registered name>\" }, ... ] }',\n\t'- a step\\'s \"name\" is a REGISTERED behavior name (a registry key), NOT a human label.',\n\t'- every step name must exist in the host-supplied functions registry; an unknown name is rejected.',\n\t'- the top-level \"name\" is optional; when present it is also the workflow persistence id. Other ids are filled in for you.',\n\t'Example:',\n\tJSON.stringify(WORKFLOW_TOOL_FLAT_EXAMPLE),\n\t'',\n\t'ADVANCED — the full nested form, for multi-task phases or explicit ids. A workflow has phases; a phase has tasks; a task may have a \"behavior\" (a registered behavior name); omitting it creates a JSON-null no-op:',\n\tJSON.stringify(WORKFLOW_TOOL_NESTED_EXAMPLE),\n\t'In the nested form you may omit any \"id\"/\"name\" and they are filled in positionally; a provided one is kept.',\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createWorkspaceTool} advertises by default,\n * `'workspace'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`)\n * registers under.\n */\nexport const WORKSPACE_TOOL_NAME = 'workspace'\n\n/**\n * Holds a valid {@link import('./types.js').WorkspaceOperation} object — the canonical example\n * embedded verbatim in {@link WORKSPACE_TOOL_DESCRIPTION}.\n *\n * @remarks\n * A `'write'` op (the most common authoring\n * action): create or overwrite `notes.txt` with `hello`. Frozen so it cannot be mutated in\n * place.\n */\nexport const WORKSPACE_TOOL_EXAMPLE: WorkspaceOperation = Object.freeze({\n\toperation: 'write',\n\tpath: 'notes.txt',\n\tcontent: 'hello',\n})\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createWorkspaceTool} advertises in place of\n * {@link WORKSPACE_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed file editing and\n * pointing at `describe` for the operation list and its fields.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const WORKSPACE_TOOL_SUMMARY =\n\t\"Read and edit files in a workspace — one operation per call (read, write, list, search, replace, splice, move, remove, plus workspace switching), chosen by the 'operation' field. Call describe('workspace') for the full operation list and fields.\"\n\n/**\n * Holds the description {@link import('./factories.js').createWorkspaceTool} advertises — the\n * operation-keyed workspace protocol, all supported operations, and worked examples.\n *\n * @remarks\n * Mirrors {@link WORKFLOW_TOOL_DESCRIPTION}'s teaching style and embeds\n * {@link WORKSPACE_TOOL_EXAMPLE} verbatim.\n */\nexport const WORKSPACE_TOOL_DESCRIPTION = [\n\t'Read and edit files in a workspace. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'All file operations act on the ACTIVE workspace; use \"workspaces\" then \"switch\" to move between workspaces.',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- read { \"operation\": \"read\", \"path\": \"<file>\" } — return the file\\'s text.',\n\t'- list { \"operation\": \"list\" } — list every file in the active workspace (path, state, size, lines, kind).',\n\t'- has { \"operation\": \"has\", \"path\": \"<file>\" } — whether the file exists.',\n\t'- search { \"operation\": \"search\", \"query\": \"<text>\", \"regex\"?: bool, \"sensitive\"?: bool, \"limit\"?: int } — find lines matching the query across all files.',\n\t'- replace { \"operation\": \"replace\", \"query\": \"<text>\", \"replacement\": \"<text>\", \"regex\"?: bool, \"sensitive\"?: bool, \"limit\"?: int } — replace matches across all files.',\n\t'- write { \"operation\": \"write\", \"path\": \"<file>\", \"content\": \"<text>\" } — create or overwrite the whole file.',\n\t'- splice { \"operation\": \"splice\", \"path\": \"<file>\", \"content\": \"<text>\", \"fromLine\": int, \"fromColumn\": int, \"toLine\": int, \"toColumn\": int } — replace a 1-based range (from inclusive, to exclusive) with content.',\n\t'- prepend { \"operation\": \"prepend\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the start of the file.',\n\t'- append { \"operation\": \"append\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the end of the file.',\n\t'- move { \"operation\": \"move\", \"from\": \"<file>\", \"to\": \"<file>\" } — rename / move a file.',\n\t'- remove { \"operation\": \"remove\", \"path\": \"<file>\" } — delete a file.',\n\t'- workspaces { \"operation\": \"workspaces\" } — list the workspaces you can switch between (each id, file count, active).',\n\t'- switch { \"operation\": \"switch\", \"id\": \"<id>\" } — make the workspace with that id active (ids come from \"workspaces\").',\n\t'',\n\t'Notes: lines and columns are 1-based (column 1 is the first character). \"regex\" defaults to false (a literal substring), \"sensitive\" defaults to true (case-sensitive). \"search\"/\"replace\"/\"splice\" act only on text files. Editing with no active workspace auto-creates one.',\n\t'',\n\t'Example — write a file:',\n\tJSON.stringify(WORKSPACE_TOOL_EXAMPLE),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createDescribeTool} advertises by default,\n * `'describe'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n *\n * @remarks\n * Pairs with the lean {@link AGENT_TOOL_SUMMARY} / {@link WORKFLOW_TOOL_SUMMARY} /\n * {@link WORKSPACE_TOOL_SUMMARY} — a model that reads only the\n * advertised summary can call `describe` with that tool's registered name to get its full\n * teaching description back.\n */\nexport const DESCRIBE_TOOL_NAME = 'describe'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createDescribeTool}\n * advertises — this tool needs no teaching of its own, so its summary and description are both\n * short.\n */\nexport const DESCRIBE_TOOL_SUMMARY = 'Return the full description of a named registered tool.'\n\n/**\n * Holds the description {@link import('./factories.js').createDescribeTool} advertises — the\n * registered tool `name` it requires, and the full description of that tool it returns.\n *\n * @remarks\n * Deliberately short — unlike the workflow / workspace / agent tools, this one has no authoring\n * schema or multi-step protocol to teach.\n */\nexport const DESCRIBE_TOOL_DESCRIPTION =\n\t'Return the full description of a registered tool by its name. Required: name - the registered tool name (see another tool listing for available names).'\n\n/**\n * Holds the name {@link import('./factories.js').createPromptTool} advertises by default, `'ask'` —\n * the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const PROMPT_TOOL_NAME = 'ask'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createPromptTool} advertises in place of\n * {@link PROMPT_TOOL_DESCRIPTION} — one sentence offering the blocking multi-field ask and pointing\n * at `describe` for the schema.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const PROMPT_TOOL_SUMMARY =\n\t\"Ask another terminal a multi-field form and BLOCK until it answers; the call resolves with the values record. Call describe('ask') for the schema.\"\n\n/**\n * Holds the form protocol {@link import('./factories.js').createPromptTool} advertises — the\n * required `to` and `schema`, how a field declares its control and its rules, and a worked\n * example.\n */\nexport const PROMPT_TOOL_DESCRIPTION = [\n\t'Ask another terminal a multi-field form and block until it answers. This call does not return until the addressed terminal answers, or the form expires.',\n\t'',\n\t'Required:',\n\t' to - the terminal name to ask.',\n\t' schema - an @orkestrel/form schema: each field declares `control` and `name`, plus optional `label`, `rule`, `default`, and `choices`; `fields` is an ordered array and each `name` must be unique.',\n\t'The result is one values object keyed by those field names. A cycle or expired form fails with a typed error.',\n\t'Example:',\n\tJSON.stringify({\n\t\tto: 'reviewer',\n\t\tschema: {\n\t\t\tlabel: 'Release review',\n\t\t\tfields: [\n\t\t\t\t{ control: 'confirm', name: 'approved', label: 'Approve the release?' },\n\t\t\t\t{ control: 'editor', name: 'notes', label: 'Review notes' },\n\t\t\t],\n\t\t},\n\t}),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createAnswerTool} advertises by default,\n * `'answer'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const ANSWER_TOOL_NAME = 'answer'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createAnswerTool} advertises in place of\n * {@link ANSWER_TOOL_DESCRIPTION} — one sentence offering the pending listing and the answer call,\n * and pointing at `describe` for the fields each takes.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const ANSWER_TOOL_SUMMARY =\n\t\"List forms addressed to this terminal, or answer one by id with a values record. Call describe('answer') for the required fields.\"\n\n/**\n * Holds the protocol {@link import('./factories.js').createAnswerTool} advertises — the `pending`\n * and `answer` operations and the `values` record an answer supplies, each with a worked example.\n */\nexport const ANSWER_TOOL_DESCRIPTION = [\n\t'List the forms addressed to this terminal, or answer one of them by id. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'',\n\t'Operations:',\n\t'- pending { \"operation\": \"pending\" } — list every form addressed to this terminal (id, from, schema).',\n\t'- answer { \"operation\": \"answer\", \"id\": \"<form id>\", \"values\": { \"<field name>\": <field value> } } — answer every required field with the value its control accepts.',\n\t'Example — list pending forms:',\n\tJSON.stringify({ operation: 'pending' }),\n\t'Example — answer one:',\n\tJSON.stringify({ operation: 'answer', id: 'abc123', values: { approved: true, notes: 'Ready' } }),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createDatabaseTool} advertises by default,\n * `'database'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const DATABASE_TOOL_NAME = 'database'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createDatabaseTool} advertises in place of\n * {@link DATABASE_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed database call and\n * pointing at `describe` for the operation list, the query form, and the column DSL.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const DATABASE_TOOL_SUMMARY =\n\t\"Create and query a database — one operation per call (create, tables, get, records, count, aggregate, add, set, update, remove, destroy), chosen by the 'operation' field. Call describe('database') for the full operation list, the query form, and the column DSL.\"\n\n/**\n * Holds the description {@link import('./factories.js').createDatabaseTool} advertises — a\n * multi-line guide that teaches a small model the operation list, the serialized query form, and\n * the {@link import('./types.js').TableSpec} column DSL.\n *\n * @remarks\n * The query form is deliberately serialized (never fluent) — every condition is a flat object\n * `{ column, operator, values, connector? }` where `values` is always an array, even for a\n * single-value operator (`{ column: 'age', operator: 'from', values: [18] }`), so a small model\n * never has to chain method calls or guess whether a value is scalar or a list.\n */\nexport const DATABASE_TOOL_DESCRIPTION = [\n\t'Create and query a database. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- create { \"operation\": \"create\", \"id\": \"<database id>\", \"tables\": { \"<table>\": { \"columns\": { \"<column>\": \"string\" | \"integer\" | \"number\" | \"boolean\" | { \"primitive\": \"string\", \"optional\": true } } } }, \"primary\"?: { \"<table>\": \"<column>\" }, \"indexes\"?: { \"<table>\": [[\"<column>\"]] }, \"version\"?: <number> } — define a new database.',\n\t'- tables { \"operation\": \"tables\", \"id\": \"<database id>\" } — list a database\\'s table names.',\n\t'- get { \"operation\": \"get\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — fetch one row by its primary key.',\n\t'- records { \"operation\": \"records\", \"id\": \"<database id>\", \"table\": \"<table>\", \"query\"?: <Query> } — list rows matching a query.',\n\t'- count { \"operation\": \"count\", \"id\": \"<database id>\", \"table\": \"<table>\", \"query\"?: <Query> } — count rows matching a query.',\n\t'- aggregate { \"operation\": \"aggregate\", \"id\": \"<database id>\", \"table\": \"<table>\", \"column\": \"<column>\", \"function\": \"count\" | \"sum\" | \"average\" | \"minimum\" | \"maximum\", \"query\"?: <Query> } — compute an aggregate.',\n\t'- add { \"operation\": \"add\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — insert a row (fails on a duplicate key).',\n\t'- set { \"operation\": \"set\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — upsert a row.',\n\t'- update { \"operation\": \"update\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\", \"changes\": { ... } } — patch an existing row.',\n\t'- remove { \"operation\": \"remove\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — delete a row by key.',\n\t'- destroy { \"operation\": \"destroy\", \"id\": \"<database id>\" } — drop a database entirely.',\n\t'',\n\t'Query form — SERIALIZED, never fluent. A condition is a flat object; \"values\" is ALWAYS an array, even for one value:',\n\t' { \"conditions\": [ { \"column\": \"age\", \"operator\": \"from\", \"values\": [18], \"connector\": \"and\" } ], \"order\"?: [...], \"offset\"?: 0, \"limit\"?: 100 }',\n\t' operators: equals, not, above, below, from, to, between, like, glob, starts, ends, any, none, absent, present.',\n\t' \"connector\" joins this condition to the next (\"and\" | \"or\"); omit on the last condition.',\n\t'',\n\t'Column DSL (used by \"create\" \"tables\"): a column is either a bare primitive string (\"string\" | \"integer\" | \"number\" | \"boolean\"), or { \"primitive\": \"<primitive>\", \"optional\": true } when the column may be absent from a row.',\n\t'Schema configuration is creation-time only. Evolve a schema by opening a newly configured target-version database over a versioned persistent driver; reconciliation requires paired metadata/stamp capabilities.',\n\t'Example — create a database:',\n\tJSON.stringify({\n\t\toperation: 'create',\n\t\tid: 'shop',\n\t\ttables: {\n\t\t\tproducts: {\n\t\t\t\tcolumns: {\n\t\t\t\t\tname: 'string',\n\t\t\t\t\tprice: 'number',\n\t\t\t\t\tnotes: { primitive: 'string', optional: true },\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}),\n\t'Example — query records:',\n\tJSON.stringify({\n\t\toperation: 'records',\n\t\tid: 'shop',\n\t\ttable: 'products',\n\t\tquery: { conditions: [{ column: 'price', operator: 'below', values: [50] }] },\n\t}),\n].join('\\n')\n\n/**\n * Holds the default cap on rows a `records` call returns when the caller omits `query.limit`,\n * `1000` — the database tool's default row ceiling.\n */\nexport const DATABASE_TOOL_LIMIT = 1000\n\n/** Lists the runtime-frozen database-tool mutation names disabled by `DatabaseToolOptions.readonly`. */\nexport const DATABASE_TOOL_MUTATIONS: readonly string[] = Object.freeze([\n\t'create',\n\t'add',\n\t'set',\n\t'update',\n\t'remove',\n\t'destroy',\n])\n\n/**\n * Holds the name {@link import('./factories.js').createRelationTool} advertises by default,\n * `'relation'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const RELATION_TOOL_NAME = 'relation'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createRelationTool} advertises in place of\n * {@link RELATION_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed relationship\n * traversal and pointing at `describe` for the include-path syntax.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const RELATION_TOOL_SUMMARY =\n\t\"Traverse and edit relationships between database rows — one operation per call (load, find, link, unlink, links), chosen by the 'operation' field. Call describe('relation') for the include-path syntax.\"\n\n/**\n * Holds the description {@link import('./factories.js').createRelationTool} advertises — a\n * multi-line guide that teaches a small model the operation list and the flat dot-path `include`\n * syntax.\n *\n * @remarks\n * An include path is a flat dot-separated string (`'contacts.account'`), never a nested object —\n * the same small-model ergonomic lever the other tools in this package use for flat args.\n */\nexport const RELATION_TOOL_DESCRIPTION = [\n\t'Traverse and edit relationships between database rows. Every call is ONE operation, chosen by the \"operation\" field. \"manager\" is optional (omit it when only one relation manager is registered).',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- load { \"operation\": \"load\", \"model\": \"<model>\", \"key\": \"<row key>\", \"include\"?: [\"<path>\", ...] } — fetch one (or, with an array key, several) row(s) with related rows attached.',\n\t'- find { \"operation\": \"find\", \"model\": \"<model>\", \"include\"?: [\"<path>\", ...], \"limit\"?: <n>, \"offset\"?: <n>, \"sort\"?: \"<column>\", \"direction\"?: \"ascending\"|\"descending\" } — list rows, each with related rows attached.',\n\t'- link { \"operation\": \"link\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — connect two rows through a \"through\" relation.',\n\t'- unlink { \"operation\": \"unlink\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — disconnect two rows.',\n\t'- links { \"operation\": \"links\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\" } — list every key linked to a row through a \"through\" relation.',\n\t'',\n\t'\"include\" is a FLAT dot-path array (not nested objects) — each string names a chain of relations to attach, up to the configured depth cap. Example: \"contacts.account\" attaches each row\\'s contacts, and each contact\\'s account.',\n\t'Example — load a row with two levels of relations:',\n\tJSON.stringify({ operation: 'load', model: 'orders', key: '1', include: ['contacts.account'] }),\n].join('\\n')\n\n/**\n * Holds the default cap on rows a `find` or `links` call returns when the caller omits `limit`,\n * `1000` — the relation tool's default row ceiling.\n */\nexport const RELATION_TOOL_LIMIT = 1000\n\n/**\n * Holds the default cap on how many `include` path segments deep a `load` or `find` call may\n * traverse, `3` — the relation tool's default include-depth ceiling.\n */\nexport const RELATION_TOOL_DEPTH = 3\n\n/**\n * Holds the name {@link import('./factories.js').createInferTool} advertises by default, `'infer'`\n * — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const INFER_TOOL_NAME = 'infer'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createInferTool} advertises in place of\n * {@link INFER_TOOL_DESCRIPTION} — one sentence offering schema inference from example values and\n * pointing at `describe` for the fields it takes.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const INFER_TOOL_SUMMARY =\n\t\"Infer a JSON Schema (as advertised tool parameters) from one or more example values. Call describe('infer') for the required fields.\"\n\n/**\n * Holds the schema-inference protocol {@link import('./factories.js').createInferTool} advertises —\n * the required `samples`, the optional `format`, `enum`, and `candidates` arguments, and a worked\n * example of the bare return and of the `candidates`-wrapped return.\n */\nexport const INFER_TOOL_DESCRIPTION = [\n\t'Infer a JSON Schema from example values, returned in the same shape a tool advertises its parameters.',\n\t'',\n\t'Required:',\n\t' samples - an array of at least one example value to infer the schema from.',\n\t'Optional:',\n\t' format - infer string formats (date-time, email, ...) from the samples. Defaults to false.',\n\t' enum - infer enum constraints from repeated literal values across the samples. Defaults to false.',\n\t' candidates - values to check against the freshly inferred schema. When present, the result',\n\t' is wrapped as { parameters, checks } instead of the bare parameters record, one',\n\t' check per candidate (same index). Every check has the uniform shape',\n\t' { index, valid, coercible, faults? }. `valid` is a STRICT verdict (no coercion)',\n\t' — for example the number 7 is NOT valid against a string slot. `coercible` answers a',\n\t' separate question: would the SAME value be accepted by an endpoint tool call,',\n\t\" whose enforcement NORMALIZES args (7 coerces to '7')? So 7 against a string slot\",\n\t' yields { valid: false, coercible: true, faults: [] } — a strict mismatch that',\n\t' normalization would silently accept, so faults is EMPTY. `faults` only ever',\n\t' populates for a non-coercible mismatch (a wrong type normalization cannot fix,',\n\t' a missing required key, an out-of-enum value); checks never throw, regardless of',\n\t' candidate shape.',\n\t'Example (no candidates):',\n\t` in: ${JSON.stringify({\n\t\tsamples: [\n\t\t\t{ id: 1, name: 'Ada' },\n\t\t\t{ id: 2, name: 'Bob' },\n\t\t],\n\t})}`,\n\t` out: ${JSON.stringify({\n\t\ttype: 'object',\n\t\tproperties: { id: { type: 'integer' }, name: { type: 'string' } },\n\t\trequired: ['id', 'name'],\n\t\tadditionalProperties: false,\n\t})}`,\n\t'Example (with candidates):',\n\t` in: ${JSON.stringify({\n\t\tsamples: [{ id: 1, name: 'Ada' }],\n\t\tcandidates: [\n\t\t\t{ id: 3, name: 'Cy' },\n\t\t\t{ id: 'x', name: 'Cy' },\n\t\t\t{ id: 1, name: 7 },\n\t\t],\n\t})}`,\n\t` out: ${JSON.stringify({\n\t\tparameters: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { id: { type: 'integer' }, name: { type: 'string' } },\n\t\t\trequired: ['id', 'name'],\n\t\t\tadditionalProperties: false,\n\t\t},\n\t\tchecks: [\n\t\t\t{ index: 0, valid: true, coercible: true },\n\t\t\t{ index: 1, valid: false, coercible: false, faults: '<structured faults>' },\n\t\t\t{ index: 2, valid: false, coercible: true, faults: [] },\n\t\t],\n\t})}`,\n].join('\\n')\n","import type { ToolboxErrorCode } from './types.js'\nimport { isInstance } from '@orkestrel/contract'\n\n// Toolbox errors — one error class per domain this package mints its own error for.\n// `@orkestrel/workflow`'s `WorkflowError` and `@orkestrel/workspace`'s `WorkspaceError` already\n// cover their genuine domain failure paths (imported and thrown as-is, never duplicated here\n// under AGENTS' no-superfluous-wrappers law). Neither package error fits this package's own\n// malformed-call and resolution guards, so this package mints one typed error, `ToolboxError`,\n// mirroring `WorkflowError`'s exact shape (`code` and an optional `context`) for the same reason:\n// a thrown, machine-readable, code-bearing error after AGENTS' “narrow untrusted input with\n// guards” boundary rejects a call, never a `{ error }` return. `ToolboxError` is this package's\n// general tool-call error — not scoped to agent delegation alone — so every package-owned `TOOL`\n// misuse shares it rather than minting one error class per tool.\n\n/**\n * Represents a package-owned tool-call failure: malformed input or unresolved configuration (`TOOL`),\n * delegation depth/cycle rejection (`DEPTH`), prompt failure (`DEADLOCK` / `EXPIRE` / `ANSWER`),\n * or a translated upstream database/relation failure (`DATABASE` / `RELATION`).\n *\n * @remarks\n * Carries a machine-readable `code` (see {@link import('./types.js').ToolboxErrorCode}) and\n * an optional `context` bag for structured diagnostics. They are readable through an in-process\n * catch, including around a direct `tool.execute(args, context)` call. The `ToolManagerInterface`\n * (`@orkestrel/tool`) instead flattens every throw to the canonical tool result's top-level\n * `error` message string under AGENTS' “narrow untrusted input with guards” rule.\n *\n * @example\n * ```ts\n * import { ToolboxError, isToolboxError } from '@src/core'\n *\n * try {\n * \tthrow new ToolboxError('TOOL', 'task is required')\n * } catch (error) {\n * \tif (isToolboxError(error)) console.log(error.code) // 'TOOL'\n * }\n * ```\n */\nexport class ToolboxError extends Error {\n\treadonly code: ToolboxErrorCode\n\tdeclare readonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: ToolboxErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'ToolboxError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link ToolboxError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is an {@link ToolboxError}; false otherwise\n *\n * @example\n * ```ts\n * import { isToolboxError } from '@src/core'\n *\n * try {\n * \t// ...\n * } catch (error) {\n * \tif (isToolboxError(error)) console.log(error.code)\n * }\n * ```\n */\nexport function isToolboxError(value: unknown): value is ToolboxError {\n\treturn isInstance(value, ToolboxError)\n}\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tAgentFunction,\n\tColumnPrimitive,\n\tColumnSpec,\n\tDatabaseDefinition,\n\tWorkflowLineage,\n} from './types.js'\nimport {\n\tattempt,\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisFunction,\n\tisNonEmptyString,\n\tisRecord,\n\tisString,\n\tliteralOf,\n} from '@orkestrel/contract'\n\n// Toolbox guards — the total `(value: unknown) => value is T` narrows this package applies at its\n// untrusted boundaries: an authored lineage, a frozen agent adapter, the small-model column DSL,\n// and a persisted database definition read back from a store.\n\n/**\n * Narrows an unknown value to a valid alternating workflow lineage.\n *\n * @param value - The value to inspect\n * @returns True if `value` is a unique, nonempty-tagged workflow/agent chain; false otherwise\n */\nexport function isWorkflowLineage(value: unknown): value is WorkflowLineage {\n\tconst inspected = attempt(() => {\n\t\tif (!isArray(value)) return false\n\t\tconst seen = new Set<string>()\n\t\tfor (const [index, tag] of value.entries()) {\n\t\t\tif (!isString(tag)) return false\n\t\t\tconst prefix = index % 2 === 0 ? 'workflow:' : 'agent:'\n\t\t\tif (!tag.startsWith(prefix) || tag.length === prefix.length || seen.has(tag)) return false\n\t\t\tseen.add(tag)\n\t\t}\n\t\treturn true\n\t})\n\treturn inspected.success && inspected.value\n}\n\n/**\n * Narrows an unknown callable to Toolbox's frozen contextual agent adapter metadata.\n *\n * @param value - The value to inspect\n * @returns True if it is a frozen {@link AgentFunction} with a frozen valid lineage; false otherwise\n */\nexport function isAgentFunction(value: unknown): value is AgentFunction {\n\tconst inspected = attempt(() => {\n\t\tif (!isFunction(value) || !Object.isFrozen(value)) return false\n\t\tconst category = Reflect.getOwnPropertyDescriptor(value, 'category')\n\t\tconst lineage = Reflect.getOwnPropertyDescriptor(value, 'lineage')\n\t\treturn (\n\t\t\tcategory?.value === 'agent' &&\n\t\t\tlineage !== undefined &&\n\t\t\t'value' in lineage &&\n\t\t\tObject.isFrozen(lineage.value) &&\n\t\t\tisWorkflowLineage(lineage.value)\n\t\t)\n\t})\n\treturn inspected.success && inspected.value\n}\n\n/**\n * Narrows an unknown value to a {@link ColumnSpec}.\n *\n * @param value - The value to inspect\n * @returns True if `value` is a valid {@link ColumnPrimitive} shorthand or a `{ primitive, optional }` record with a valid `primitive`; false otherwise\n */\nexport function isColumnSpec(value: unknown): value is ColumnSpec {\n\tif (isColumnPrimitive(value)) return true\n\tif (!isRecord(value)) return false\n\treturn (\n\t\tisColumnPrimitive(value.primitive) &&\n\t\t(value.optional === undefined || isBoolean(value.optional))\n\t)\n}\n\n/**\n * Narrows an unknown value to a {@link ColumnPrimitive}.\n *\n * @param value - The value to inspect\n * @returns True if `value` is `'string'`, `'integer'`, `'number'`, or `'boolean'`; false otherwise\n */\nexport const isColumnPrimitive: Guard<ColumnPrimitive> = literalOf(\n\t'string',\n\t'integer',\n\t'number',\n\t'boolean',\n)\n\n/**\n * Narrows an unknown value to a {@link DatabaseDefinition} — a non-empty `id` and `driver`, a\n * `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, plus optional\n * `primary`, `indexes`, and finite `version` schema configuration. The boundary guard a\n * {@link import('./types.js').DefinitionStoreInterface} applies to an untrusted persisted blob\n * before trusting it as a definition (never an `as`).\n *\n * @param value - The value to inspect\n * @returns True if `value` is a complete {@link DatabaseDefinition}; false otherwise\n */\nexport function isDatabaseDefinition(value: unknown): value is DatabaseDefinition {\n\tif (!isRecord(value)) return false\n\tif ('keys' in value) return false\n\tif (!isNonEmptyString(value.id) || !isNonEmptyString(value.driver)) return false\n\tif (!isRecord(value.tables)) return false\n\tfor (const table of Object.values(value.tables)) {\n\t\tif (!isRecord(table) || !isRecord(table.columns)) return false\n\t\tfor (const column of Object.values(table.columns)) {\n\t\t\tif (!isColumnSpec(column)) return false\n\t\t}\n\t}\n\tif (value.primary !== undefined) {\n\t\tif (!isRecord(value.primary)) return false\n\t\tfor (const key of Object.values(value.primary)) {\n\t\t\tif (!isNonEmptyString(key)) return false\n\t\t}\n\t}\n\tif (value.indexes !== undefined) {\n\t\tif (!isRecord(value.indexes)) return false\n\t\tfor (const groups of Object.values(value.indexes)) {\n\t\t\tif (!isArray(groups)) return false\n\t\t\tfor (const group of groups) {\n\t\t\t\tif (!isArray(group) || group.length === 0) return false\n\t\t\t\tfor (const column of group) {\n\t\t\t\t\tif (!isNonEmptyString(column)) return false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (value.version !== undefined && !isFiniteNumber(value.version)) return false\n\treturn true\n}\n","import {\n\tarrayShape,\n\tbooleanShape,\n\tintegerShape,\n\tjsonShape,\n\tliteralShape,\n\tnumberShape,\n\tobjectShape,\n\toptionalShape,\n\trecordShape,\n\tstringShape,\n\tunionShape,\n} from '@orkestrel/contract'\nimport { MAX_TIMER_MS } from '@orkestrel/workflow'\n\n// === Prompt / answer shapes (createPromptTool / createAnswerTool call args)\n\n/**\n * Describes the shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` names the\n * terminal identity and `schema` carries the complete multi-field form document.\n *\n * @remarks\n * The contract first requires exact JSON. The handler then delegates schema parsing and semantic\n * validation to `@orkestrel/form`'s `parseForm`, so Toolbox does not duplicate the form schema.\n */\nexport const promptToolShape = objectShape({\n\tto: stringShape({ min: 1, description: 'The terminal identity to address the form to.' }),\n\tschema: jsonShape({\n\t\tdescription:\n\t\t\t'The @orkestrel/form schema to ask, with form metadata and one or more typed fields.',\n\t}),\n})\n\n/**\n * Describes the shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated\n * by `operation`: `'pending'` lists the forms addressed to this tool's terminal, while `'answer'`\n * resolves one by `id` with a complete `values` record.\n *\n * @remarks\n * `values` is first bounded to exact JSON. The handler then narrows it with the originating Form\n * package's `isFormValues` guard before the terminal manager applies it to the parked live form.\n */\nexport const answerToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['pending'], {\n\t\t\tdescription: 'List the forms addressed to this terminal.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['answer'], { description: 'Answer one pending form by id.' }),\n\t\tid: stringShape({ min: 1, description: 'The id of the pending form to answer.' }),\n\t\tvalues: jsonShape({ description: 'The form answers keyed by field name.' }),\n\t}),\n)\n\n// Toolbox shapes — the shape value each `create*Tool` factory (factories.ts) compiles into\n// the lockstep guard, parser, and JSON Schema outputs. `agentToolShape` must agree\n// with the hand-written `AgentToolArguments` (types.ts), which is the source of truth.\n// `workflowStepsShape` / `workflowDraftShape` are Toolbox's authoring boundary over the current\n// `@orkestrel/workflow` definition contract. `workspaceToolShape` is Toolbox's operation boundary\n// over the editing primitives now owned by `@orkestrel/workspace`.\n\n/**\n * Describes the shape of {@link import('./types.js').AgentToolArguments} —\n * {@link import('./factories.js').createAgentTool}'s advertised `parameters`.\n *\n * @remarks\n * `task` is the only required field (a non-empty string); `provider` / `tools` / `system`\n * are per-call overrides of the tool's own configured defaults.\n */\nexport const agentToolShape = objectShape({\n\ttask: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The instructions the sub-agent carries out.',\n\t}),\n\tprovider: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'Registry key of the provider to run the sub-agent against (overrides the default).',\n\t\t}),\n\t),\n\ttools: optionalShape(\n\t\tarrayShape(stringShape({ min: 1 }), {\n\t\t\tdescription:\n\t\t\t\t'Registry keys of the tools loaded into the sub-agent (replaces the default list).',\n\t\t}),\n\t),\n\tsystem: optionalShape(\n\t\tstringShape({\n\t\t\tdescription: \"A system prompt seeding the sub-agent's context (overrides the default).\",\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of {@link import('./types.js').DescribeToolArguments} —\n * {@link import('./factories.js').createDescribeTool}'s advertised `parameters`.\n *\n * @remarks\n * `name` is the only field (a non-empty string) — the registered tool name to look up.\n */\nexport const describeToolShape = objectShape({\n\tname: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The registered name of the tool whose full description to return.',\n\t}),\n})\n\n// === Workflow draft / flat-steps shapes\n\n/**\n * Describes the shape of a {@link import('./types.js').TaskDraft} — identical to a strict task\n * shape except that `id` and `name` are optional.\n */\nexport const taskDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Task id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Task name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional task description.' })),\n\tbehavior: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'The registered behavior name to invoke (a registry key, not a label); omitted completes with JSON null.',\n\t\t}),\n\t),\n\tretries: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tdescription:\n\t\t\t\t'Extra attempts after the first on failure; overrides the phase default. Omitted means none.',\n\t\t}),\n\t),\n\ttimeout: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tmax: MAX_TIMER_MS,\n\t\t\tdescription:\n\t\t\t\t'Persisted per-attempt deadline in milliseconds (0 disables it); omitted means no deadline.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of a phase in a draft workflow — identical to a strict phase shape except\n * that `id` and `name` are optional and each task takes {@link taskDraftShape}.\n */\nexport const phaseDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Phase id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Phase name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional phase description.' })),\n\ttasks: arrayShape(taskDraftShape, { description: 'The phase tasks; they run CONCURRENTLY.' }),\n\tconcurrency: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'Max tasks in flight at once (a resource throttle); omitted means unbounded.',\n\t\t}),\n\t),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription: 'Per-phase failure-policy override; omitted inherits the workflow bail.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of a draft workflow — identical to a strict workflow shape except that `id`\n * and `name` are optional at the workflow, phase, and task levels, so a small model can omit every\n * identity string and let the tool synthesize them positionally.\n *\n * @remarks\n * The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.\n * `behavior` stays optional like the strict form; omission is the deliberate JSON `null` no-op. A\n * provided `id` / `name` still has `minLength: 1` (so\n * an explicitly-empty `id: ''` is rejected, not auto-filled). After\n * {@link import('./helpers.js').completeDraft} fills the missing ids/names, the result is\n * validated against the strict `createWorkflowContract` (`@orkestrel/workflow`) gate before\n * running.\n */\nexport const workflowDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Workflow id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Workflow name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional workflow description.' })),\n\tphases: arrayShape(phaseDraftShape, {\n\t\tdescription: 'The workflow phases; they run SEQUENTIALLY, in order.',\n\t}),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription:\n\t\t\t\t'Failure policy: false (default) continues gracefully, true halts on the first failure.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of one flat step — `{ name }` — the building block of\n * {@link workflowStepsShape}.\n *\n * @remarks\n * `name` is the registered behavior name the step runs (it becomes the task's `behavior`). The tool\n * expands each step into a one-task phase, in order ({@link import('./helpers.js').expandSteps}).\n */\nexport const stepShape = objectShape({\n\tname: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The registered behavior name this step runs (becomes the task behavior).',\n\t}),\n})\n\n/**\n * Describes the flat authoring shape {@link import('./factories.js').createWorkflowTool} advertises\n * as its `parameters` — the simplest surface a small model can fill:\n * `{ name?, steps: [{ name }] }`.\n *\n * @remarks\n * A deliberately-reduced surface: a flat ordered list of steps, each a `{ name }`. The tool\n * expands it ({@link import('./helpers.js').expandSteps}) into a full\n * {@link import('./types.js').WorkflowDefinition} — one one-task phase per step, in order —\n * then validates against the strict `createWorkflowContract` (`@orkestrel/workflow`) gate. The\n * full nested form is still accepted by the tool (it branches on the args' shape) and is\n * documented as the advanced escape-hatch in the tool's description — but this is what\n * `parameters` advertises.\n */\nexport const workflowStepsShape = objectShape({\n\tname: optionalShape(stringShape({ min: 1, description: 'Optional workflow name.' })),\n\tsteps: arrayShape(stepShape, {\n\t\tdescription: 'The ordered steps to run, one after another (each becomes a one-task phase).',\n\t}),\n})\n\n// === Workspace operation shape\n\n/**\n * Describes the shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union\n * over the workspace edit, read, and navigation operations, discriminated by the `operation`\n * literal (never a bare `kind`). Each variant leads with its `operation`\n * discriminant then its flat fields, every field through `stringShape` / `optionalShape` /\n * `integerShape({ min: 1 })` / `booleanShape`, each carrying a strong field-level `description`.\n *\n * @remarks\n * The union compiles to an `anyOf` JSON Schema, a `unionOf` guard, and a first-match parser\n * automatically ({@link import('./factories.js').createWorkspaceTool} types the result to the\n * hand-written {@link import('./types.js').WorkspaceOperation}). `limit` and the `'splice'`\n * caret components are positive integers (`integerShape({ min: 1 })`); `regex` / `sensitive`\n * are `optionalShape(booleanShape(...))`. The registry arms — `workspaces` (list the\n * workspaces the model can move between) and `switch` (re-point the active one by `id`) — let a\n * model discover then choose which workspace the edit / read arms target.\n */\nexport const workspaceToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['read'], { description: \"Read a whole text file's text by path.\" }),\n\t\tpath: stringShape({ description: 'The path of the file to read.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['list'], { description: 'List every file in the workspace.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['has'], { description: 'Check whether a file exists at the path.' }),\n\t\tpath: stringShape({ description: 'The path to check for.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['search'], {\n\t\t\tdescription: 'Search every text file for a query, returning each hit.',\n\t\t}),\n\t\tquery: stringShape({ description: 'The text (or regular-expression source) to search for.' }),\n\t\tregex: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription:\n\t\t\t\t\t'Treat the query as a regular expression. Defaults to false (a literal substring).',\n\t\t\t}),\n\t\t),\n\t\tsensitive: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription: 'Match case-sensitively. Defaults to true (set false for case-insensitive).',\n\t\t\t}),\n\t\t),\n\t\tlimit: optionalShape(\n\t\t\tintegerShape({\n\t\t\t\tmin: 1,\n\t\t\t\tdescription: 'Stop after this many matches across all files. Omitted means unlimited.',\n\t\t\t}),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['replace'], {\n\t\t\tdescription: 'Replace a query with a replacement across every text file.',\n\t\t}),\n\t\tquery: stringShape({ description: 'The text (or regular-expression source) to replace.' }),\n\t\treplacement: stringShape({ description: 'The text to substitute for each match.' }),\n\t\tregex: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription:\n\t\t\t\t\t'Treat the query as a regular expression. Defaults to false (a literal substring).',\n\t\t\t}),\n\t\t),\n\t\tsensitive: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription: 'Match case-sensitively. Defaults to true (set false for case-insensitive).',\n\t\t\t}),\n\t\t),\n\t\tlimit: optionalShape(\n\t\t\tintegerShape({\n\t\t\t\tmin: 1,\n\t\t\t\tdescription: 'Stop after this many replacements across all files. Omitted means unlimited.',\n\t\t\t}),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['write'], {\n\t\t\tdescription: 'Create or overwrite a whole file with content.',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to write.' }),\n\t\tcontent: stringShape({ description: 'The full new contents of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['splice'], {\n\t\t\tdescription:\n\t\t\t\t'Replace a 1-based range of an existing text file (from inclusive, to exclusive) with content.',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the text file to edit.' }),\n\t\tcontent: stringShape({ description: 'The text to splice in place of the range.' }),\n\t\tfromLine: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'The 1-based start line of the range (inclusive).',\n\t\t}),\n\t\tfromColumn: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'The 1-based start column of the range (inclusive; column 1 is the first character).',\n\t\t}),\n\t\ttoLine: integerShape({ min: 1, description: 'The 1-based end line of the range (exclusive).' }),\n\t\ttoColumn: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'The 1-based end column of the range (exclusive).',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['prepend'], {\n\t\t\tdescription: 'Add content to the start of a file (creating it when absent).',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to prepend to.' }),\n\t\tcontent: stringShape({ description: 'The text to add at the start of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['append'], {\n\t\t\tdescription: 'Add content to the end of a file (creating it when absent).',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to append to.' }),\n\t\tcontent: stringShape({ description: 'The text to add at the end of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['move'], {\n\t\t\tdescription: 'Rename or move a file (overwriting an occupied target).',\n\t\t}),\n\t\tfrom: stringShape({ description: 'The current path of the file.' }),\n\t\tto: stringShape({ description: 'The new path for the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['remove'], { description: 'Delete a file from the workspace.' }),\n\t\tpath: stringShape({ description: 'The path of the file to remove.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['workspaces'], {\n\t\t\tdescription:\n\t\t\t\t'List the workspaces you can move between (each id, file count, and whether it is active), so you can pick an id to switch to.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['switch'], {\n\t\t\tdescription:\n\t\t\t\t'Switch the active workspace to the one with this id (get ids from the \"workspaces\" operation). Edit and read operations then target it.',\n\t\t}),\n\t\tid: stringShape({\n\t\t\tdescription: 'The id of the workspace to make active (from the \"workspaces\" listing).',\n\t\t}),\n\t}),\n)\n\n// === Database tool shape\n\n/** Describes a {@link import('./types.js').ColumnPrimitive} literal — the leaf {@link columnSpecShape} wraps. */\nexport const columnPrimitiveShape = literalShape(['string', 'integer', 'number', 'boolean'], {\n\tdescription: 'A column primitive: \"string\" | \"integer\" | \"number\" | \"boolean\".',\n})\n\n/** Describes a {@link import('./types.js').ColumnSpec} — a bare {@link columnPrimitiveShape}, or `{ primitive, optional }`. */\nexport const columnSpecShape = unionShape(\n\tcolumnPrimitiveShape,\n\tobjectShape({\n\t\tprimitive: columnPrimitiveShape,\n\t\toptional: optionalShape(\n\t\t\tbooleanShape({ description: 'Whether the column may be absent from a row.' }),\n\t\t),\n\t}),\n)\n\n/** Describes a {@link import('./types.js').TableSpec} — table name to `{ columns }`, each column a {@link columnSpecShape}. */\nexport const tableSpecShape = recordShape(\n\tobjectShape({\n\t\tcolumns: recordShape(columnSpecShape, {\n\t\t\tdescription: 'Column name to its primitive or its { primitive, optional } spec.',\n\t\t}),\n\t}),\n\t{ description: 'Table name to its column layout.' },\n)\n\n/**\n * Describes one key value for the database tool and the relation tool — a string or number; the\n * array form (multiple keys, positional) resolves first, so an array argument is read as many keys\n * rather than one.\n */\nexport const keyShape = unionShape(\n\tarrayShape(unionShape(stringShape(), numberShape()), {\n\t\tdescription: 'Multiple row keys, positional — a miss at an index is undefined there.',\n\t}),\n\tstringShape({ description: 'One row key.' }),\n\tnumberShape({ description: 'One row key.' }),\n)\n\n/** Describes a loose row — a flat object of column name to JSON value. */\nexport const rowShape = recordShape(jsonShape(), {\n\tdescription: 'A row as a flat object of column name to value.',\n})\n\n/**\n * Describes one or many loose rows — the array form resolves first, so an array argument is read as\n * many rows rather than one.\n */\nexport const rowsShape = unionShape(\n\tarrayShape(rowShape, { description: 'Multiple rows.' }),\n\trowShape,\n)\n\n/**\n * Describes one serialized where condition — `values` is always an array, even for a single-value\n * operator.\n */\nexport const conditionShape = objectShape({\n\tcolumn: stringShape({ description: 'The column this condition applies to.' }),\n\toperator: literalShape(\n\t\t[\n\t\t\t'equals',\n\t\t\t'not',\n\t\t\t'above',\n\t\t\t'below',\n\t\t\t'from',\n\t\t\t'to',\n\t\t\t'between',\n\t\t\t'like',\n\t\t\t'glob',\n\t\t\t'starts',\n\t\t\t'ends',\n\t\t\t'any',\n\t\t\t'none',\n\t\t\t'absent',\n\t\t\t'present',\n\t\t],\n\t\t{ description: 'The comparison operator.' },\n\t),\n\tvalues: arrayShape(jsonShape(), {\n\t\tdescription: 'The operand values the operator needs (always an array, even for one value).',\n\t}),\n\tconnector: optionalShape(\n\t\tliteralShape(['and', 'or'], {\n\t\t\tdescription: 'Joins this condition to the next; omit on the last condition.',\n\t\t}),\n\t),\n})\n\n/** Describes one sort term — a `column` to sort by and the `direction` to sort it in. */\nexport const orderShape = objectShape({\n\tcolumn: stringShape({ description: 'The column to sort by.' }),\n\tdirection: literalShape(['ascending', 'descending'], { description: 'The sort direction.' }),\n})\n\n/** Describes the serialized query form — conditions, order, and pagination. */\nexport const queryShape = objectShape({\n\tconditions: optionalShape(\n\t\tarrayShape(conditionShape, { description: 'The WHERE conditions, folded left to right.' }),\n\t),\n\torder: optionalShape(\n\t\tarrayShape(orderShape, { description: 'The sort terms, applied in order.' }),\n\t),\n\tlimit: optionalShape(integerShape({ min: 0, description: 'Max rows to return.' })),\n\toffset: optionalShape(integerShape({ min: 0, description: 'Rows to skip before returning.' })),\n})\n\n/**\n * Describes the shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —\n * discriminated by `operation` into the database operations `'create'`, `'tables'`, `'get'`,\n * `'records'`, `'count'`, `'aggregate'`, `'add'`, `'set'`, `'update'`, `'remove'`, and `'destroy'`.\n *\n * @remarks\n * Every arm carries `id` (the database id). `'create'` carries `tables` (the\n * {@link import('./types.js').TableSpec} column DSL, compiled through\n * {@link import('./compilers.js').expandTables}); `'get'` / `'update'` / `'remove'` carry `key`\n * (one key or an array of keys, positional); `'add'` / `'set'` carry `row` (one row or an array of\n * rows); `'update'` also carries `changes` (a loose partial row); `'records'` / `'count'` /\n * `'aggregate'` carry an optional `query` (the serialized form — `values` is always an array,\n * even for a single-value operator, so a caller never chains method calls or guesses arity).\n */\nexport const databaseToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['create'], { description: 'Define a new database.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttables: tableSpecShape,\n\t\tdriver: optionalShape(\n\t\t\tstringShape({ min: 1, description: 'The registered driver key. Defaults to \"memory\".' }),\n\t\t),\n\t\tprimary: optionalShape(\n\t\t\trecordShape(stringShape({ min: 1 }), {\n\t\t\t\tdescription: 'Table name to its primary-key column.',\n\t\t\t}),\n\t\t),\n\t\tindexes: optionalShape(\n\t\t\trecordShape(\n\t\t\t\tarrayShape(\n\t\t\t\t\tarrayShape(stringShape({ min: 1 }), {\n\t\t\t\t\t\tmin: 1,\n\t\t\t\t\t\tdescription: 'One nonempty index group of column names.',\n\t\t\t\t\t}),\n\t\t\t\t\t{ description: 'Zero or more index groups declared for the table.' },\n\t\t\t\t),\n\t\t\t\t{ description: 'Table name to its index column groups.' },\n\t\t\t),\n\t\t),\n\t\tversion: optionalShape(\n\t\t\tnumberShape({ description: 'The schema version for open-time reconciliation.' }),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['tables'], { description: \"List a database's table names.\" }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['get'], { description: 'Fetch one or more rows by primary key.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['records'], { description: 'List rows matching a query.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['count'], { description: 'Count rows matching a query.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['aggregate'], { description: 'Compute an aggregate over a column.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tfunction: literalShape(['count', 'sum', 'average', 'minimum', 'maximum'], {\n\t\t\tdescription: 'The aggregate function.',\n\t\t}),\n\t\tcolumn: stringShape({ min: 1, description: 'The column to aggregate.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['add'], {\n\t\t\tdescription: 'Insert one or more rows (fails on a duplicate key).',\n\t\t}),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\trow: rowsShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['set'], { description: 'Upsert one or more rows.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\trow: rowsShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['update'], { description: 'Patch one or more existing rows.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t\tchanges: rowShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['remove'], { description: 'Delete one or more rows by key.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['destroy'], { description: 'Drop a database entirely.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t}),\n)\n\n// === Relation tool shape (createRelationTool call args)\n//\n// Every arm carries an optional `manager` (which registered `RelationManagerInterface` to\n// address — omitted resolves to the sole registered manager) and a required `model` (the table\n// name on that manager). `include` is a flat array of dot-paths (mirrors `databaseToolShape`'s\n// flat-args ergonomic lever), expanded into a live `Include` by\n// {@link import('./helpers.js').expandInclude}.\n\n/** Describes a single row key (not an array) — used by `'link'` / `'unlink'` / `'links'`, which address exactly one owning row. */\nexport const singleKeyShape = unionShape(\n\tstringShape({ description: 'The owning row key.' }),\n\tnumberShape({ description: 'The owning row key.' }),\n)\n\n/** Describes the flat dot-path relation include list, expanded through {@link import('./helpers.js').expandInclude}. */\nexport const includeShape = optionalShape(\n\tarrayShape(\n\t\tstringShape({\n\t\t\tdescription: 'A dot-separated chain of relation names, for example \"contacts.account\".',\n\t\t}),\n\t\t{ description: 'Which relations to attach, as flat dot-paths.' },\n\t),\n)\n\n/** Describes which registered relation manager to address — omitted resolves to the sole registered manager. */\nexport const managerShape = optionalShape(\n\tstringShape({ min: 1, description: 'Which registered relation manager to address.' }),\n)\n\n/**\n * Describes the shape of {@link import('./factories.js').createRelationTool}'s call arguments —\n * discriminated by `operation` into the relation operations `'load'`, `'find'`, `'link'`,\n * `'unlink'`, and `'links'`.\n *\n * @remarks\n * `'load'` fetches one or more rows (positional key/array) with `include` attached. `'find'`\n * fetches rows (pagination / sort only) with `include` attached. `'link'` / `'unlink'` write /\n * remove a `through` junction row; `'links'` lists a `through` relation's linked keys.\n */\nexport const relationToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['load'], {\n\t\t\tdescription: 'Fetch one or more rows by key, with related rows attached.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: keyShape,\n\t\tinclude: includeShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['find'], {\n\t\t\tdescription: 'List rows, with related rows attached.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tinclude: includeShape,\n\t\tlimit: optionalShape(integerShape({ min: 0, description: 'Max rows to return.' })),\n\t\toffset: optionalShape(integerShape({ min: 0, description: 'Rows to skip before returning.' })),\n\t\tsort: optionalShape(stringShape({ min: 1, description: 'The column to sort by.' })),\n\t\tdirection: optionalShape(\n\t\t\tliteralShape(['ascending', 'descending'], { description: 'The sort direction.' }),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['link'], {\n\t\t\tdescription: 'Connect two rows through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t\ttarget: singleKeyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['unlink'], {\n\t\t\tdescription: 'Disconnect two rows previously linked through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t\ttarget: singleKeyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['links'], {\n\t\t\tdescription: 'List every key linked to a row through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t}),\n)\n\n/**\n * Describes the shape of {@link import('./factories.js').createInferTool}'s call arguments — one or more\n * example `samples` to infer a JSON Schema from, plus per-call `format` / `enum` toggles and an\n * optional `candidates` array to check against the inferred schema.\n *\n * @remarks\n * `samples` requires at least one element (`min: 1`) — an empty array parses to `undefined`,\n * surfaced by the handler as a typed `TOOL` {@link import('./errors.js').ToolboxError}. When\n * `candidates` is present (any array, including empty), the handler compiles a contract from the\n * freshly inferred schema and checks each candidate against it with a strict guard (`.is`, no\n * coercion) — the opposite of {@link import('./factories.js').createEndpointTool}'s normalizing\n * `.parse` enforcement.\n */\nexport const inferToolShape = objectShape({\n\tsamples: arrayShape(jsonShape(), {\n\t\tmin: 1,\n\t\tdescription: 'The example values to infer a JSON Schema from (at least one).',\n\t}),\n\tformat: optionalShape(\n\t\tbooleanShape({\n\t\t\tdescription:\n\t\t\t\t'Infer string formats (date-time, email, ...) from the samples. Defaults to false.',\n\t\t}),\n\t),\n\tenum: optionalShape(\n\t\tbooleanShape({\n\t\t\tdescription: 'Infer enum constraints from repeated literal values. Defaults to false.',\n\t\t}),\n\t),\n\tcandidates: optionalShape(\n\t\tarrayShape(jsonShape(), {\n\t\t\tdescription:\n\t\t\t\t'Optional values to check against the freshly inferred schema. When present, the tool ' +\n\t\t\t\t'returns a per-candidate verdict (strict — no coercion) alongside the inferred parameters.',\n\t\t}),\n\t),\n})\n","import type { WorkflowDefinition, WorkflowResult } from '@orkestrel/workflow'\nimport type { DatabaseErrorCode } from '@orkestrel/database'\nimport type {\n\tInclude,\n\tModelInterface,\n\tRelationErrorCode,\n\tRelationManagerInterface,\n} from '@orkestrel/relation'\nimport type { QueryInput } from '@orkestrel/database'\nimport type {\n\tToolboxErrorCode,\n\tClampedQuery,\n\tDatabaseQueryInput,\n\tWorkflowToolResult,\n\tWorkflowLineage,\n} from './types.js'\nimport type { PhaseDraft, TaskDraft, WorkflowDraft, WorkflowSteps } from './types.js'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { isDatabaseError } from '@orkestrel/database'\nimport { isRelationError } from '@orkestrel/relation'\nimport { isObject } from '@orkestrel/contract'\nimport { ToolboxError } from './errors.js'\nimport { isWorkflowLineage } from './validators.js'\n\n// Toolbox owns the workflow tool's lenient-authoring completion, ancestry tags, and boundary\n// projections. Runtime scheduling, named-function resolution, and persistence remain native\n// `@orkestrel/workflow` responsibilities.\n\n/**\n * Returns the ancestry identifier of a workflow in a run chain — `workflow:<id>`.\n *\n * @remarks\n * Namespacing keeps a workflow id and a {@link tagAgent} agent name in one set without\n * collision, so re-entering a workflow or an agent already in the chain is a single `includes`\n * check.\n *\n * @param id - The workflow definition's `id`\n * @returns The namespaced ancestry tag (`workflow:<id>`)\n */\nexport function tagWorkflow(id: string): string {\n\treturn `workflow:${id}`\n}\n\n/**\n * Returns the ancestry identifier of an agent in a run chain — `agent:<name>`.\n *\n * @remarks\n * The agent counterpart of {@link tagWorkflow}: {@link import('./factories.js').createAgentFunction}\n * / {@link import('./factories.js').createWorkflowTool} guard against re-entering an agent or\n * workflow already in the chain (this package's typed `DEPTH` `ToolboxError`). The\n * `agent:` namespace keeps it distinct from a same-string workflow id.\n *\n * @param name - The agent's identifier / registry name\n * @returns The namespaced ancestry tag (`agent:<name>`)\n */\nexport function tagAgent(name: string): string {\n\treturn `agent:${name}`\n}\n\n/**\n * Returns the canonical workflow lineage — validated, copied, and frozen.\n *\n * @param lineage - The configured chain; omitted means a direct root\n * @returns An immutable caller-isolated lineage\n */\nexport function normalizeLineage(lineage: WorkflowLineage = []): WorkflowLineage {\n\tif (!isWorkflowLineage(lineage)) {\n\t\tthrow new ToolboxError('TOOL', 'workflow lineage must alternate unique workflow and agent tags')\n\t}\n\treturn Object.freeze([...lineage])\n}\n\n/**\n * Appends one tag to a workflow lineage and returns a frozen copy.\n *\n * @param lineage - The valid chain to extend\n * @param tag - The workflow or agent tag to append\n * @returns The validated immutable extension\n */\nexport function extendLineage(lineage: WorkflowLineage, tag: string): WorkflowLineage {\n\treturn normalizeLineage([...lineage, tag])\n}\n\n/**\n * Derives the zero-based workflow nesting depth from a valid lineage.\n *\n * @param lineage - The workflow/agent chain\n * @returns Zero for an empty/root lineage, then one per nested workflow\n */\nexport function deriveWorkflowDepth(lineage: WorkflowLineage): number {\n\tconst current = normalizeLineage(lineage)\n\tconst workflows = current.filter((tag) => tag.startsWith('workflow:')).length\n\treturn Math.max(0, workflows - 1)\n}\n\n/**\n * Builds the plain success summary {@link import('./factories.js').createWorkflowTool} returns on a\n * completed run — the universal tool-handler contract: return a plain value on success, appearing\n * identically over both the agent loop and MCP.\n *\n * @remarks\n * The summary is lean: the workflow's terminal `status`, settled-task count, and exact optional\n * native persistence outcome. It carries no synthetic `id` / `name`: a tool handler has no call\n * id; the `ToolManagerInterface` (`@orkestrel/tool`) supplies the canonical envelope's identity.\n *\n * @param result - The terminal `WorkflowResult` (`@orkestrel/workflow`) the run produced\n * @returns The plain success summary — `{ status, count, durable?, fault? }`\n */\nexport function summarizeWorkflow(result: WorkflowResult): WorkflowToolResult {\n\treturn {\n\t\tstatus: result.status,\n\t\tcount: result.results.length,\n\t\t...(result.durable === undefined ? {} : { durable: result.durable }),\n\t\t...(result.fault === undefined ? {} : { fault: result.fault }),\n\t}\n}\n\n// === Draft completion and flat-steps expansion (the tool's lenient authoring surfaces)\n//\n// Pure, deterministic synthesis that turns a widened authoring form into a strict\n// `WorkflowDefinition` (`@orkestrel/workflow`). They auto-fill only omitted identity (a provided\n// id/name is preserved verbatim; an explicitly-empty `id: ''` is rejected upstream by the draft\n// contract, never reached here), so a small model can author a complete tree without emitting an\n// `id` or a `name` anywhere in it. The factory re-validates the result against the strict\n// `createWorkflowContract().is` gate before running (soundness).\n\n/**\n * Completes a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesizes a\n * missing `id` deterministically and positionally, and defaults a missing `name` to its resolved\n * `id`.\n *\n * @remarks\n * The positional id scheme is stable and human-legible: the workflow is `wf`, phase `i` is\n * `phase-<i>`, and task `j` of that phase is `<phaseId>-task-<j>` (so a provided phase id flows\n * into its tasks' synthesized ids). A provided `id` / `name` at any level is kept verbatim —\n * synthesis touches only the omitted ones. A missing `name` defaults to the resolved `id` (never\n * the other way round), so the result always carries an `id` and a `name`. `behavior`, `description`, the per-phase\n * `concurrency` / `bail`, the per-task `retries` / `timeout`, and the workflow `bail` carry over\n * unchanged. The result is a complete {@link WorkflowDefinition}; the caller still validates it\n * against the strict contract.\n *\n * @param draft - The draft workflow (`id` and `name` optional at the workflow, phase, and task levels)\n * @returns A complete {@link WorkflowDefinition} with every id/name filled\n */\nexport function completeDraft(draft: WorkflowDraft): WorkflowDefinition {\n\tconst id = draft.id ?? 'wf'\n\treturn {\n\t\tid,\n\t\tname: draft.name ?? id,\n\t\t...(draft.description === undefined ? {} : { description: draft.description }),\n\t\tphases: draft.phases.map((phase, index) => completePhaseDraft(phase, index)),\n\t\t...(draft.bail === undefined ? {} : { bail: draft.bail }),\n\t}\n}\n\n/**\n * Completes one {@link PhaseDraft} into a strict phase definition — the per-phase step of\n * {@link completeDraft} (phase `index` → `phase-<index>` when its id is omitted).\n *\n * @param phase - The draft phase\n * @param index - The phase's positional index in the workflow\n * @returns A complete phase definition\n */\nexport function completePhaseDraft(\n\tphase: PhaseDraft,\n\tindex: number,\n): WorkflowDefinition['phases'][number] {\n\tconst id = phase.id ?? `phase-${index}`\n\treturn {\n\t\tid,\n\t\tname: phase.name ?? id,\n\t\t...(phase.description === undefined ? {} : { description: phase.description }),\n\t\ttasks: phase.tasks.map((task, taskIndex) => completeTaskDraft(task, id, taskIndex)),\n\t\t...(phase.concurrency === undefined ? {} : { concurrency: phase.concurrency }),\n\t\t...(phase.bail === undefined ? {} : { bail: phase.bail }),\n\t}\n}\n\n/**\n * Completes one {@link TaskDraft} into a strict task definition — the per-task leaf step of\n * {@link completeDraft} (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id\n * is omitted).\n *\n * @param task - The draft task\n * @param phaseId - The (resolved) parent phase id, so the synthesized task id nests under it\n * @param index - The task's positional index within its phase\n * @returns A complete task definition\n */\nexport function completeTaskDraft(\n\ttask: TaskDraft,\n\tphaseId: string,\n\tindex: number,\n): WorkflowDefinition['phases'][number]['tasks'][number] {\n\tconst id = task.id ?? `${phaseId}-task-${index}`\n\treturn {\n\t\tid,\n\t\tname: task.name ?? id,\n\t\t...(task.description === undefined ? {} : { description: task.description }),\n\t\t...(task.behavior === undefined ? {} : { behavior: task.behavior }),\n\t\t...(task.retries === undefined ? {} : { retries: task.retries }),\n\t\t...(task.timeout === undefined ? {} : { timeout: task.timeout }),\n\t}\n}\n\n/**\n * Expands a flat {@link WorkflowSteps} blob into a strict {@link WorkflowDefinition} — each step\n * becomes a one-task phase, in order.\n *\n * @remarks\n * The expansion of the tool's advertised surface: the deliberately-reduced flat form. Each\n * {@link import('./types.js').WorkflowStep} maps to a phase holding exactly one task: the step's\n * `name` becomes the task's `behavior` (the behavior-registry key). Ids/names are auto-filled\n * positionally — it builds an ids-omitted {@link WorkflowDraft} and delegates to\n * {@link completeDraft}, so the lenient surfaces share one synthesis path (step `i` → phase\n * `phase-<i>`, its task `phase-<i>-task-0`). The optional `name` becomes both the workflow's\n * deterministic id and its name, so named flat workflows retain distinct persistence keys;\n * omission keeps the shared draft fallback `wf`. The result is a complete definition the caller\n * validates against the strict contract before running.\n *\n * @param flat - The flat steps blob (`{ name?, steps: [{ name }] }`)\n * @returns A complete {@link WorkflowDefinition} (one one-task phase per step)\n */\nexport function expandSteps(flat: WorkflowSteps): WorkflowDefinition {\n\treturn completeDraft({\n\t\t...(flat.name === undefined ? {} : { id: flat.name, name: flat.name }),\n\t\tphases: flat.steps.map((step) => ({\n\t\t\ttasks: [{ behavior: step.name }],\n\t\t})),\n\t})\n}\n\n/**\n * Maps a caught error to the {@link ToolboxErrorCode} the terminal-tool factory throws with — the\n * pure classification step of that factory's error handling.\n *\n * @remarks\n * Narrows `error` with {@link isTerminalError} (`@orkestrel/terminal`) first: a non-`TerminalError`\n * value returns `undefined`, telling the caller this mapper does not apply (rethrow / handle\n * otherwise). For a genuine `TerminalError`, `'DEADLOCK'` maps to `'DEADLOCK'`, `'EXPIRE'` maps\n * to `'EXPIRE'`, and every other {@link import('@orkestrel/terminal').TerminalErrorCode}\n * (`'TARGET'`, `'LIMIT'`, `'CANCEL'`, `'DRIVER'`, `'DESTROYED'`) maps to the generic `'TOOL'`\n * code. The mapper only classifies — the factory performs the actual throw.\n *\n * @param error - The value caught from a terminal-manager operation (`ask` / `answer` / …)\n * @returns The mapped {@link ToolboxErrorCode}, or `undefined` if `error` is not a `TerminalError`\n */\nexport function inferTerminalCode(error: unknown): ToolboxErrorCode | undefined {\n\tif (!isTerminalError(error)) return undefined\n\tif (error.code === 'DEADLOCK') return 'DEADLOCK'\n\tif (error.code === 'EXPIRE') return 'EXPIRE'\n\treturn 'TOOL'\n}\n\n// === Database- and relation-tool error classification — a caught upstream error maps to the\n// code the owning factory re-throws with.\n\n/**\n * Maps a caught error to the granular {@link DatabaseErrorCode} (`@orkestrel/database`) the code\n * {@link import('./factories.js').createDatabaseTool} throws with — the pure classification step\n * of that factory's error handling, mirroring {@link inferTerminalCode}'s idiom for\n * `@orkestrel/database`.\n *\n * @param error - The value caught from a `@orkestrel/database` table operation\n * @returns The granular {@link DatabaseErrorCode}, or `undefined` if `error` is not a `DatabaseError`\n */\nexport function inferDatabaseCode(error: unknown): DatabaseErrorCode | undefined {\n\treturn isDatabaseError(error) ? error.code : undefined\n}\n\n/**\n * Maps a caught error to the granular {@link RelationErrorCode} (`@orkestrel/relation`) the code\n * {@link import('./factories.js').createRelationTool} throws with — the pure classification step\n * of that factory's error handling, mirroring {@link inferTerminalCode}'s idiom for\n * `@orkestrel/relation`.\n *\n * @param error - The value caught from a `@orkestrel/relation` operation\n * @returns The granular {@link RelationErrorCode}, or `undefined` if `error` is not a `RelationError`\n */\nexport function inferRelationCode(error: unknown): RelationErrorCode | undefined {\n\treturn isRelationError(error) ? error.code : undefined\n}\n\n/**\n * Expands the relation tool's flat dot-path `include` list into a live `@orkestrel/relation`\n * {@link Include} tree — the pure leaf {@link import('./factories.js').createRelationTool} calls\n * before a `'load'` / `'find'` call.\n *\n * @remarks\n * Each path splits on `'.'` into a chain of relation names, deep-merged into one nested\n * `Include` object with a leaf `true`. A longer path subsumes a shorter sibling's bare `true` —\n * `'contacts'` followed by `'contacts.account'` yields `{ contacts: { account: true } }`, never\n * overwriting the deeper chain. An empty segment (`''`, from a leading/trailing/doubled `.`) or a\n * path whose segment count exceeds `depth` throws a typed `TOOL` {@link ToolboxError}.\n *\n * @param paths - The flat dot-path `include` list (or `undefined` — yields `{}`)\n * @param depth - The max segment count a single path may reach\n * @returns The equivalent nested {@link Include}\n *\n * @example\n * ```ts\n * import { expandInclude } from '@src/core'\n *\n * expandInclude(['contacts', 'contacts.account'], 3)\n * // { contacts: { account: true } }\n * ```\n */\nexport function expandInclude(paths: readonly string[] | undefined, depth: number): Include {\n\tlet include: Include = {}\n\tfor (const path of paths ?? []) {\n\t\tconst segments = path.split('.')\n\t\tif (segments.length > depth || segments.some((segment) => segment.length === 0)) {\n\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t}\n\t\tconst ancestors: Include[] = []\n\t\tlet branch = include\n\t\tconst last = segments.length - 1\n\t\tfor (let index = 0; index < last; index++) {\n\t\t\tconst segment = segments[index]\n\t\t\tif (segment === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t\t}\n\t\t\tancestors.push(branch)\n\t\t\tconst existing = branch[segment]\n\t\t\tbranch = isObject(existing) ? existing : {}\n\t\t}\n\t\tconst leaf = segments[last]\n\t\tif (leaf === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t}\n\t\tconst existing = branch[leaf]\n\t\tlet merged: Include = {\n\t\t\t...branch,\n\t\t\t[leaf]: existing === undefined ? true : existing,\n\t\t}\n\t\tfor (let index = last - 1; index >= 0; index--) {\n\t\t\tconst ancestor = ancestors[index]\n\t\t\tconst segment = segments[index]\n\t\t\tif (ancestor === undefined || segment === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t\t}\n\t\t\tmerged = { ...ancestor, [segment]: merged }\n\t\t}\n\t\tinclude = merged\n\t}\n\treturn include\n}\n\n/**\n * Resolves which registered {@link RelationManagerInterface} a relation-tool call addresses — the\n * pure manager-resolution leaf {@link import('./factories.js').createRelationTool} calls on\n * every operation.\n *\n * @remarks\n * An explicit `name` must match a key of `managers` (a miss throws a typed `TOOL`\n * {@link ToolboxError} naming the registered managers). An omitted `name` resolves to the sole\n * registered manager when exactly one is registered, else throws the same typed error.\n *\n * @param managers - The tool's registered `RelationManagerInterface` map\n * @param name - The call's optional `manager` field\n * @returns The resolved {@link RelationManagerInterface}\n */\nexport function resolveRelationManager(\n\tmanagers: Readonly<Record<string, RelationManagerInterface>>,\n\tname: string | undefined,\n): RelationManagerInterface {\n\tif (name !== undefined) {\n\t\tconst manager = managers[name]\n\t\tif (manager === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `unknown relation manager '${name}'`, {\n\t\t\t\tmanager: name,\n\t\t\t\tmanagers: Object.keys(managers),\n\t\t\t})\n\t\t}\n\t\treturn manager\n\t}\n\tconst names = Object.keys(managers)\n\tconst [single] = names\n\tif (names.length === 1 && single !== undefined) {\n\t\tconst manager = managers[single]\n\t\tif (manager !== undefined) return manager\n\t}\n\tthrow new ToolboxError('TOOL', 'no relation manager resolved for the call', {\n\t\tmanagers: names,\n\t})\n}\n\n/**\n * Resolves a `model` name against a live {@link RelationManagerInterface} — the pure model-lookup\n * leaf {@link import('./factories.js').createRelationTool} calls on every operation, mirroring\n * {@link resolveRelationManager}'s guard shape.\n *\n * @param manager - The resolved {@link RelationManagerInterface}\n * @param name - The call's `model` field\n * @returns The model's {@link ModelInterface}\n */\nexport function resolveRelationModel(\n\tmanager: RelationManagerInterface,\n\tname: string,\n): ModelInterface {\n\tif (!manager.has(name)) {\n\t\tthrow new ToolboxError('TOOL', `unknown model '${name}'`, {\n\t\t\tmodel: name,\n\t\t\tmodels: manager.names(),\n\t\t})\n\t}\n\treturn manager.model(name)\n}\n\n// === Database-tool operation leaves\n\n/**\n * Returns the canonical live `@orkestrel/database` {@link QueryInput} for the database tool's\n * parsed serialized query — each condition's omitted `connector` defaults to `'and'`.\n *\n * @remarks\n * The wire form ({@link import('./shapers.js').databaseToolShape}) lets a caller drop `connector`\n * on the last condition (it has nothing to join forward to); the compiled `Condition` a live\n * `@orkestrel/database` table call accepts always carries one, so this fills the gap. `order` /\n * `limit` / `offset` pass through unchanged. Pure and total.\n *\n * @param query - The parsed query (or `undefined`)\n * @returns The equivalent live `QueryInput`, or `undefined` when `query` is `undefined`\n */\nexport function normalizeQuery(query: DatabaseQueryInput | undefined): QueryInput | undefined {\n\tif (query === undefined) return undefined\n\tconst conditions = query.conditions?.map((condition) => ({\n\t\t...condition,\n\t\tconnector: condition.connector ?? 'and',\n\t}))\n\treturn {\n\t\t...(conditions === undefined ? {} : { conditions }),\n\t\t...(query.order === undefined ? {} : { order: query.order }),\n\t\t...(query.limit === undefined ? {} : { limit: query.limit }),\n\t\t...(query.offset === undefined ? {} : { offset: query.offset }),\n\t}\n}\n\n/**\n * Picks the effective row limit a tool reads with — the requested count when it sits inside the\n * cap, the cap when it exceeds it, and `0` when either falls below zero.\n *\n * @remarks\n * The one place the database tool's `'records'` clamp ({@link clampQuery}) and the relation tool's\n * `'find'` / `'links'` truncation both take their ceiling from, so a negative construction-time\n * option can never reach a slice. Pure and total.\n *\n * @example\n * ```ts\n * import { resolveLimit } from '@src/core'\n *\n * resolveLimit(undefined, 100) // 100 — an omitted request takes the cap\n * resolveLimit(500, 100) // 100 — a request over the cap is clamped down\n * resolveLimit(-1, 100) // 0 — a negative request floors at zero\n * ```\n *\n * @param requested - The caller's requested row count (or `undefined`)\n * @param cap - The row-count ceiling\n * @returns The effective row limit, never below `0` and never above `cap`\n */\nexport function resolveLimit(requested: number | undefined, cap: number): number {\n\treturn Math.max(0, Math.min(requested ?? cap, cap))\n}\n\n/**\n * Clamps a `'records'` call's query to a row cap, and builds the probe query the caller reads with\n * — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation uses\n * to detect truncation without a separate `count` round trip.\n *\n * @remarks\n * {@link resolveLimit} picks the effective limit, so a caller can never exceed the configured cap\n * by supplying a larger `query.limit`, and can never drive it below `0`. The returned probe query\n * requests one more row than the effective limit (`limit: effective + 1`) — if storage returns\n * that many, the caller knows the true result was truncated (`rows.length > effective`) and slices\n * back down to `effective` before returning.\n *\n * @example\n * ```ts\n * import { clampQuery } from '@src/core'\n *\n * const { query, limit } = clampQuery(undefined, 100)\n * // limit === 100, query.limit === 101 — a probe fetching one extra row\n * const rows = await table.records(query)\n * const truncated = rows.length > limit // true when storage had more than `limit` rows\n * ```\n *\n * @param query - The live query to clamp (or `undefined`)\n * @param cap - The row-count ceiling\n * @returns The probe query (`limit` bumped by one) and the effective `limit`\n */\nexport function clampQuery(query: QueryInput | undefined, cap: number): ClampedQuery {\n\tconst limit = resolveLimit(query?.limit, cap)\n\treturn { query: { ...query, limit: limit + 1 }, limit }\n}\n","import type { TableMap } from '@orkestrel/database'\nimport type { ContractShape } from '@orkestrel/contract'\nimport type { ColumnPrimitive, ColumnSpec, TableSpec } from './types.js'\nimport {\n\tbooleanShape,\n\tintegerShape,\n\tisString,\n\tnumberShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\n\n// Toolbox compilers — the config-only `TableSpec` column DSL compiled into the live\n// `@orkestrel/database` `TableMap` a `createDatabase` call accepts. Pure and total: one composite\n// walk over the spec, and the `compileColumn` / `compileColumnPrimitive` leaves it maps with.\n\n/**\n * Compiles a {@link TableSpec} into the `@orkestrel/database` {@link TableMap} it configures —\n * each {@link ColumnSpec} maps to the matching primitive shaper (`'string'` → `stringShape()`,\n * `'integer'` → `integerShape()`, `'number'` → `numberShape()`, `'boolean'` → `booleanShape()`),\n * wrapped in `optionalShape` when the column declares `optional: true`. Total, pure.\n *\n * @param spec - The small-model-facing table layout\n * @returns The compiled `TableMap` a `@orkestrel/database` `createDatabase` call accepts\n */\nexport function expandTables(spec: TableSpec): TableMap {\n\tconst tables: Record<string, Readonly<Record<string, ContractShape>>> = {}\n\tfor (const [table, definition] of Object.entries(spec)) {\n\t\tconst columns: Record<string, ContractShape> = {}\n\t\tfor (const [column, columnSpec] of Object.entries(definition.columns)) {\n\t\t\tcolumns[column] = compileColumn(columnSpec)\n\t\t}\n\t\ttables[table] = columns\n\t}\n\treturn tables\n}\n\n/**\n * Compiles one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf\n * {@link expandTables} maps over.\n *\n * @param spec - The column spec to compile\n * @returns The `@orkestrel/database` column shape, wrapped in `optionalShape` when the spec declares `optional: true`\n */\nexport function compileColumn(spec: ColumnSpec): ContractShape {\n\tconst primitive = isString(spec) ? spec : spec.primitive\n\tconst optional = !isString(spec) && spec.optional === true\n\tconst shape = compileColumnPrimitive(primitive)\n\treturn optional ? optionalShape(shape) : shape\n}\n\n/**\n * Compiles one {@link import('./types.js').ColumnPrimitive} into its primitive\n * `@orkestrel/database` shape — the leaf {@link compileColumn} wraps.\n *\n * @param primitive - The declared column primitive\n * @returns The matching primitive `@orkestrel/database` shape\n */\nexport function compileColumnPrimitive(primitive: ColumnPrimitive): ContractShape {\n\tif (primitive === 'string') return stringShape()\n\tif (primitive === 'integer') return integerShape()\n\tif (primitive === 'number') return numberShape()\n\treturn booleanShape()\n}\n","import type { DatabaseDefinition, DefinitionStoreInterface } from '../types.js'\n\n/**\n * Represents the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of\n * {@link DatabaseDefinition}s keyed by database id, the default store\n * {@link import('../factories.js').createMemoryDefinitionStore} builds. It implements the same\n * {@link DefinitionStoreInterface} contract as\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}: this store copies on\n * write and on read; the table-backed store narrows an untrusted stored blob and reports\n * `undefined` for a malformed one.\n *\n * @remarks\n * A plain `Map<string, DatabaseDefinition>` (the definition is already pure,\n * self-contained config-only JSON, so no encoding is needed for the memory tier). Values are\n * structured-cloned on both write and read, keeping caller mutation outside the store. There is no\n * idle-TTL and no eviction: a persisted definition lives until an explicit `delete`. A durable\n * backend (JSON / SQLite / IndexedDB) swaps in through the same interface without touching a\n * consumer — its driver-pluggable twin is\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore} (the definition as one\n * opaque JSON column).\n *\n * - **`get` resolves the persisted definition for an id**, or `undefined` if none is stored.\n * - **`set` inserts / replaces under the definition's own `id`** (no separate id param).\n * - **`delete` drops a definition by id**; an absent id is a no-op (no throw).\n *\n * The public surface is exactly `get` / `set` / `delete` — no extra members (the method\n * bijection with {@link DefinitionStoreInterface}).\n *\n * @example\n * ```ts\n * import { createMemoryDefinitionStore } from '@src/core'\n *\n * const store = createMemoryDefinitionStore()\n * await store.set({ id: 'shop', driver: 'memory', tables: {} })\n * const definition = await store.get('shop')\n * await store.delete('shop')\n * ```\n */\nexport class MemoryDefinitionStore implements DefinitionStoreInterface {\n\treadonly #definitions = new Map<string, DatabaseDefinition>()\n\n\t/**\n\t * Resolves the persisted definition for `id`, copied out of the backing `Map`.\n\t *\n\t * @param id - The database id to read\n\t * @returns The stored {@link DatabaseDefinition}, or `undefined` when none is stored\n\t */\n\tget(id: string): Promise<DatabaseDefinition | undefined> {\n\t\tconst definition = this.#definitions.get(id)\n\t\treturn Promise.resolve(definition === undefined ? undefined : structuredClone(definition))\n\t}\n\n\t/**\n\t * Inserts or replaces a definition under its own `id`, copied into the backing `Map`.\n\t *\n\t * @param definition - The config to persist; its own `id` is the key (no separate id param)\n\t * @returns A promise settling after the definition is stored\n\t */\n\tset(definition: DatabaseDefinition): Promise<void> {\n\t\tthis.#definitions.set(definition.id, structuredClone(definition))\n\t\treturn Promise.resolve()\n\t}\n\n\t/**\n\t * Drops the definition stored under `id`.\n\t *\n\t * @param id - The database id to drop; an absent id is a no-op, never a throw\n\t * @returns A promise settling after no definition is stored under `id`\n\t */\n\tdelete(id: string): Promise<void> {\n\t\tthis.#definitions.delete(id)\n\t\treturn Promise.resolve()\n\t}\n}\n","import type {\n\tDatabaseDefinition,\n\tDatabaseDefinitionRow,\n\tDefinitionStoreInterface,\n} from '../types.js'\nimport type { TableInterface } from '@orkestrel/database'\nimport { isDatabaseDefinition } from '../validators.js'\n\n/**\n * Represents a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database` layer — a\n * database's durable config state is a row, so persistence reduces to keyed point-access\n * (`get` / `set` / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the\n * plain-`Map` {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}.\n *\n * @remarks\n * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,\n * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /\n * IndexedDB backend swaps in without touching a consumer — the same seam as\n * {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}. The driver defaults to\n * memory ({@link import('../factories.js').createDatabaseDefinitionStore} passes\n * `createMemoryDriver()`), so it also works in memory out of the box; you opt into the durable\n * plumbing by passing a JSON / SQLite / IndexedDB driver.\n *\n * The {@link DatabaseDefinition} is stored as one opaque JSON column — the table is a row of\n * `{ id; definition }` ({@link DatabaseDefinitionRow}). The definition is already a complete,\n * self-contained, pure-JSON config payload (never a live handle), so storing it whole is lossless\n * and keeps the row type flat (`definition` reads back as `unknown`).\n *\n * - **`set(definition)` upserts under the definition's own `id`** (no separate id param) — it\n * writes the row `{ id: definition.id, definition }`.\n * - **`get(id)` resolves the stored definition for an id**, narrowing the opaque JSON column back\n * to a {@link DatabaseDefinition} ({@link import('../validators.js').isDatabaseDefinition} — the\n * boundary narrow for an untrusted storage read), or `undefined` if none is stored\n * or the stored blob is malformed.\n * - **`delete(id)` drops a definition by id**; an absent id is a no-op (no throw).\n *\n * The public surface is exactly `get` / `set` / `delete` — no extra members (the method\n * bijection with {@link DefinitionStoreInterface}).\n *\n * @example\n * ```ts\n * import { createDatabaseDefinitionStore, createMemoryDriver } from '@src/core'\n *\n * const store = createDatabaseDefinitionStore(createMemoryDriver()) // a durable driver swaps in here\n * await store.set({ id: 'shop', driver: 'memory', tables: {} }) // persist the config (one JSON column)\n * const definition = await store.get('shop')\n * await store.delete('shop')\n * ```\n */\nexport class DatabaseDefinitionStore implements DefinitionStoreInterface {\n\treadonly #table: TableInterface<DatabaseDefinitionRow>\n\n\t/**\n\t * Wraps a table as a definition store.\n\t *\n\t * @param table - The {@link TableInterface} holding the definitions — its row is the\n\t * {@link DatabaseDefinitionRow} `{ id; definition }` shape (the definition one opaque JSON column)\n\t */\n\tconstructor(table: TableInterface<DatabaseDefinitionRow>) {\n\t\tthis.#table = table\n\t}\n\n\t/**\n\t * Resolves the persisted definition for `id`, narrowing the opaque JSON column back to a\n\t * {@link DatabaseDefinition}.\n\t *\n\t * @param id - The database id to read\n\t * @returns The stored {@link DatabaseDefinition}, or `undefined` when none is stored or the\n\t * stored blob is malformed\n\t */\n\tasync get(id: string): Promise<DatabaseDefinition | undefined> {\n\t\tconst row = await this.#table.get(id)\n\t\tif (row === undefined) return undefined\n\t\t// The definition crosses back as an untrusted storage read (a structured clone / a JSON\n\t\t// row), so narrow the opaque JSON column with the boundary guard rather than a cast; a\n\t\t// malformed blob resolves `undefined`, never a broken definition.\n\t\treturn isDatabaseDefinition(row.definition) ? row.definition : undefined\n\t}\n\n\t/**\n\t * Inserts or replaces a definition under its own `id` — the written row is `{ id, definition }`.\n\t *\n\t * @param definition - The config to persist; its own `id` is the row key (no separate id param)\n\t * @returns A promise settling after the row is written\n\t */\n\tasync set(definition: DatabaseDefinition): Promise<void> {\n\t\tawait this.#table.set({ id: definition.id, definition })\n\t}\n\n\t/**\n\t * Drops the definition stored under `id`.\n\t *\n\t * @param id - The database id to drop; an absent id is a no-op, never a throw\n\t * @returns A promise settling after no row is stored under `id`\n\t */\n\tasync delete(id: string): Promise<void> {\n\t\tawait this.#table.remove(id)\n\t}\n}\n","import type { DatabaseInterface, DriverInterface, KeyFunction } from '@orkestrel/database'\nimport type { DefinitionStoreInterface } from '../types.js'\nimport { createDatabase } from '@orkestrel/database'\nimport { ToolboxError } from '../errors.js'\nimport { expandTables } from '../compilers.js'\n\n/**\n * Resolves a database definition into a cached live handle for a database tool, over the tool's\n * live handles, its stored definitions, its driver registry, and an optional key generator.\n *\n * @example\n * ```ts\n * import { DatabaseResolver } from '@orkestrel/toolbox'\n *\n * const resolver = new DatabaseResolver(handles, drivers, generator, store)\n * const database = await resolver.resolve('shop')\n * ```\n */\nexport class DatabaseResolver {\n\treadonly #handles: Map<string, DatabaseInterface>\n\treadonly #drivers: Readonly<Record<string, () => DriverInterface>>\n\treadonly #generator: KeyFunction | undefined\n\treadonly #store: DefinitionStoreInterface | undefined\n\n\t/**\n\t * Creates a database resolver over the tool's live state and optional definition store.\n\t *\n\t * @param handles - Initial live database handles cached by id\n\t * @param drivers - Driver factories keyed by definition driver name\n\t * @param generator - Optional key generator supplied to newly created databases\n\t * @param store - Optional persistent definition store\n\t */\n\tconstructor(\n\t\thandles: ReadonlyMap<string, DatabaseInterface>,\n\t\tdrivers: Readonly<Record<string, () => DriverInterface>>,\n\t\tgenerator?: KeyFunction,\n\t\tstore?: DefinitionStoreInterface,\n\t) {\n\t\tthis.#handles = new Map(handles)\n\t\tthis.#drivers = drivers\n\t\tthis.#generator = generator\n\t\tthis.#store = store\n\t}\n\n\t/**\n\t * Determines whether a live database is cached by id.\n\t *\n\t * @param id - Database id\n\t * @returns True if a live handle is cached; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#handles.has(id)\n\t}\n\n\t/**\n\t * Reads a cached database without consulting the definition store.\n\t *\n\t * @param id - Database id\n\t * @returns The cached live database, or `undefined`\n\t */\n\tget(id: string): DatabaseInterface | undefined {\n\t\treturn this.#handles.get(id)\n\t}\n\n\t/**\n\t * Caches a live database by id.\n\t *\n\t * @param id - Database id\n\t * @param database - Live database handle\n\t * @returns Nothing\n\t */\n\tset(id: string, database: DatabaseInterface): void {\n\t\tthis.#handles.set(id, database)\n\t}\n\n\t/**\n\t * Removes a cached live database by id.\n\t *\n\t * @param id - Database id\n\t * @returns Nothing\n\t */\n\tdelete(id: string): void {\n\t\tthis.#handles.delete(id)\n\t}\n\n\t/**\n\t * Resolves a live database by id — the cached handle when one exists, otherwise a database\n\t * constructed from its stored definition.\n\t *\n\t * @param id - Database definition id\n\t * @returns The cached or newly constructed live database\n\t */\n\tasync resolve(id: string): Promise<DatabaseInterface> {\n\t\tconst cached = this.#handles.get(id)\n\t\tif (cached !== undefined) return cached\n\t\tif (this.#store !== undefined) {\n\t\t\tconst definition = await this.#store.get(id)\n\t\t\tif (definition !== undefined) {\n\t\t\t\tconst factory = this.#drivers[definition.driver]\n\t\t\t\tif (factory === undefined) {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown driver '${definition.driver}'`, {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tdriver: definition.driver,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst handle = createDatabase({\n\t\t\t\t\tdriver: factory(),\n\t\t\t\t\ttables: expandTables(definition.tables),\n\t\t\t\t\tname: id,\n\t\t\t\t\t...(definition.primary === undefined ? {} : { primary: definition.primary }),\n\t\t\t\t\t...(definition.indexes === undefined ? {} : { indexes: definition.indexes }),\n\t\t\t\t\t...(definition.version === undefined ? {} : { version: definition.version }),\n\t\t\t\t\t...(this.#generator === undefined ? {} : { generator: this.#generator }),\n\t\t\t\t})\n\t\t\t\tthis.set(id, handle)\n\t\t\t\treturn handle\n\t\t\t}\n\t\t}\n\t\tthrow new ToolboxError('TOOL', `unknown database '${id}'`, { id })\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type { AgentInterface, AgentRegistryInterface } from '@orkestrel/agent'\nimport type { WorkspaceManagerInterface } from '@orkestrel/workspace'\nimport type { ToolInterface, ToolManagerInterface } from '@orkestrel/tool'\nimport type {\n\tWorkflowDefinition,\n\tWorkflowFunction,\n\tWorkflowRegistry,\n\tWorkflowRunnerInterface,\n\tTaskControllerInterface,\n} from '@orkestrel/workflow'\nimport type {\n\tAgentFunction,\n\tAgentFunctionOptions,\n\tWorkflowAgents,\n\tAgentToolOptions,\n\tAnswerToolOptions,\n\tDatabaseDefinition,\n\tDatabaseDefinitionRow,\n\tDatabaseToolOptions,\n\tDefinitionStoreInterface,\n\tEndpointDefinition,\n\tEndpointToolOptions,\n\tInferToolOptions,\n\tPromptToolOptions,\n\tRelationToolOptions,\n\tWorkflowDraft,\n\tWorkflowSteps,\n\tWorkflowToolOptions,\n\tWorkspaceOperation,\n\tWorkspaceToolOptions,\n} from './types.js'\nimport type { DatabaseInterface, DriverInterface, TableInterface } from '@orkestrel/database'\nimport { agentResultToJSON } from '@orkestrel/agent'\nimport { createWorkspaceManager, isText, rangeOf } from '@orkestrel/workspace'\nimport { createTool } from '@orkestrel/tool'\nimport {\n\tattempt,\n\tcloneJSONRecord,\n\tcreateContract,\n\tisArray,\n\tisError,\n\tisFunction,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tparseJSONValue,\n\trawShape,\n\tsamplesToSchema,\n\tschemaToObject,\n\tschemaToParameters,\n\tschemaToShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { createForm, isFormError, isFormValues, parseForm } from '@orkestrel/form'\nimport { createDatabase, createMemoryDriver } from '@orkestrel/database'\nimport { createWorkflowContract } from '@orkestrel/workflow'\nimport { MemoryDefinitionStore } from './stores/MemoryDefinitionStore.js'\nimport { DatabaseDefinitionStore } from './stores/DatabaseDefinitionStore.js'\nimport { DatabaseResolver } from './databases/DatabaseResolver.js'\nimport {\n\tAGENT_TOOL_DEPTH,\n\tAGENT_TOOL_DESCRIPTION,\n\tAGENT_TOOL_NAME,\n\tAGENT_TOOL_SUMMARY,\n\tANSWER_TOOL_DESCRIPTION,\n\tANSWER_TOOL_NAME,\n\tANSWER_TOOL_SUMMARY,\n\tDATABASE_TOOL_DESCRIPTION,\n\tDATABASE_TOOL_LIMIT,\n\tDATABASE_TOOL_MUTATIONS,\n\tDATABASE_TOOL_NAME,\n\tDATABASE_TOOL_SUMMARY,\n\tDESCRIBE_TOOL_DESCRIPTION,\n\tDESCRIBE_TOOL_NAME,\n\tDESCRIBE_TOOL_SUMMARY,\n\tINFER_TOOL_DESCRIPTION,\n\tINFER_TOOL_NAME,\n\tINFER_TOOL_SUMMARY,\n\tMAX_WORKFLOW_CHAIN,\n\tPROMPT_TOOL_DESCRIPTION,\n\tPROMPT_TOOL_NAME,\n\tPROMPT_TOOL_SUMMARY,\n\tRELATION_TOOL_DEPTH,\n\tRELATION_TOOL_DESCRIPTION,\n\tRELATION_TOOL_LIMIT,\n\tRELATION_TOOL_NAME,\n\tRELATION_TOOL_SUMMARY,\n\tWORKFLOW_TOOL_DESCRIPTION,\n\tWORKFLOW_TOOL_NAME,\n\tWORKFLOW_TOOL_SUMMARY,\n\tWORKSPACE_TOOL_DESCRIPTION,\n\tWORKSPACE_TOOL_NAME,\n\tWORKSPACE_TOOL_SUMMARY,\n} from './constants.js'\nimport { ToolboxError, isToolboxError } from './errors.js'\nimport {\n\tclampQuery,\n\tcompleteDraft,\n\tderiveWorkflowDepth,\n\texpandInclude,\n\texpandSteps,\n\textendLineage,\n\tinferDatabaseCode,\n\tinferRelationCode,\n\tinferTerminalCode,\n\tnormalizeLineage,\n\tnormalizeQuery,\n\tresolveLimit,\n\tresolveRelationManager,\n\tresolveRelationModel,\n\tsummarizeWorkflow,\n\ttagAgent,\n\ttagWorkflow,\n} from './helpers.js'\nimport { expandTables } from './compilers.js'\nimport { isAgentFunction } from './validators.js'\nimport {\n\tagentToolShape,\n\tanswerToolShape,\n\tdatabaseToolShape,\n\tdescribeToolShape,\n\tinferToolShape,\n\tpromptToolShape,\n\trelationToolShape,\n\tworkflowDraftShape,\n\tworkflowStepsShape,\n\tworkspaceToolShape,\n} from './shapers.js'\n\n// This package's tool factories. `createWorkflowTool` owns authoring translation and boundary\n// policy while delegating execution/persistence to `@orkestrel/workflow`; `createWorkspaceTool`\n// owns the model-facing operation dispatch over `@orkestrel/workspace`; `createAgentTool` owns\n// sub-agent delegation over an `AgentRegistryInterface`.\n\n/**\n * Wraps a registered tool as a {@link WorkflowFunction} (`@orkestrel/workflow`) — the opt-in\n * adapter that lets a `function`-form task run a `@orkestrel/tool` tool by name.\n *\n * @remarks\n * Composes into a caller's `WorkflowOptions.functions` registry like any other behavior\n * (`{ publish: createToolFunction(tools, 'publish') }`); the pure workflow runner has no\n * knowledge of tools itself. The returned function executes `name` against `tools` with the\n * task's `controller.input` as the call arguments. The adapter resolves the live tool, calls its\n * `execute` method directly, and deep-gates the returned unknown through `parseJSONValue`. The\n * execution context it passes carries the task's own `controller.signal`, so a handler that\n * reads `context.signal` observes the caller's cancellation.\n * Genuine execution throws retain identity. An unregistered name or non-JSON return throws this\n * package's typed `TOOL` `ToolboxError`.\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/tool`) the named tool is registered on\n * @param name - The registered tool's name\n * @returns A {@link WorkflowFunction} that runs the named tool\n *\n * @example\n * ```ts\n * import { createToolFunction } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const tools = createToolManager()\n * tools.add(myPublishTool)\n * const runner = createWorkflowRunner()\n * await runner.execute(definition, { functions: { publish: createToolFunction(tools, 'publish') } })\n * ```\n */\nexport function createToolFunction(tools: ToolManagerInterface, name: string): WorkflowFunction {\n\tif (name === WORKFLOW_TOOL_NAME) {\n\t\tthrow new ToolboxError('TOOL', `tool '${WORKFLOW_TOOL_NAME}' is reserved for live workflows`, {\n\t\t\ttool: name,\n\t\t})\n\t}\n\treturn async (controller) => {\n\t\tconst tool = tools.tool(name)\n\t\tif (tool === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `tool '${name}' is not registered`, { tool: name })\n\t\t}\n\t\tconst result = parseJSONValue(\n\t\t\tawait tool.execute(controller.input, { signal: controller.signal }),\n\t\t)\n\t\tif (result === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `tool '${name}' returned a non-JSON value`, { tool: name })\n\t\t}\n\t\treturn result\n\t}\n}\n\n/**\n * Wraps a live `AgentInterface` (`@orkestrel/agent`) as a {@link WorkflowFunction}\n * (`@orkestrel/workflow`) — the opt-in adapter that runs the agent to a settled result and carries\n * immutable lineage metadata for contextual Toolbox composition.\n *\n * @remarks\n * Composes into a caller's registry like any other behavior; the pure workflow runner has no\n * knowledge of agents itself. A root adapter derives its workflow lineage from the controller,\n * while a contextual adapter requires an exact match. Repeated agents, repeated workflows, and\n * targets deeper than {@link import('./constants.js').MAX_WORKFLOW_CHAIN} are rejected before\n * agent or runner activity. When {@link import('./types.js').AgentFunctionOptions.runner} is\n * supplied, the adapter binds a recursion-safe {@link createWorkflowTool} onto the agent's\n * `context.tools`, propagating opaque leaves, raw agents, lineage, and the native store. The\n * task's cancellation propagates through the Agent's native per-run signal seam:\n * `agent.generate({ signal: controller.signal })` resolves a partial `AgentResult` on a cancel\n * (never rejects), projected onto its exact JSON fields.\n *\n * A bound agent is single-run. A concurrent branch sharing the same real agent is rejected before\n * its fixed {@link import('./constants.js').WORKFLOW_TOOL_NAME} binding can be replaced. Toolbox\n * cannot serialize opaque external wrappers that hide or bypass the raw agent registry; hosts\n * must give such concurrent work distinct agents.\n *\n * @param agent - The live `AgentInterface` to run\n * @param options - The nested-workflow composition and lineage options\n * @returns A frozen {@link AgentFunction} that runs `agent` to its settled result\n *\n * @example\n * ```ts\n * import { createAgentFunction } from '@src/core'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const runner = createWorkflowRunner()\n * const review = createAgentFunction(myAgent, { runner })\n * await runner.execute(definition, { functions: { review } })\n * ```\n */\nexport function createAgentFunction(\n\tagent: AgentInterface,\n\toptions?: AgentFunctionOptions,\n): AgentFunction {\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('workflow:')) {\n\t\tthrow new ToolboxError('TOOL', 'agent function lineage must end with a workflow tag')\n\t}\n\tconst functions =\n\t\toptions?.functions === undefined ? undefined : Object.freeze({ ...options.functions })\n\tconst agents = options?.agents === undefined ? undefined : Object.freeze({ ...options.agents })\n\tconst metadata: Pick<AgentFunction, 'category' | 'lineage'> = {\n\t\tcategory: 'agent',\n\t\tlineage,\n\t}\n\treturn Object.freeze(\n\t\tObject.assign(async (controller: TaskControllerInterface) => {\n\t\t\tconst workflow = tagWorkflow(controller.task.phase.workflow.id)\n\t\t\tconst current = lineage.length === 0 ? extendLineage(lineage, workflow) : lineage\n\t\t\tif (current.at(-1) !== workflow) {\n\t\t\t\tthrow new ToolboxError('DEPTH', 'agent function workflow does not match its lineage', {\n\t\t\t\t\tworkflow,\n\t\t\t\t\tlineage: [...current],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst depth = deriveWorkflowDepth(current)\n\t\t\t// Reject over-depth or re-entry before the agent, tool registry, or runner becomes active.\n\t\t\tif (depth > MAX_WORKFLOW_CHAIN) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${agent.id}' exceeds max workflow depth`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_CHAIN,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagAgent(agent.id)\n\t\t\tif (current.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${agent.id}' is already an ancestor (cycle)`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t\tlineage: [...current],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst nested = extendLineage(current, tag)\n\t\t\t// Bind the nested workflow tool with this agent appended to the immutable lineage.\n\t\t\tconst runner = options?.runner\n\t\t\tif (runner !== undefined) {\n\t\t\t\tif (agent.status === 'running') {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `agent '${agent.id}' is already running`, {\n\t\t\t\t\t\tagent: agent.id,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst workflowId = controller.task.phase.workflow.id\n\t\t\t\tconst wrapped: WorkflowDefinition = { id: workflowId, name: workflowId, phases: [] }\n\t\t\t\tagent.context.tools.add(\n\t\t\t\t\tcreateWorkflowTool(wrapped, runner, {\n\t\t\t\t\t\tlineage: nested,\n\t\t\t\t\t\t...(functions === undefined ? {} : { functions }),\n\t\t\t\t\t\t...(agents === undefined ? {} : { agents }),\n\t\t\t\t\t\t...(options?.store === undefined ? {} : { store: options.store }),\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\t\t\t// Start synchronously with the task's native per-run signal so Agent owns cancellation,\n\t\t\t// including already-aborted signals and partial-result settlement.\n\t\t\tconst generated = agent.generate({ signal: controller.signal })\n\t\t\tconst result = agentResultToJSON(await generated)\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `agent '${agent.id}' returned a non-JSON result`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn result\n\t\t}, metadata),\n\t)\n}\n\n/**\n * Composes opaque host functions and raw agents into one immutable workflow registry.\n *\n * @remarks\n * This is the target-aware composition boundary used by direct runner consumers and\n * {@link createWorkflowTool}. Opaque leaves are copied unchanged, marked agent adapters are\n * rejected from that channel, raw agents are rebound to the supplied lineage, collisions fail\n * closed, and the returned null-prototype record prevents inherited names from becoming phantom\n * Workflow handlers.\n *\n * @param runner - The native runner propagated into contextual agent adapters\n * @param options - Target lineage, opaque functions, raw agents, and native store\n * @returns A frozen null-prototype snapshot of the target workflow's callable registry\n *\n * @example\n * ```ts\n * import { createWorkflowFunctions } from '@src/core'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const runner = createWorkflowRunner()\n * const functions = createWorkflowFunctions(runner, {\n * \tfunctions: { publish: async () => 'published' },\n * \tagents: { review: reviewAgent },\n * })\n * await runner.execute(definition, { functions })\n * ```\n */\nexport function createWorkflowFunctions(\n\trunner: WorkflowRunnerInterface,\n\toptions?: WorkflowToolOptions,\n): WorkflowRegistry {\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('workflow:')) {\n\t\tthrow new ToolboxError('TOOL', 'workflow functions lineage must end with a workflow tag')\n\t}\n\tconst functions: WorkflowRegistry =\n\t\toptions?.functions === undefined ? Object.freeze({}) : Object.freeze({ ...options.functions })\n\tconst agents: WorkflowAgents =\n\t\toptions?.agents === undefined ? Object.freeze({}) : Object.freeze({ ...options.agents })\n\tconst composed: Record<string, WorkflowFunction> = {}\n\tObject.setPrototypeOf(composed, null)\n\tfor (const [name, fn] of Object.entries(functions)) {\n\t\tif (!isFunction(fn)) {\n\t\t\tthrow new ToolboxError('TOOL', `workflow function '${name}' is not callable`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tif (isAgentFunction(fn)) {\n\t\t\tthrow new ToolboxError('TOOL', `agent function '${name}' must be supplied through agents`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tcomposed[name] = fn\n\t}\n\tfor (const [name, agent] of Object.entries(agents)) {\n\t\tif (Object.hasOwn(composed, name)) {\n\t\t\tthrow new ToolboxError('TOOL', `workflow function '${name}' collides with an agent`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tconst fn = createAgentFunction(agent, {\n\t\t\trunner,\n\t\t\tlineage,\n\t\t\tfunctions,\n\t\t\tagents,\n\t\t\t...(options?.store === undefined ? {} : { store: options.store }),\n\t\t})\n\t\tcomposed[name] = fn\n\t}\n\treturn Object.freeze(composed)\n}\n\n/**\n * Compiles the lenient workflow draft contract {@link createWorkflowTool} parses an authored tree\n * with — a `ContractInterface` over a {@link WorkflowDraft}, whose `id` and `name` are optional at\n * the workflow, phase, and task levels.\n *\n * @returns The compiled {@link import('./types.js').WorkflowDraft} contract\n */\nexport function createWorkflowDraftContract(): ContractInterface<WorkflowDraft> {\n\treturn createContract(workflowDraftShape)\n}\n\n/**\n * Wraps a {@link WorkflowDefinition} as an LLM-callable tool — it advertises the flat authoring\n * shape (`{ name?, steps: [{ name }] }`) as its `parameters`, and its handler completes the\n * authored blob, validates it against the strict contract, and runs it through `runner`, forwarding\n * the caller's optional named functions and native checkpoint store.\n *\n * @remarks\n * A plain `ToolManagerInterface`-compatible tool (`@orkestrel/tool`), reproducing\n * Toolbox's flat / draft / full authoring contract, strict soundness gate, and lineage guard.\n * It is also the propagation carrier\n * {@link createAgentFunction} binds onto a wrapped agent's `context.tools`: because a tool\n * handler receives only the model-supplied `args`, the immutable lineage is closed over at bind\n * time. The authored target is appended and its zero-based depth derived from workflow tags.\n *\n * **Widened authoring surface (additive — the canonical contract and runner stay strict and\n * unchanged).** A 2B model reliably calls the tool but cannot reliably emit the full nested\n * {@link WorkflowDefinition}, whose every `id` and `name` is required across an all-or-nothing\n * tree. So the tool accepts the authoring forms that follow and converges them on the same strict\n * `createWorkflowContract` gate before running (soundness preserved):\n * - the flat shape `{ name?, steps: [{ name }] }` — the advertised `parameters` (the simplest\n * form, {@link import('./helpers.js').expandSteps}'d into one one-task phase per step);\n * - a nested draft with any `id`/`name` omitted — {@link createWorkflowDraftContract}-parsed then\n * {@link import('./helpers.js').completeDraft}'d (missing ids synthesized positionally);\n * - the full nested {@link WorkflowDefinition} — the advanced escape-hatch, accepted as the draft\n * super-set.\n *\n * The universal tool-handler contract: returns the plain run summary\n * (`{ status, count, durable?, fault? }`) on success, throws a typed `ToolboxError` on Toolbox\n * boundary failures — malformed authored args (`TOOL`), or an over-deep / cyclic nested run\n * (`DEPTH`) — and preserves genuine runner `WorkflowError`s. The `ToolManagerInterface` isolates every throw into the canonical tool result's\n * top-level `error`, so nothing escapes the run. `options.lineage` is the propagation carrier\n * across a workflow → agent → workflow chain. Opaque `functions` remain host leaves; raw `agents`\n * are contextually adapted through {@link createWorkflowFunctions}; native checkpoint persistence\n * makes the final snapshot retrievable without a second Toolbox write.\n *\n * @param definition - The workflow the tool runs when called with no authored args\n * @param runner - The `WorkflowRunnerInterface` (`@orkestrel/workflow`) that executes the (nested) workflow\n * @param options - Lineage-aware functions, agents, and optional native store\n * @returns A `ToolInterface` (named {@link import('./constants.js').WORKFLOW_TOOL_NAME}) whose\n * `parameters` advertise the flat authoring schema\n *\n * @example Authoring and running a workflow through the tool with a real ToolManager\n * ```ts\n * import { createWorkflowTool } from '@orkestrel/toolbox'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n * import type { WorkflowDefinition } from '@orkestrel/workflow'\n *\n * const definition: WorkflowDefinition = { id: 'release', name: 'Release', phases: [] }\n * const runner = createWorkflowRunner()\n * const functions = {\n * \tcompile: () => 'compiled',\n * \tpublish: () => 'published',\n * }\n * const tool = createWorkflowTool(definition, runner, { functions })\n *\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * // A small model authors the simple flat shape — no ids/names required.\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'workflow',\n * \targuments: { name: 'release', steps: [{ name: 'compile' }, { name: 'publish' }] },\n * })\n * if (!result.success) throw new Error(result.error)\n * result.value // { status: 'completed', count: 2 } — the single-level envelope; no nested { id, name, value }\n * ```\n *\n * @example\n * ```ts\n * import { createWorkflowTool } from '@src/core'\n * import { createWorkflowRunner, createMemoryWorkflowStore } from '@orkestrel/workflow'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const runner = createWorkflowRunner()\n * const store = createMemoryWorkflowStore()\n * const tool = createWorkflowTool(definition, runner, { store })\n * const tools = createToolManager()\n * tools.add(tool) // authored runs now use native checkpoints through `store`\n * ```\n */\nexport function createWorkflowTool(\n\tdefinition: WorkflowDefinition,\n\trunner: WorkflowRunnerInterface,\n\toptions?: WorkflowToolOptions,\n): ToolInterface {\n\tconst strict = createWorkflowContract()\n\tconst draft = createWorkflowDraftContract()\n\tconst steps: ContractInterface<WorkflowSteps> = createContract(workflowStepsShape)\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('agent:')) {\n\t\tthrow new ToolboxError('TOOL', 'workflow tool lineage must end with an agent tag')\n\t}\n\tconst functions =\n\t\toptions?.functions === undefined ? undefined : Object.freeze({ ...options.functions })\n\tconst agents = options?.agents === undefined ? undefined : Object.freeze({ ...options.agents })\n\tconst store = options?.store\n\tconst parameters = schemaToParameters(steps.schema)\n\treturn createTool({\n\t\tname: WORKFLOW_TOOL_NAME,\n\t\tdescription: WORKFLOW_TOOL_DESCRIPTION,\n\t\tsummary: WORKFLOW_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst cloned = attempt(() => cloneJSONRecord(args))\n\t\t\tif (!cloned.success) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed workflow definition', {\n\t\t\t\t\tworkflow: definition.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst owned = cloned.value\n\t\t\t// Branch on the owned args snapshot's shape (no ambient context — a tool handler gets only\n\t\t\t// `args`): empty ⇒ the wrapped definition; a `steps` array ⇒ the flat form, parsed and\n\t\t\t// expanded; otherwise the nested draft form, parsed and completed. A parse failure leaves\n\t\t\t// `target` undefined ⇒ the strict gate that follows throws `TOOL`.\n\t\t\tlet target: WorkflowDefinition | undefined\n\t\t\tif (Object.keys(owned).length === 0) {\n\t\t\t\ttarget = definition\n\t\t\t} else if (isArray(owned.steps)) {\n\t\t\t\tconst flat = steps.parse(owned)\n\t\t\t\ttarget = flat === undefined ? undefined : expandSteps(flat)\n\t\t\t} else {\n\t\t\t\tconst parsed = draft.parse(owned)\n\t\t\t\ttarget = parsed === undefined ? undefined : completeDraft(parsed)\n\t\t\t}\n\t\t\t// The soundness gate: whatever authoring form produced `target`, it must satisfy the\n\t\t\t// strict canonical contract before it runs — the leniency never reaches the runner.\n\t\t\tif (target === undefined || !strict.is(target)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed workflow definition', {\n\t\t\t\t\tworkflow: definition.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagWorkflow(target.id)\n\t\t\tif (lineage.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `workflow '${target.id}' is already an ancestor (cycle)`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tlineage: [...lineage],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst targetLineage = extendLineage(lineage, tag)\n\t\t\tconst depth = deriveWorkflowDepth(targetLineage)\n\t\t\tif (depth > MAX_WORKFLOW_CHAIN) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `nested workflow exceeds max depth ${MAX_WORKFLOW_CHAIN}`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_CHAIN,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst registry =\n\t\t\t\tfunctions === undefined && agents === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: createWorkflowFunctions(runner, {\n\t\t\t\t\t\t\tlineage: targetLineage,\n\t\t\t\t\t\t\t...(functions === undefined ? {} : { functions }),\n\t\t\t\t\t\t\t...(agents === undefined ? {} : { agents }),\n\t\t\t\t\t\t\t...(store === undefined ? {} : { store }),\n\t\t\t\t\t\t})\n\t\t\tconst result = await runner.execute(target, {\n\t\t\t\t...(registry === undefined ? {} : { functions: registry }),\n\t\t\t\t...(store === undefined ? {} : { store }),\n\t\t\t})\n\t\t\treturn summarizeWorkflow(result)\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable workspace-editing tool — it advertises the `operation`-discriminated union\n * ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its handler parses\n * the model-supplied args against that contract and dispatches the matched operation against the\n * manager's active workspace, returning the plain result.\n *\n * @remarks\n * Manager-driven: every edit / read op (read / list / has / search / replace / write / splice /\n * prepend / append / move / remove) targets `manager.active`, so the model edits whichever\n * workspace is active and a host can re-point it (`WorkspaceManagerInterface.switch`) between\n * turns. The registry ops make the model self-sufficient: `workspaces` lists the registered\n * workspaces (each `{ id, files, active }`) so it can discover an id, and `switch` re-points the\n * active workspace by id (lenient — an unknown id is a no-op reporting `switched: false`, never a\n * throw).\n *\n * No-active rule (the ergonomic seam): a writing op (write / splice / prepend / append / move /\n * remove / replace) run when `manager.active` is `undefined` auto-creates and activates a default\n * workspace (`manager.add()`) so the model can start writing; a pure-read op (read / list /\n * has / search) against no active workspace returns the empty result (`undefined` / `[]` /\n * `false`), never creating one and never throwing.\n *\n * The handler conforms to the universal tool-handler contract: it `contract.parse`s\n * the args, throws a `TOOL` `ToolboxError` when no operation arm matched (a malformed / unknown\n * operation), else `switch`es on `op.operation` and returns the plain result — letting a\n * `WorkspaceError` raised by the live workspace (`MISSING` / `MODALITY` / `PATTERN` / `RANGE`)\n * propagate uncaught. The range edit is the flat `'splice'` op: its flat caret integers are\n * reassembled into a `Range` (`@orkestrel/workspace`) by `rangeOf` and fed to the workspace's\n * ranged `write`.\n *\n * @param options - `manager` (drive directly) or `store` (build a manager over it); neither ⇒\n * an in-memory-backed manager (see {@link import('./types.js').WorkspaceToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').WORKSPACE_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createWorkspaceTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createWorkspaceTool() // in-memory workspace, no persistence\n * const tools = createToolManager()\n * tools.add(tool)\n * ```\n */\nexport function createWorkspaceTool(options?: WorkspaceToolOptions): ToolInterface {\n\tconst manager: WorkspaceManagerInterface =\n\t\toptions?.manager ??\n\t\tcreateWorkspaceManager(options?.store === undefined ? undefined : { store: options.store })\n\tconst contract: ContractInterface<WorkspaceOperation> = createContract(workspaceToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options?.name ?? WORKSPACE_TOOL_NAME,\n\t\tdescription: options?.description ?? WORKSPACE_TOOL_DESCRIPTION,\n\t\tsummary: WORKSPACE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\texecute(args) {\n\t\t\tconst op = contract.parse(args)\n\t\t\tif (op === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'unknown or malformed operation', { args })\n\t\t\t}\n\t\t\t// Registry ops act on the manager, not a workspace — handle them first.\n\t\t\tif (op.operation === 'workspaces') {\n\t\t\t\tconst activeId = manager.active?.id\n\t\t\t\treturn manager.workspaces().map((workspace) => ({\n\t\t\t\t\tid: workspace.id,\n\t\t\t\t\tfiles: workspace.count,\n\t\t\t\t\tactive: workspace.id === activeId,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tif (op.operation === 'switch') {\n\t\t\t\tconst switched = manager.switch(op.id)\n\t\t\t\t// Lenient: an unknown id leaves `active` unchanged and reports `switched: false`.\n\t\t\t\treturn switched === undefined\n\t\t\t\t\t? { id: op.id, switched: false }\n\t\t\t\t\t: { id: switched.id, switched: true, files: switched.count }\n\t\t\t}\n\t\t\t// Edit and read ops target the active workspace. A writing op auto-creates and activates a\n\t\t\t// default workspace when none is active (the no-active ergonomic seam) — while a pure-read\n\t\t\t// op returns the empty result against no active workspace rather than creating one.\n\t\t\tconst active = manager.active\n\t\t\tswitch (op.operation) {\n\t\t\t\tcase 'read':\n\t\t\t\t\treturn active?.read(op.path)\n\t\t\t\tcase 'list':\n\t\t\t\t\treturn (active?.files() ?? []).map((file) => ({\n\t\t\t\t\t\tpath: file.path,\n\t\t\t\t\t\tstate: file.state,\n\t\t\t\t\t\tsize: file.size,\n\t\t\t\t\t\tlines: file.lines,\n\t\t\t\t\t\tkind: isText(file.content) ? 'text' : 'binary',\n\t\t\t\t\t}))\n\t\t\t\tcase 'has':\n\t\t\t\t\treturn active?.has(op.path) ?? false\n\t\t\t\tcase 'search':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tactive?.search(op.query, {\n\t\t\t\t\t\t\t...(op.regex === undefined ? {} : { regex: op.regex }),\n\t\t\t\t\t\t\t...(op.sensitive === undefined ? {} : { sensitive: op.sensitive }),\n\t\t\t\t\t\t\t...(op.limit === undefined ? {} : { limit: op.limit }),\n\t\t\t\t\t\t}) ?? []\n\t\t\t\t\t)\n\t\t\t\tcase 'replace': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn workspace.replace(op.query, op.replacement, {\n\t\t\t\t\t\t...(op.regex === undefined ? {} : { regex: op.regex }),\n\t\t\t\t\t\t...(op.sensitive === undefined ? {} : { sensitive: op.sensitive }),\n\t\t\t\t\t\t...(op.limit === undefined ? {} : { limit: op.limit }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcase 'write': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.write(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'splice': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.write(\n\t\t\t\t\t\top.path,\n\t\t\t\t\t\top.content,\n\t\t\t\t\t\trangeOf(op.fromLine, op.fromColumn, op.toLine, op.toColumn),\n\t\t\t\t\t)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'prepend': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.prepend(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'append': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.append(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'move': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn { from: op.from, to: op.to, moved: workspace.move(op.from, op.to) }\n\t\t\t\t}\n\t\t\t\tcase 'remove': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn { path: op.path, removed: workspace.remove(op.path) }\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable sub-agent delegation tool — it resolves a live, seeded `AgentInterface`\n * from `registry` and runs it to completion for one delegated `task`.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').agentToolShape}, assembles an `AgentJobInput` (`task` seeds the\n * sub-agent's conversation as a single `user` message; `provider` / `tools` / `system` fall\n * back to the tool's own {@link import('./types.js').AgentToolOptions} defaults), rehydrates the sub-agent through\n * `registry.build`, runs it with `agent.generate()`, and returns the settled\n * `AgentResult.content` string (the sub-agent's final text). A missing / unresolvable `provider`, or a malformed call, throws a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}; a delegation that would exceed\n * {@link import('./constants.js').AGENT_TOOL_DEPTH}, or re-enter an already-delegated agent (a\n * cycle), throws a typed `DEPTH` {@link import('./errors.js').ToolboxError}, each isolated\n * by the `ToolManagerInterface` into the canonical tool result's top-level `error`.\n *\n * `AgentInterface` (`@orkestrel/agent`) exposes no teardown method — a bound sub-agent's\n * lifetime is the single `generate()` call this handler awaits; there is nothing to release\n * afterwards (unlike a store-backed resource, its state lives entirely in the resolved\n * `AgentContextInterface`, owned by the caller's registry).\n *\n * @param registry - The `AgentRegistryInterface` a delegated job resolves against (providers,\n * tools, authorities, schedulers, and the `build` rehydration seam)\n * @param options - Delegation defaults, depth/ancestry bookkeeping, and advertised overrides\n * (see {@link import('./types.js').AgentToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').AGENT_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createAgentTool } from '@src/core'\n * import { createAgentRegistry } from '@orkestrel/agent'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const registry = createAgentRegistry({ providers: { openai: myProvider } })\n * const tool = createAgentTool(registry, { provider: 'openai' })\n * const tools = createToolManager()\n * tools.add(tool) // a model can now delegate a task to a sub-agent\n * ```\n */\nexport function createAgentTool(\n\tregistry: AgentRegistryInterface,\n\toptions?: AgentToolOptions,\n): ToolInterface {\n\tconst contract = createContract(agentToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst depth = options?.depth ?? 0\n\tconst ancestry = options?.ancestry ?? []\n\treturn createTool({\n\t\tname: options?.name ?? AGENT_TOOL_NAME,\n\t\tdescription: options?.description ?? AGENT_TOOL_DESCRIPTION,\n\t\tsummary: AGENT_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed agent-delegation call', { args })\n\t\t\t}\n\t\t\tconst provider = call.provider ?? options?.provider\n\t\t\tif (provider === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'no provider resolved for the delegated agent', {\n\t\t\t\t\ttask: call.task,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (depth + 1 > AGENT_TOOL_DEPTH) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `delegation exceeds max agent depth ${AGENT_TOOL_DEPTH}`, {\n\t\t\t\t\tprovider,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: AGENT_TOOL_DEPTH,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagAgent(provider)\n\t\t\tif (ancestry.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${provider}' is already an ancestor (cycle)`, {\n\t\t\t\t\tprovider,\n\t\t\t\t\tancestry: [...ancestry],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tools = call.tools ?? options?.tools\n\t\t\tconst system = call.system ?? options?.system\n\t\t\tconst agent = registry.build({\n\t\t\t\tprovider,\n\t\t\t\tmessages: [{ role: 'user', content: call.task }],\n\t\t\t\t...(system === undefined ? {} : { system }),\n\t\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t})\n\t\t\tconst result = await agent.generate()\n\t\t\tif (options?.store !== undefined) {\n\t\t\t\tconst active = agent.context.conversations.active\n\t\t\t\tif (active !== undefined) await options.store.set(active.snapshot())\n\t\t\t}\n\t\t\treturn result.content\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable tool that returns the full `description` of another registered tool by\n * name — the counterpart to the lean `summary` the other tools in this package advertise.\n *\n * @remarks\n * `ToolManagerInterface.definitions()` (`@orkestrel/tool`) advertises `tool.summary ??\n * tool.description` — a lean one-sentence summary stands in for a tool's full teaching\n * description when `summary` is set, keeping the advertised tool list compact for a small model.\n * This tool is the on-demand expansion seam: given a registered tool's `name`, it looks the tool\n * up through `tools.tool(name)` and returns its full `description` (falling back to `summary` when a\n * tool has no `description` of its own, then a placeholder when it has neither).\n *\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').describeToolShape}, returns the plain description string on\n * success, throws a typed `TOOL` {@link import('./errors.js').ToolboxError} on a malformed call\n * or an unknown tool name.\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/tool`) whose registered tools this\n * tool can describe\n * @returns A `ToolInterface` (named {@link import('./constants.js').DESCRIBE_TOOL_NAME})\n *\n * @example\n * ```ts\n * import { createDescribeTool, createWorkflowTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tools = createToolManager()\n * tools.add(createWorkflowTool(definition, runner))\n * tools.add(createDescribeTool(tools))\n * const full = await tools.execute({ id: '1', name: 'describe', arguments: { name: 'workflow' } })\n * full.value // the workflow tool's full teaching description\n * ```\n */\nexport function createDescribeTool(tools: ToolManagerInterface): ToolInterface {\n\tconst contract = createContract(describeToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: DESCRIBE_TOOL_NAME,\n\t\tdescription: DESCRIBE_TOOL_DESCRIPTION,\n\t\tsummary: DESCRIBE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed describe call', { args })\n\t\t\t}\n\t\t\tconst tool = tools.tool(call.name)\n\t\t\tif (tool === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `unknown tool '${call.name}'`, { name: call.name })\n\t\t\t}\n\t\t\treturn tool.description ?? tool.summary ?? '<no description>'\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable form tool — the ask side of the terminal seam. It asks a multi-field form\n * and blocks until the addressed terminal answers, returning the resolved values record.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').promptToolShape}, parses the call's schema through\n * `@orkestrel/form`, constructs the live form, and passes it to `TerminalManagerInterface.ask`.\n * `from` is fixed at construction\n * ({@link import('./types.js').PromptToolOptions.from}) — never read from the model-supplied\n * args — so a model cannot spoof which terminal is asking. A form cycle rejects with\n * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`\n * {@link import('./errors.js').ToolboxError}; an expired form re-surfaces as `EXPIRE`; an\n * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal\n * and how many brokers the manager holds (`manager.count`). A schema `parseForm` refuses — an\n * unknown control, a duplicate field name, a `'select'` or `'checkbox'` field without usable\n * `choices` — throws a typed `TOOL` error up front, so a malformed schema never parks as a form\n * nobody can answer.\n *\n * @param options - The live manager, the fixed `from` identity, and advertised overrides (see\n * {@link import('./types.js').PromptToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').PROMPT_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createPromptTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createTerminalManager } from '@orkestrel/terminal'\n *\n * const manager = createTerminalManager()\n * manager.add('agent')\n * manager.add('reviewer')\n * const tool = createPromptTool({ manager, from: 'agent' })\n * const tools = createToolManager()\n * tools.add(tool) // the agent can now ask 'reviewer' and block for the answer\n * ```\n */\nexport function createPromptTool(options: PromptToolOptions): ToolInterface {\n\tconst contract = createContract(promptToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options.name ?? PROMPT_TOOL_NAME,\n\t\tdescription: options.description ?? PROMPT_TOOL_DESCRIPTION,\n\t\tsummary: PROMPT_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed ask call', { args })\n\t\t\t}\n\t\t\tconst schema = parseForm(call.schema)\n\t\t\tif (schema === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed form schema', { schema: call.schema })\n\t\t\t}\n\t\t\tfor (const field of schema.fields) {\n\t\t\t\tif (\n\t\t\t\t\t(field.control === 'select' || field.control === 'checkbox') &&\n\t\t\t\t\t!field.choices.some((choice) => choice.disabled !== true)\n\t\t\t\t) {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'TOOL',\n\t\t\t\t\t\t`${field.control} field '${field.name}' has no enabled choices`,\n\t\t\t\t\t\t{ control: field.control, field: field.name },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await options.manager.ask(options.from, call.to, createForm(schema))\n\t\t\t} catch (error) {\n\t\t\t\tif (isFormError(error) && error.code === 'ABANDONED') {\n\t\t\t\t\tthrow new ToolboxError('EXPIRE', `form to '${call.to}' expired before it was answered`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst code = inferTerminalCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tif (code === 'DEADLOCK') {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'DEADLOCK',\n\t\t\t\t\t\t`asking '${call.to}' would create a form cycle`,\n\t\t\t\t\t\tisTerminalError(error) ? error.context : { from: options.from, to: call.to },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (code === 'EXPIRE') {\n\t\t\t\t\tthrow new ToolboxError('EXPIRE', `form to '${call.to}' expired before it was answered`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (isTerminalError(error) && error.code === 'TARGET') {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown terminal '${call.to}'`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t\tcount: options.manager.count,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow new ToolboxError('TOOL', `asking '${call.to}' failed`, { to: call.to })\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable answer tool — the answer side of the terminal seam. It lists the forms\n * addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of them by id.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`\n * returns a compact list (`{ id, from, schema }`) of every form addressed to `to`.\n * `'answer'` looks the form up by `id`, narrows the supplied `values` through `@orkestrel/form`,\n * and applies it through\n * `TerminalManagerInterface.answer` — a rejected / unknown / unresolvable outcome\n * (`TerminalAnswerResult.error`) re-surfaces as a typed `ANSWER` `ToolboxError`; success returns\n * `{ answered: id }`. `to` is fixed at construction\n * ({@link import('./types.js').AnswerToolOptions.to}) — never read from the model-supplied args —\n * so a model cannot spoof which terminal it is answering for. Concurrent answerers racing on one\n * endpoint are first-write-wins — a late answer to an already-settled form returns a typed\n * `ANSWER` `ToolboxError` (surfaced as a 422 over HTTP).\n *\n * @param options - The live manager, the fixed `to` identity, and advertised overrides (see\n * {@link import('./types.js').AnswerToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').ANSWER_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createAnswerTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createTerminalManager } from '@orkestrel/terminal'\n *\n * const manager = createTerminalManager()\n * manager.add('reviewer')\n * const tool = createAnswerTool({ manager, to: 'reviewer' })\n * const tools = createToolManager()\n * tools.add(tool) // the reviewer terminal can now list/answer forms addressed to it\n * ```\n */\nexport function createAnswerTool(options: AnswerToolOptions): ToolInterface {\n\tconst contract = createContract(answerToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options.name ?? ANSWER_TOOL_NAME,\n\t\tdescription: options.description ?? ANSWER_TOOL_DESCRIPTION,\n\t\tsummary: ANSWER_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed answer call', { args })\n\t\t\t}\n\t\t\tif (call.operation === 'pending') {\n\t\t\t\treturn options.manager.pending(options.to).map((form) => ({\n\t\t\t\t\tid: form.id,\n\t\t\t\t\tfrom: form.from,\n\t\t\t\t\tschema: form.schema,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tconst form = options.manager.pending(options.to).find((entry) => entry.id === call.id)\n\t\t\tif (form === undefined) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `unknown form '${call.id}'`, {\n\t\t\t\t\tid: call.id,\n\t\t\t\t\treason: 'unknown',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (!isFormValues(call.values)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed form values', { values: call.values })\n\t\t\t}\n\t\t\tconst result = options.manager.answer(options.to, call.id, call.values)\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t'ANSWER',\n\t\t\t\t\t`failed to answer form '${call.id}': ${result.error.reason}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\treason: result.error.reason,\n\t\t\t\t\t\t...(result.error.reason === 'rejected' ? { errors: result.error.errors } : {}),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { answered: call.id }\n\t\t},\n\t})\n}\n\n// === Database definition stores\n\n/**\n * Creates the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database\n * definitions, the default store the database and relation tools persist their `DatabaseDefinition`\n * configs through.\n *\n * @returns A {@link DefinitionStoreInterface}\n *\n * @example\n * ```ts\n * import { createMemoryDefinitionStore } from '@src/core'\n *\n * const store = createMemoryDefinitionStore()\n * ```\n */\nexport function createMemoryDefinitionStore(): DefinitionStoreInterface {\n\treturn new MemoryDefinitionStore()\n}\n\n/**\n * Creates a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database`\n * layer — the driver-pluggable twin of {@link createMemoryDefinitionStore}, storing each\n * database's definition as one opaque JSON column.\n *\n * @param driver - The {@link DriverInterface} backing the table (default an in-memory driver)\n * @returns A {@link DefinitionStoreInterface}\n *\n * @example\n * ```ts\n * import { createDatabaseDefinitionStore } from '@src/core'\n *\n * const store = createDatabaseDefinitionStore() // in-memory by default\n * ```\n */\nexport function createDatabaseDefinitionStore(\n\tdriver: DriverInterface = createMemoryDriver(),\n): DefinitionStoreInterface {\n\t// The definition is stored as one opaque JSON column (`rawShape`), so the row infers flat —\n\t// `{ id: string; definition: unknown }` = DatabaseDefinitionRow.\n\tconst columns = { id: stringShape(), definition: rawShape({}) }\n\tconst database = createDatabase({ driver, tables: { definitions: columns } })\n\tconst table: TableInterface<DatabaseDefinitionRow> = database.table('definitions')\n\treturn new DatabaseDefinitionStore(table)\n}\n\n// === Database tool\n\n/**\n * Builds an LLM-callable database tool — it creates, queries, and mutates `@orkestrel/database`\n * databases through one `operation`-discriminated call (matching\n * {@link createWorkspaceTool}'s single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').databaseToolShape}, dispatches to the matching operation, and\n * returns a plain result on success. A database is resolved lazily and cached for the tool's\n * lifetime — `'create'` mints one from `tables` ({@link import('./compilers.js').expandTables}) and\n * a registered `driver` key ({@link import('./types.js').DatabaseToolOptions.drivers}, default\n * `{ memory: () => createMemoryDriver() }`); any other operation addressing an uncached id falls\n * back to {@link import('./types.js').DatabaseToolOptions.store} (an unknown id throws a typed\n * `TOOL` {@link import('./errors.js').ToolboxError}). When a `store` is configured, `'create'`\n * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.\n *\n * `'records'` clamps its `query` to\n * {@link import('./types.js').DatabaseToolOptions.limit} (default\n * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) through\n * {@link import('./helpers.js').clampQuery}, reporting `truncated` when storage held more rows\n * than the cap. Every operation's `query` is normalized through\n * {@link import('./helpers.js').normalizeQuery} (defaults an omitted condition `connector` to `'and'`).\n * When {@link import('./types.js').DatabaseToolOptions.readonly} is `true`, every mutating\n * operation throws a typed `TOOL` `ToolboxError` before doing anything. A configured\n * {@link import('./types.js').DatabaseToolOptions.timeout} is passed as a fresh\n * `AbortSignal.timeout(timeout)` only to table operations whose current database API accepts\n * operation options (`records`, `count`, `aggregate`, `add`, `set`, `update`, and `remove`). It is\n * not an outer deadline for resolution, construction, schema inspection, `get`, or `close`. A typed `@orkestrel/database`\n * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `ToolboxError` carrying the\n * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`\n * ({@link import('./helpers.js').inferDatabaseCode}); an `ToolboxError` thrown by this tool's own\n * guards passes through unwrapped.\n *\n * A lazily re-minted database over the default in-memory driver yields an empty database — only\n * the {@link import('./types.js').DatabaseDefinition} schema persists in `store`, never rows;\n * durable rows need a persistent driver factory registered in\n * {@link import('./types.js').DatabaseToolOptions.drivers}. `'destroy'` closes whatever handle is\n * cached for the id, including an embedder-supplied\n * {@link import('./types.js').DatabaseToolOptions.databases} handle — the embedder relinquishes\n * that handle's lifecycle to this tool for any id it wires in. This tool assumes the\n * single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent calls\n * against one id are not serialized by this tool. `'get'` is uncapped by\n * {@link import('./types.js').DatabaseToolOptions.limit} (bounded only by the caller's `key` array\n * size), unlike `'records'` / `'find'` / `'links'`.\n *\n * @param options - The tool's configuration (see {@link import('./types.js').DatabaseToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').DATABASE_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createDatabaseTool } from '@src/core'\n *\n * const tool = createDatabaseTool()\n * await tool.execute(\n * \t{\n * \t\toperation: 'create',\n * \t\tid: 'shop',\n * \t\ttables: { products: { columns: { name: 'string', price: 'number' } } },\n * \t},\n * \t{ signal: new AbortController().signal },\n * )\n * ```\n */\nexport function createDatabaseTool(options: DatabaseToolOptions = {}): ToolInterface {\n\tif (\n\t\toptions.timeout !== undefined &&\n\t\t(options.timeout < 0 || !isNumber(options.timeout) || !Number.isSafeInteger(options.timeout))\n\t) {\n\t\tthrow new ToolboxError('TOOL', 'database timeout must be a nonnegative safe integer', {\n\t\t\ttimeout: options.timeout,\n\t\t})\n\t}\n\tconst contract = createContract(databaseToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst handles = new Map<string, DatabaseInterface>(Object.entries(options.databases ?? {}))\n\tconst drivers = options.drivers ?? { memory: createMemoryDriver }\n\tconst generator = options.generator\n\tconst cap = options.limit ?? DATABASE_TOOL_LIMIT\n\tconst store = options.store\n\tconst resolver =\n\t\tstore === undefined\n\t\t\t? new DatabaseResolver(handles, drivers, generator)\n\t\t\t: new DatabaseResolver(handles, drivers, generator, store)\n\n\treturn createTool({\n\t\tname: options.name ?? DATABASE_TOOL_NAME,\n\t\tdescription: options.description ?? DATABASE_TOOL_DESCRIPTION,\n\t\tsummary: DATABASE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed database call', { args })\n\t\t\t}\n\t\t\tif (options.readonly === true && DATABASE_TOOL_MUTATIONS.includes(call.operation)) {\n\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t'TOOL',\n\t\t\t\t\t`operation '${call.operation}' is disabled in readonly mode`,\n\t\t\t\t\t{ operation: call.operation },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst read: Readonly<{ signal?: AbortSignal }> | undefined =\n\t\t\t\toptions.timeout === undefined ? undefined : { signal: AbortSignal.timeout(options.timeout) }\n\t\t\ttry {\n\t\t\t\tswitch (call.operation) {\n\t\t\t\t\tcase 'create': {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tresolver.has(call.id) ||\n\t\t\t\t\t\t\t(store !== undefined && (await store.get(call.id)) !== undefined)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new ToolboxError('TOOL', `database '${call.id}' already exists`, {\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst name = call.driver ?? 'memory'\n\t\t\t\t\t\tconst factory = drivers[name]\n\t\t\t\t\t\tif (factory === undefined) {\n\t\t\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown driver '${name}'`, {\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst tables = call.tables\n\t\t\t\t\t\tconst primary = call.primary\n\t\t\t\t\t\tconst indexes = call.indexes\n\t\t\t\t\t\tconst version = call.version\n\t\t\t\t\t\tconst handle = createDatabase({\n\t\t\t\t\t\t\tdriver: factory(),\n\t\t\t\t\t\t\ttables: expandTables(tables),\n\t\t\t\t\t\t\tname: call.id,\n\t\t\t\t\t\t\t...(primary === undefined ? {} : { primary }),\n\t\t\t\t\t\t\t...(indexes === undefined ? {} : { indexes }),\n\t\t\t\t\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t\t\t\t\t...(generator === undefined ? {} : { generator }),\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst definition: DatabaseDefinition = {\n\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\ttables,\n\t\t\t\t\t\t\t...(primary === undefined ? {} : { primary }),\n\t\t\t\t\t\t\t...(indexes === undefined ? {} : { indexes }),\n\t\t\t\t\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (store !== undefined) await store.set(definition)\n\t\t\t\t\t\tresolver.set(call.id, handle)\n\t\t\t\t\t\treturn { id: call.id, tables: Object.keys(tables) }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'tables': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst tables = Object.keys(handle.export()).map((name) => {\n\t\t\t\t\t\t\tconst table = handle.table(name)\n\t\t\t\t\t\t\treturn { name, primary: table.primary, columns: table.contract.schema }\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn { tables }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'get': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst rows = await table.get(keys)\n\t\t\t\t\t\treturn many ? { rows } : { row: rows[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'records': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst { query: probe, limit } = clampQuery(normalizeQuery(call.query), cap)\n\t\t\t\t\t\tconst rows = await table.records(probe, read)\n\t\t\t\t\t\tconst truncated = rows.length > limit\n\t\t\t\t\t\tconst sliced = rows.slice(0, limit)\n\t\t\t\t\t\treturn { rows: sliced, count: sliced.length, truncated, limit }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'count': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst count = await table.count(normalizeQuery(call.query), read)\n\t\t\t\t\t\treturn { count }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'aggregate': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst value = await table.aggregate(\n\t\t\t\t\t\t\tcall.function,\n\t\t\t\t\t\t\tcall.column,\n\t\t\t\t\t\t\tnormalizeQuery(call.query),\n\t\t\t\t\t\t\tread,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn { value }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'add': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.row)\n\t\t\t\t\t\tconst rows = isArray(call.row) ? call.row : [call.row]\n\t\t\t\t\t\tconst keys = await table.add(rows, read)\n\t\t\t\t\t\treturn many ? { keys } : { key: keys[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'set': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.row)\n\t\t\t\t\t\tconst rows = isArray(call.row) ? call.row : [call.row]\n\t\t\t\t\t\tconst keys = await table.set(rows, read)\n\t\t\t\t\t\treturn many ? { keys } : { key: keys[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'update': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst changes = call.changes\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst updated = await table.update(keys, changes, read)\n\t\t\t\t\t\treturn many ? { updated } : { updated: updated[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'remove': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst removed = await table.remove(keys, read)\n\t\t\t\t\t\treturn many ? { removed } : { removed: removed[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'destroy': {\n\t\t\t\t\t\tconst cached = resolver.get(call.id)\n\t\t\t\t\t\tconst persisted =\n\t\t\t\t\t\t\tstore !== undefined && cached === undefined\n\t\t\t\t\t\t\t\t? (await store.get(call.id)) !== undefined\n\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\tif (cached !== undefined) {\n\t\t\t\t\t\t\tawait cached.close()\n\t\t\t\t\t\t\tresolver.delete(call.id)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (store !== undefined) await store.delete(call.id)\n\t\t\t\t\t\treturn { id: call.id, destroyed: cached !== undefined || persisted }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (isToolboxError(error)) throw error\n\t\t\t\tconst code = inferDatabaseCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', isError(error) ? error.message : String(error), {\n\t\t\t\t\tcode,\n\t\t\t\t\toperation: call.operation,\n\t\t\t\t\tid: call.id,\n\t\t\t\t\t...('table' in call ? { table: call.table } : {}),\n\t\t\t\t})\n\t\t\t}\n\t\t},\n\t})\n}\n\n// === Relation tool\n\n/**\n * Builds an LLM-callable relation tool — it traverses and edits `@orkestrel/relation` relationships\n * through one `operation`-discriminated call (matching {@link createDatabaseTool}'s\n * single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').relationToolShape}, resolves the addressed\n * {@link import('@orkestrel/relation').RelationManagerInterface} — an explicit `manager` field\n * must match a key of {@link import('./types.js').RelationToolOptions.managers}, an omitted one\n * resolves to the sole registered manager, either miss throwing a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}\n * ({@link import('./helpers.js').resolveRelationManager}) — then resolves `model` against it\n * ({@link import('./helpers.js').resolveRelationModel}, same typed-`TOOL`-on-miss shape), and\n * dispatches to the matched operation, returning a plain result on success.\n *\n * `'load'` / `'find'` expand the call's flat dot-path `include` list into a live\n * `@orkestrel/relation` `Include` tree through {@link import('./helpers.js').expandInclude}, capped\n * at {@link import('./types.js').RelationToolOptions.depth} (default\n * {@link import('./constants.js').RELATION_TOOL_DEPTH}) — a path exceeding the cap, or carrying an\n * empty segment, throws a typed `TOOL` error. `'load'` dispatches on whether `key` is an array\n * (positional many-key form — an array key is read as many keys rather than one) or a single key.\n * `'find'` and `'links'` clamp their\n * result to {@link import('./types.js').RelationToolOptions.limit} (default\n * {@link import('./constants.js').RELATION_TOOL_LIMIT}), taken through\n * {@link import('./helpers.js').resolveLimit} — `'find'` probes one row past the effective limit to\n * report `truncated`; `'links'` (which has no upstream pagination) fetches the full linked-key\n * list and slices/truncates it the same way. `'link'` / `'unlink'` write / remove one `through` junction\n * row.\n *\n * A typed `@orkestrel/relation` failure (`RelationError`) re-surfaces as a typed `RELATION`\n * `ToolboxError` carrying the original {@link import('@orkestrel/relation').RelationErrorCode}\n * in `context.code`; a typed `@orkestrel/database` failure underneath it (`DatabaseError`)\n * re-surfaces as a typed `DATABASE` `ToolboxError`, mirroring {@link createDatabaseTool}'s error\n * mapping; an `ToolboxError` thrown by this tool's own guards (malformed args, an unknown\n * manager/model) passes through unwrapped.\n *\n * @param options - The tool's configuration (see {@link import('./types.js').RelationToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').RELATION_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createRelationTool } from '@src/core'\n *\n * const tool = createRelationTool({ managers: { shop: manager } })\n * await tool.execute(\n * \t{ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] },\n * \t{ signal: new AbortController().signal },\n * )\n * ```\n */\nexport function createRelationTool(options: RelationToolOptions): ToolInterface {\n\tconst contract = createContract(relationToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst depth = options.depth ?? RELATION_TOOL_DEPTH\n\tconst cap = options.limit ?? RELATION_TOOL_LIMIT\n\treturn createTool({\n\t\tname: options.name ?? RELATION_TOOL_NAME,\n\t\tdescription: options.description ?? RELATION_TOOL_DESCRIPTION,\n\t\tsummary: RELATION_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed relation call', { args })\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst manager = resolveRelationManager(options.managers, call.manager)\n\t\t\t\tconst model = resolveRelationModel(manager, call.model)\n\t\t\t\tswitch (call.operation) {\n\t\t\t\t\tcase 'load': {\n\t\t\t\t\t\tconst include = expandInclude(call.include, depth)\n\t\t\t\t\t\tif (isString(call.key) || isNumber(call.key)) {\n\t\t\t\t\t\t\tconst row = await model.load(call.key, include)\n\t\t\t\t\t\t\treturn { row }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst rows = await model.load(call.key, include)\n\t\t\t\t\t\treturn { rows }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'find': {\n\t\t\t\t\t\tconst include = expandInclude(call.include, depth)\n\t\t\t\t\t\tconst effective = resolveLimit(call.limit, cap)\n\t\t\t\t\t\tconst rows = await model.find(include, {\n\t\t\t\t\t\t\tlimit: effective + 1,\n\t\t\t\t\t\t\t...(call.offset === undefined ? {} : { offset: call.offset }),\n\t\t\t\t\t\t\t...(call.sort === undefined ? {} : { sort: call.sort }),\n\t\t\t\t\t\t\t...(call.direction === undefined ? {} : { direction: call.direction }),\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst truncated = rows.length > effective\n\t\t\t\t\t\tconst sliced = rows.slice(0, effective)\n\t\t\t\t\t\treturn { rows: sliced, count: sliced.length, truncated, limit: effective }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'link': {\n\t\t\t\t\t\tawait model.link(call.key, call.relation, call.target)\n\t\t\t\t\t\treturn { linked: true }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'unlink': {\n\t\t\t\t\t\tawait model.unlink(call.key, call.relation, call.target)\n\t\t\t\t\t\treturn { unlinked: true }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'links': {\n\t\t\t\t\t\tconst effective = resolveLimit(undefined, cap)\n\t\t\t\t\t\tconst keys = await model.links(call.key, call.relation)\n\t\t\t\t\t\tconst truncated = keys.length > effective\n\t\t\t\t\t\tconst sliced = keys.slice(0, effective)\n\t\t\t\t\t\treturn { keys: sliced, count: sliced.length, truncated, limit: effective }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (isToolboxError(error)) throw error\n\t\t\t\tconst relation = inferRelationCode(error)\n\t\t\t\tif (relation !== undefined) {\n\t\t\t\t\tthrow new ToolboxError('RELATION', isError(error) ? error.message : String(error), {\n\t\t\t\t\t\tcode: relation,\n\t\t\t\t\t\toperation: call.operation,\n\t\t\t\t\t\tmodel: call.model,\n\t\t\t\t\t\t...('relation' in call ? { relation: call.relation } : {}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst database = inferDatabaseCode(error)\n\t\t\t\tif (database === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', isError(error) ? error.message : String(error), {\n\t\t\t\t\tcode: database,\n\t\t\t\t\toperation: call.operation,\n\t\t\t\t})\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds a standalone LLM-callable tool that infers a JSON Schema from example values — the utility\n * half of the bridge from an existing API or database into an MCP tool (the other half,\n * {@link createEndpointTool}, wraps one concrete endpoint).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').inferToolShape} (`samples` non-empty, `format` / `enum` optional\n * booleans, `candidates` an optional array), infers a schema through `@orkestrel/contract`'s\n * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` through `schemaToObject` (mirrors\n * the tool-parameters convention every other `create*Tool` factory advertises), and returns the\n * resulting parameters record. An empty `samples` array fails `inferToolShape`'s `min: 1` bound —\n * `contract.parse` returns `undefined` and the handler throws a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}.\n *\n * When `candidates` is absent, the return is the bare parameters record — unchanged from before\n * this array existed. When `candidates` is present (any array, including empty), the handler\n * compiles a separate per-call contract from the raw inferred schema (through `@orkestrel/contract`'s\n * `schemaToShape`, not the `schemaToObject`-wrapped parameters — a bare-value sample checks a\n * bare-value candidate) and returns `{ parameters, checks }`, one check per candidate at the same\n * index. Every entry has a uniform shape — `{ index, valid, coercible }`, with `faults` added only\n * when `valid` is `false`: `valid` is the strict guard verdict (`checker.is(candidate)`), the\n * opposite of {@link createEndpointTool}'s enforcement, which coerces (`7` becomes `'7'` for a\n * string slot) — here a conformance report answers \"does this value conform as-is\": `7` against a\n * string slot is `valid: false`, full stop. `coercible` answers a separate question — \"would the\n * normalizing parse accept this value\", that is would {@link createEndpointTool}'s default enforcement\n * admit it (`checker.parse(candidate) !== undefined`) — computed for every candidate regardless of\n * `valid`; by the house parse/guard round-trip, a `valid: true` entry is\n * always also `coercible: true`. `@orkestrel/contract`'s `explain` mirrors the normalizing\n * `parse`'s leniency, not `is`'s strictness — so a strictly-invalid but coercible candidate (`7`\n * against a string slot) yields `{ valid: false, coercible: true, faults: [] }`: empty faults, because\n * the mismatch the normalizing parse would silently fix is not one `explain` reports. `faults`\n * therefore only ever populates for a non-coercible mismatch — a wrong type the parse can't coerce\n * (a boolean in a string slot), a missing required key, or an out-of-enum value — where\n * `coercible: false`. `checker.is` / `.parse` / `.explain` are all total over JSON-safe input — a\n * JSON-safe hostile candidate (a `__proto__`-carrying object, deeply nested data) reaches each of them\n * and yields a bounded, non-throwing per-candidate verdict; a non-JSON-safe candidate (for example a\n * throwing-getter `Proxy`) never reaches the checker at all — it fails the outer `args` parse\n * against {@link import('./shapers.js').inferToolShape} and rejects the whole call with the same\n * `TOOL` {@link import('./errors.js').ToolboxError} a malformed `samples`/`format`/`enum` throws,\n * with no per-candidate verdict produced.\n *\n * @param options - Advertised `name` / `description` overrides (see\n * {@link import('./types.js').InferToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').INFER_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createInferTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createInferTool()\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'infer',\n * \targuments: { samples: [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bob' }] },\n * })\n * // result.value -> { type: 'object', properties: { id: {...}, name: {...} }, ... }\n *\n * // with candidates, the result is wrapped with per-candidate verdicts\n * const checked = await tools.execute({\n * \tid: 'call-2',\n * \tname: 'infer',\n * \targuments: {\n * \t\tsamples: [{ id: 1, name: 'Ada' }],\n * \t\tcandidates: [{ id: 2, name: 'Bob' }, { id: 'x', name: 'Cy' }],\n * \t},\n * })\n * // checked.value -> { parameters: {...}, checks: [\n * // { index: 0, valid: true, coercible: true },\n * // { index: 1, valid: false, coercible: false, faults: [...] },\n * // ] }\n * ```\n */\nexport function createInferTool(options?: InferToolOptions): ToolInterface {\n\tconst contract = createContract(inferToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options?.name ?? INFER_TOOL_NAME,\n\t\tdescription: options?.description ?? INFER_TOOL_DESCRIPTION,\n\t\tsummary: INFER_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst parsed = contract.parse(args)\n\t\t\tif (parsed === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed infer arguments', { args })\n\t\t\t}\n\t\t\tconst schema = samplesToSchema(parsed.samples, {\n\t\t\t\tformat: parsed.format ?? false,\n\t\t\t\tenum: parsed.enum ?? false,\n\t\t\t})\n\t\t\tconst result = schemaToParameters(schemaToObject(schema))\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'could not infer a schema', { args })\n\t\t\t}\n\t\t\tif (parsed.candidates === undefined) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t\tconst checker = createContract(schemaToShape(schema))\n\t\t\tconst checks = parsed.candidates.map((candidate, index) => {\n\t\t\t\tconst valid = checker.is(candidate)\n\t\t\t\tconst coercible = checker.parse(candidate) !== undefined\n\t\t\t\treturn valid\n\t\t\t\t\t? { index, valid, coercible }\n\t\t\t\t\t: { index, valid, coercible, faults: checker.explain(candidate) }\n\t\t\t})\n\t\t\treturn { parameters: result, checks }\n\t\t},\n\t})\n}\n\n/**\n * Wraps one concrete endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable\n * `ToolInterface` — the endpoint half of the bridge from an existing API or database into an MCP\n * tool (the other half, {@link createInferTool}, is a standalone inference utility).\n *\n * @remarks\n * `parameters` is inferred once at construction from `definition.samples` through\n * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s\n * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` through `schemaToObject` —\n * the same object-rooted schema is both the advertised `parameters` and, by default\n * ({@link import('./types.js').EndpointToolOptions.validate} `true`), the enforced contract:\n * `@orkestrel/contract`'s `schemaToShape` compiles it once (through `createContract`) into a\n * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.execute` — a\n * normalizing parse, not a strict type check: a scalar is coerced to its inferred type where the\n * house parsers coerce (a number to/from a numeric string, a boolean from `'1'`/`'0'`/`'true'`/\n * `'false'`/`1`/`0`), so `definition.execute` receives the coerced value (for example `7` sent for a\n * string slot arrives as `'7'`), not the raw call value. A call whose `args` fails to parse into\n * a record — a required key missing, or a value not coercible to its slot's type — throws a\n * typed `TOOL` {@link import('./errors.js').ToolboxError} carrying the compiled contract's\n * structured `explain` faults, and `definition.execute` is never called. `format` annotations are\n * never asserted, and a key outside the closed inferred schema is silently dropped rather than\n * rejected (see {@link import('./types.js').EndpointToolOptions.validate}). With\n * `validate: false`, the tool's `execute` passes through the model-supplied `args` to\n * `definition.execute` without re-validation — the raw-passthrough opt-out. The execution context\n * the tool's `execute` receives reaches `definition.execute` unchanged whichever way `args` are\n * handled, so a handler that reads `context.signal` observes the caller's cancellation. Either way,\n * the definition's return flows back as the tool call's plain result; a throw propagates uncaught,\n * isolated by the `ToolManagerInterface` (`@orkestrel/tool`) into the canonical error envelope\n * — never caught or re-wrapped here.\n *\n * @param definition - The endpoint's identity, non-empty samples, and local handler (see\n * {@link import('./types.js').EndpointDefinition})\n * @param options - Construction-time inference tuning and the validate opt-out (see\n * {@link import('./types.js').EndpointToolOptions})\n * @returns A `ToolInterface` named `definition.name`\n *\n * @example\n * ```ts\n * import { createEndpointTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createEndpointTool({\n * \tname: 'lookupUser',\n * \tdescription: 'Look up a user by id.',\n * \tsamples: [{ id: '1', name: 'Ada' }, { id: '2', name: 'Bob' }],\n * \texecute: (args) => ({ id: args.id, name: 'Ada' }),\n * })\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * // conforming args (all required keys present) parse and reach the definition's `execute`\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'lookupUser',\n * \targuments: { id: '1', name: 'Ada' },\n * })\n * // result.value -> { id: '1', name: 'Ada' }\n *\n * // a nonconforming call (id is not coercible to the required string) is rejected before\n * // the definition's `execute` runs\n * const rejected = await tools.execute({\n * \tid: 'call-2',\n * \tname: 'lookupUser',\n * \targuments: { id: true, name: 'Ada' },\n * })\n * // rejected.error -> the TOOL ToolboxError message\n * ```\n */\nexport function createEndpointTool(\n\tdefinition: EndpointDefinition,\n\toptions?: EndpointToolOptions,\n): ToolInterface {\n\tif (definition.samples.length === 0) {\n\t\tthrow new ToolboxError('TOOL', 'endpoint requires at least one sample', {\n\t\t\tname: definition.name,\n\t\t})\n\t}\n\tconst objectSchema = schemaToObject(\n\t\tsamplesToSchema(definition.samples, {\n\t\t\tformat: options?.format ?? false,\n\t\t\tenum: options?.enum ?? false,\n\t\t}),\n\t)\n\tconst parameters = schemaToParameters(objectSchema)\n\tconst validate = options?.validate ?? true\n\tif (!validate) {\n\t\treturn createTool({\n\t\t\tname: definition.name,\n\t\t\tdescription: definition.description,\n\t\t\t...(parameters === undefined ? {} : { parameters }),\n\t\t\texecute(args, context) {\n\t\t\t\treturn definition.execute(args, context)\n\t\t\t},\n\t\t})\n\t}\n\tconst contract = createContract(schemaToShape(objectSchema))\n\treturn createTool({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\texecute(args, context) {\n\t\t\tconst parsed = contract.parse(args)\n\t\t\tif (parsed === undefined || !isRecord(parsed)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed endpoint call arguments', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tfaults: contract.explain(args),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn definition.execute(parsed, context)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,IAAa,kBAAkB;;;;;;;;;;;;;AAc/B,IAAa,mBAAmB;;;;;;;;;;;;AAahC,IAAa,qBACZ;;;;;AAMD,IAAa,yBAAyB;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,KAAK,UAAU,EACd,MAAM,uDACP,CAAC;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;AAYX,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,qBAAqB;;;;;;;;;;;;AAalC,IAAa,6BAA4C,OAAO,OAAO;CACtE,MAAM;CACN,OAAO,OAAO,OAAO,CAAC,OAAO,OAAO,EAAE,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GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,QAAQ,MAAM,SAAS;GACtB,OAAO,WAAW,QAAQ,MAAM,OAAO;EACxC;CACD,CAAC;CAEF,MAAM,WAAW,eAAe,cAAc,YAAY,CAAC;CAC3D,OAAO,WAAW;EACjB,MAAM,WAAW;EACjB,aAAa,WAAW;EACxB,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,QAAQ,MAAM,SAAS;GACtB,MAAM,SAAS,SAAS,MAAM,IAAI;GAClC,IAAI,WAAW,KAAA,KAAa,CAAC,SAAS,MAAM,GAC3C,MAAM,IAAI,aAAa,QAAQ,qCAAqC;IACnE,MAAM,WAAW;IACjB,QAAQ,SAAS,QAAQ,IAAI;GAC9B,CAAC;GAEF,OAAO,WAAW,QAAQ,QAAQ,OAAO;EAC1C;CACD,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/shapers.ts","../../../src/core/helpers.ts","../../../src/core/compilers.ts","../../../src/core/stores/MemoryDefinitionStore.ts","../../../src/core/stores/DatabaseDefinitionStore.ts","../../../src/core/databases/DatabaseResolver.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { WorkflowDefinition } from '@orkestrel/workflow'\nimport type { WorkflowSteps, WorkspaceOperation } from './types.js'\n\n// Toolbox constants — UPPER_SNAKE, `Object.freeze`d, every member exported.\n// Toolbox owns the workflow tool's authoring text/examples/depth bound and the workspace tool's\n// name/description. The current workflow text describes Toolbox's authoring layer over\n// `@orkestrel/workflow`'s named-function and runner-owned persistence APIs; the workspace text\n// describes the editing surface Toolbox composes over `@orkestrel/workspace`.\n\n/**\n * Holds the name {@link import('./factories.js').createAgentTool} advertises by default, `'agent'`\n * — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const AGENT_TOOL_NAME = 'agent'\n\n/**\n * Holds the maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may\n * reach, `8` — the bound {@link import('./factories.js').createAgentTool}'s depth/cycle guard\n * enforces.\n *\n * @remarks\n * Deliberately a separate constant from {@link MAX_WORKFLOW_CHAIN} (rather than the guards\n * sharing one reference): they bound different chains (workflow nesting against agent\n * delegation) that happen to share a value today, and keeping this bound decoupled means a\n * future change to one never silently shifts the other. Same numeric value by convention, not\n * by shared reference.\n */\nexport const AGENT_TOOL_DEPTH = 8\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createAgentTool} advertises in place of\n * {@link AGENT_TOOL_DESCRIPTION} — one sentence offering sub-agent delegation and pointing at\n * `describe` for the optional overrides.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const AGENT_TOOL_SUMMARY =\n\t\"Delegate a task to a sub-agent and return its result; each call runs one sub-agent turn to completion. Call describe('agent') for the optional provider/tools/system overrides.\"\n\n/**\n * Holds the description {@link import('./factories.js').createAgentTool} advertises — a short guide\n * covering the required task and optional provider, tools, and system overrides.\n */\nexport const AGENT_TOOL_DESCRIPTION = [\n\t'Delegate a task to a sub-agent and return its result. Every call runs ONE sub-agent turn to completion.',\n\t'',\n\t'Required:',\n\t' task - the instructions the sub-agent carries out.',\n\t'Optional overrides (default to the values this tool was configured with):',\n\t' provider - the registry key of the model/provider the sub-agent runs against.',\n\t' tools - registry keys of the tools loaded into the sub-agent (replaces the default list, not merged).',\n\t\" system - a system prompt seeding the sub-agent's context (replaces the default).\",\n\t'Example:',\n\tJSON.stringify({\n\t\ttask: 'Summarize the attached notes in three bullet points.',\n\t}),\n].join('\\n')\n\n/**\n * Holds the maximum nesting depth a workflow → agent → workflow chain may reach, `8` — the bound\n * {@link import('./factories.js').createAgentFunction} and\n * {@link import('./factories.js').createWorkflowTool}'s depth/cycle guards enforce.\n *\n * @remarks\n * Depth is zero-based and counts workflow tags after the root: the root plus eight nested\n * workflows is allowed, while a ninth nested workflow is rejected with this package's typed\n * `DEPTH` `ToolboxError`.\n */\nexport const MAX_WORKFLOW_CHAIN = 8\n\n/**\n * Holds the name {@link import('./factories.js').createWorkflowTool} advertises by default,\n * `'workflow'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under, and the name {@link import('./factories.js').createAgentFunction} binds the\n * depth/cycle-aware workflow tool under onto a wrapped agent's `context.tools`.\n *\n * @remarks\n * The propagation seam's well-known key: when\n * `createAgentFunction`'s `runner` option is supplied, it adds a `createWorkflowTool`-built tool\n * under this name to the agent's `context.tools`, so it can author and run a nested workflow\n * (bounded by {@link MAX_WORKFLOW_CHAIN}).\n */\nexport const WORKFLOW_TOOL_NAME = 'workflow'\n\n/**\n * Holds a complete flat authoring example — the primary way a small model authors a workflow\n * through {@link import('./factories.js').createWorkflowTool}: `{ name, steps: [{ name }] }`.\n *\n * @remarks\n * Each step becomes a one-task phase, in\n * order; a step's `name` is a registered behavior name (not a label) — the registry key its\n * task's `behavior` resolves against. The tool expands this\n * ({@link import('./helpers.js').expandSteps}) into a valid `WorkflowDefinition`\n * (`@orkestrel/workflow`). It is embedded verbatim in {@link WORKFLOW_TOOL_DESCRIPTION}.\n */\nexport const WORKFLOW_TOOL_FLAT_EXAMPLE: WorkflowSteps = Object.freeze({\n\tname: 'release',\n\tsteps: Object.freeze([Object.freeze({ name: 'compile' }), Object.freeze({ name: 'publish' })]),\n})\n\n/**\n * Holds a minimal nested authoring example — the advanced escape-hatch form a model can use instead\n * of the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).\n *\n * @remarks\n * The full nested form, documented in\n * {@link WORKFLOW_TOOL_DESCRIPTION} as the advanced alternative. It is embedded verbatim.\n */\nexport const WORKFLOW_TOOL_NESTED_EXAMPLE: WorkflowDefinition = Object.freeze({\n\tid: 'release',\n\tname: 'Release',\n\tphases: Object.freeze([\n\t\tObject.freeze({\n\t\t\tid: 'build',\n\t\t\tname: 'Build',\n\t\t\ttasks: Object.freeze([\n\t\t\t\tObject.freeze({\n\t\t\t\t\tid: 'compile',\n\t\t\t\t\tname: 'Compile',\n\t\t\t\t\tbehavior: 'compile',\n\t\t\t\t}),\n\t\t\t]),\n\t\t}),\n\t]),\n})\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createWorkflowTool} advertises in place of\n * {@link WORKFLOW_TOOL_DESCRIPTION} — one sentence offering multi-phase authoring and pointing at\n * `describe` for the authoring schema and its examples.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const WORKFLOW_TOOL_SUMMARY =\n\t\"Author and run a multi-phase workflow in one call — phases run in sequence, tasks within a phase run concurrently. Call describe('workflow') for the full authoring schema and examples.\"\n\n/**\n * Holds the description {@link import('./factories.js').createWorkflowTool} advertises — the flat\n * authoring form, its worked example, and the advanced nested definition form.\n */\nexport const WORKFLOW_TOOL_DESCRIPTION = [\n\t'Author and run a workflow (phases run sequentially, the tasks within a phase run concurrently) in one call.',\n\t'',\n\t'SIMPLEST way — a flat list of steps. Each step runs one registered behavior; steps run one after another:',\n\t' { \"name\": \"<workflow name>\", \"steps\": [ { \"name\": \"<registered name>\" }, ... ] }',\n\t'- a step\\'s \"name\" is a REGISTERED behavior name (a registry key), NOT a human label.',\n\t'- every step name must exist in the host-supplied functions registry; an unknown name is rejected.',\n\t'- the top-level \"name\" is optional; when present it is also the workflow persistence id. Other ids are filled in for you.',\n\t'Example:',\n\tJSON.stringify(WORKFLOW_TOOL_FLAT_EXAMPLE),\n\t'',\n\t'ADVANCED — the full nested form, for multi-task phases or explicit ids. A workflow has phases; a phase has tasks; a task may have a \"behavior\" (a registered behavior name); omitting it creates a JSON-null no-op:',\n\tJSON.stringify(WORKFLOW_TOOL_NESTED_EXAMPLE),\n\t'In the nested form you may omit any \"id\"/\"name\" and they are filled in positionally; a provided one is kept.',\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createWorkspaceTool} advertises by default,\n * `'workspace'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`)\n * registers under.\n */\nexport const WORKSPACE_TOOL_NAME = 'workspace'\n\n/**\n * Holds a valid {@link import('./types.js').WorkspaceOperation} object — the canonical example\n * embedded verbatim in {@link WORKSPACE_TOOL_DESCRIPTION}.\n *\n * @remarks\n * A `'write'` op (the most common authoring\n * action): create or overwrite `notes.txt` with `hello`. Frozen so it cannot be mutated in\n * place.\n */\nexport const WORKSPACE_TOOL_EXAMPLE: WorkspaceOperation = Object.freeze({\n\toperation: 'write',\n\tpath: 'notes.txt',\n\tcontent: 'hello',\n})\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createWorkspaceTool} advertises in place of\n * {@link WORKSPACE_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed file editing and\n * pointing at `describe` for the operation list and its fields.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const WORKSPACE_TOOL_SUMMARY =\n\t\"Read and edit files in a workspace — one operation per call (read, write, list, search, replace, splice, move, remove, plus workspace switching), chosen by the 'operation' field. Call describe('workspace') for the full operation list and fields.\"\n\n/**\n * Holds the description {@link import('./factories.js').createWorkspaceTool} advertises — the\n * operation-keyed workspace protocol, all supported operations, and worked examples.\n *\n * @remarks\n * Mirrors {@link WORKFLOW_TOOL_DESCRIPTION}'s teaching style and embeds\n * {@link WORKSPACE_TOOL_EXAMPLE} verbatim.\n */\nexport const WORKSPACE_TOOL_DESCRIPTION = [\n\t'Read and edit files in a workspace. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'All file operations act on the ACTIVE workspace; use \"workspaces\" then \"switch\" to move between workspaces.',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- read { \"operation\": \"read\", \"path\": \"<file>\" } — return the file\\'s text.',\n\t'- list { \"operation\": \"list\" } — list every file in the active workspace (path, state, size, lines, kind).',\n\t'- has { \"operation\": \"has\", \"path\": \"<file>\" } — whether the file exists.',\n\t'- search { \"operation\": \"search\", \"query\": \"<text>\", \"regex\"?: bool, \"sensitive\"?: bool, \"limit\"?: int } — find lines matching the query across all files.',\n\t'- replace { \"operation\": \"replace\", \"query\": \"<text>\", \"replacement\": \"<text>\", \"regex\"?: bool, \"sensitive\"?: bool, \"limit\"?: int } — replace matches across all files.',\n\t'- write { \"operation\": \"write\", \"path\": \"<file>\", \"content\": \"<text>\" } — create or overwrite the whole file.',\n\t'- splice { \"operation\": \"splice\", \"path\": \"<file>\", \"content\": \"<text>\", \"fromLine\": int, \"fromColumn\": int, \"toLine\": int, \"toColumn\": int } — replace a 1-based range (from inclusive, to exclusive) with content.',\n\t'- prepend { \"operation\": \"prepend\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the start of the file.',\n\t'- append { \"operation\": \"append\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the end of the file.',\n\t'- move { \"operation\": \"move\", \"from\": \"<file>\", \"to\": \"<file>\" } — rename / move a file.',\n\t'- remove { \"operation\": \"remove\", \"path\": \"<file>\" } — delete a file.',\n\t'- workspaces { \"operation\": \"workspaces\" } — list the workspaces you can switch between (each id, file count, active).',\n\t'- switch { \"operation\": \"switch\", \"id\": \"<id>\" } — make the workspace with that id active (ids come from \"workspaces\").',\n\t'',\n\t'Notes: lines and columns are 1-based (column 1 is the first character). \"regex\" defaults to false (a literal substring), \"sensitive\" defaults to true (case-sensitive). \"search\"/\"replace\"/\"splice\" act only on text files. Editing with no active workspace auto-creates one.',\n\t'',\n\t'Example — write a file:',\n\tJSON.stringify(WORKSPACE_TOOL_EXAMPLE),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createDescribeTool} advertises by default,\n * `'describe'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n *\n * @remarks\n * Pairs with the lean {@link AGENT_TOOL_SUMMARY} / {@link WORKFLOW_TOOL_SUMMARY} /\n * {@link WORKSPACE_TOOL_SUMMARY} — a model that reads only the\n * advertised summary can call `describe` with that tool's registered name to get its full\n * teaching description back.\n */\nexport const DESCRIBE_TOOL_NAME = 'describe'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createDescribeTool}\n * advertises — this tool needs no teaching of its own, so its summary and description are both\n * short.\n */\nexport const DESCRIBE_TOOL_SUMMARY = 'Return the full description of a named registered tool.'\n\n/**\n * Holds the description {@link import('./factories.js').createDescribeTool} advertises — the\n * registered tool `name` it requires, and the full description of that tool it returns.\n *\n * @remarks\n * Deliberately short — unlike the workflow / workspace / agent tools, this one has no authoring\n * schema or multi-step protocol to teach.\n */\nexport const DESCRIBE_TOOL_DESCRIPTION =\n\t'Return the full description of a registered tool by its name. Required: name - the registered tool name (see another tool listing for available names).'\n\n/**\n * Holds the name {@link import('./factories.js').createPromptTool} advertises by default, `'ask'` —\n * the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const PROMPT_TOOL_NAME = 'ask'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createPromptTool} advertises in place of\n * {@link PROMPT_TOOL_DESCRIPTION} — one sentence offering the blocking multi-field ask and pointing\n * at `describe` for the schema.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const PROMPT_TOOL_SUMMARY =\n\t\"Ask another terminal a multi-field form and BLOCK until it answers; the call resolves with the values record. Call describe('ask') for the schema.\"\n\n/**\n * Holds the form protocol {@link import('./factories.js').createPromptTool} advertises — the\n * required `to` and `schema`, how a field declares its control and its rules, and a worked\n * example.\n */\nexport const PROMPT_TOOL_DESCRIPTION = [\n\t'Ask another terminal a multi-field form and block until it answers. This call does not return until the addressed terminal answers, or the form expires.',\n\t'',\n\t'Required:',\n\t' to - the terminal name to ask.',\n\t' schema - an @orkestrel/form schema: each field declares `control` and `name`, plus optional `label`, `rule`, `default`, and `choices`; `fields` is an ordered array and each `name` must be unique.',\n\t'The result is one values object keyed by those field names. A cycle or expired form fails with a typed error.',\n\t'Example:',\n\tJSON.stringify({\n\t\tto: 'reviewer',\n\t\tschema: {\n\t\t\tlabel: 'Release review',\n\t\t\tfields: [\n\t\t\t\t{ control: 'confirm', name: 'approved', label: 'Approve the release?' },\n\t\t\t\t{ control: 'editor', name: 'notes', label: 'Review notes' },\n\t\t\t],\n\t\t},\n\t}),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createAnswerTool} advertises by default,\n * `'answer'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const ANSWER_TOOL_NAME = 'answer'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createAnswerTool} advertises in place of\n * {@link ANSWER_TOOL_DESCRIPTION} — one sentence offering the pending listing and the answer call,\n * and pointing at `describe` for the fields each takes.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const ANSWER_TOOL_SUMMARY =\n\t\"List forms addressed to this terminal, or answer one by id with a values record. Call describe('answer') for the required fields.\"\n\n/**\n * Holds the protocol {@link import('./factories.js').createAnswerTool} advertises — the `pending`\n * and `answer` operations and the `values` record an answer supplies, each with a worked example.\n */\nexport const ANSWER_TOOL_DESCRIPTION = [\n\t'List the forms addressed to this terminal, or answer one of them by id. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'',\n\t'Operations:',\n\t'- pending { \"operation\": \"pending\" } — list every form addressed to this terminal (id, from, schema).',\n\t'- answer { \"operation\": \"answer\", \"id\": \"<form id>\", \"values\": { \"<field name>\": <field value> } } — answer every required field with the value its control accepts.',\n\t'Example — list pending forms:',\n\tJSON.stringify({ operation: 'pending' }),\n\t'Example — answer one:',\n\tJSON.stringify({ operation: 'answer', id: 'abc123', values: { approved: true, notes: 'Ready' } }),\n].join('\\n')\n\n/**\n * Holds the name {@link import('./factories.js').createDatabaseTool} advertises by default,\n * `'database'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const DATABASE_TOOL_NAME = 'database'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createDatabaseTool} advertises in place of\n * {@link DATABASE_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed database call and\n * pointing at `describe` for the operation list, the query form, and the column DSL.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const DATABASE_TOOL_SUMMARY =\n\t\"Create and query a database — one operation per call (create, tables, get, records, count, aggregate, add, set, update, remove, destroy), chosen by the 'operation' field. Call describe('database') for the full operation list, the query form, and the column DSL.\"\n\n/**\n * Holds the description {@link import('./factories.js').createDatabaseTool} advertises — a\n * multi-line guide that teaches a small model the operation list, the serialized query form, and\n * the {@link import('./types.js').TableSpec} column DSL.\n *\n * @remarks\n * The query form is deliberately serialized (never fluent) — every condition is a flat object\n * `{ column, operator, values, connector? }` where `values` is always an array, even for a\n * single-value operator (`{ column: 'age', operator: 'from', values: [18] }`), so a small model\n * never has to chain method calls or guess whether a value is scalar or a list.\n */\nexport const DATABASE_TOOL_DESCRIPTION = [\n\t'Create and query a database. Every call is ONE operation, chosen by the \"operation\" field.',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- create { \"operation\": \"create\", \"id\": \"<database id>\", \"tables\": { \"<table>\": { \"columns\": { \"<column>\": \"string\" | \"integer\" | \"number\" | \"boolean\" | { \"primitive\": \"string\", \"optional\": true } } } }, \"primary\"?: { \"<table>\": \"<column>\" }, \"indexes\"?: { \"<table>\": [[\"<column>\"]] }, \"version\"?: <number> } — define a new database.',\n\t'- tables { \"operation\": \"tables\", \"id\": \"<database id>\" } — list a database\\'s table names.',\n\t'- get { \"operation\": \"get\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — fetch one row by its primary key.',\n\t'- records { \"operation\": \"records\", \"id\": \"<database id>\", \"table\": \"<table>\", \"query\"?: <Query> } — list rows matching a query.',\n\t'- count { \"operation\": \"count\", \"id\": \"<database id>\", \"table\": \"<table>\", \"query\"?: <Query> } — count rows matching a query.',\n\t'- aggregate { \"operation\": \"aggregate\", \"id\": \"<database id>\", \"table\": \"<table>\", \"column\": \"<column>\", \"function\": \"count\" | \"sum\" | \"average\" | \"minimum\" | \"maximum\", \"query\"?: <Query> } — compute an aggregate.',\n\t'- add { \"operation\": \"add\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — insert a row (fails on a duplicate key).',\n\t'- set { \"operation\": \"set\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — upsert a row.',\n\t'- update { \"operation\": \"update\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\", \"changes\": { ... } } — patch an existing row.',\n\t'- remove { \"operation\": \"remove\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — delete a row by key.',\n\t'- destroy { \"operation\": \"destroy\", \"id\": \"<database id>\" } — drop a database entirely.',\n\t'',\n\t'Query form — SERIALIZED, never fluent. A condition is a flat object; \"values\" is ALWAYS an array, even for one value:',\n\t' { \"conditions\": [ { \"column\": \"age\", \"operator\": \"from\", \"values\": [18], \"connector\": \"and\" } ], \"order\"?: [...], \"offset\"?: 0, \"limit\"?: 100 }',\n\t' operators: equals, not, above, below, from, to, between, like, glob, starts, ends, any, none, absent, present.',\n\t' \"connector\" joins this condition to the next (\"and\" | \"or\"); omit on the last condition.',\n\t'',\n\t'Column DSL (used by \"create\" \"tables\"): a column is either a bare primitive string (\"string\" | \"integer\" | \"number\" | \"boolean\"), or { \"primitive\": \"<primitive>\", \"optional\": true } when the column may be absent from a row.',\n\t'Schema configuration is creation-time only. Evolve a schema by opening a newly configured target-version database over a versioned persistent driver; reconciliation requires paired metadata/stamp capabilities.',\n\t'Example — create a database:',\n\tJSON.stringify({\n\t\toperation: 'create',\n\t\tid: 'shop',\n\t\ttables: {\n\t\t\tproducts: {\n\t\t\t\tcolumns: {\n\t\t\t\t\tname: 'string',\n\t\t\t\t\tprice: 'number',\n\t\t\t\t\tnotes: { primitive: 'string', optional: true },\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}),\n\t'Example — query records:',\n\tJSON.stringify({\n\t\toperation: 'records',\n\t\tid: 'shop',\n\t\ttable: 'products',\n\t\tquery: { conditions: [{ column: 'price', operator: 'below', values: [50] }] },\n\t}),\n].join('\\n')\n\n/**\n * Holds the default cap on rows a `records` call returns when the caller omits `query.limit`,\n * `1000` — the database tool's default row ceiling.\n */\nexport const DATABASE_TOOL_LIMIT = 1000\n\n/** Lists the runtime-frozen database-tool mutation names disabled by `DatabaseToolOptions.readonly`. */\nexport const DATABASE_TOOL_MUTATIONS: readonly string[] = Object.freeze([\n\t'create',\n\t'add',\n\t'set',\n\t'update',\n\t'remove',\n\t'destroy',\n])\n\n/**\n * Holds the name {@link import('./factories.js').createRelationTool} advertises by default,\n * `'relation'` — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers\n * under.\n */\nexport const RELATION_TOOL_NAME = 'relation'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createRelationTool} advertises in place of\n * {@link RELATION_TOOL_DESCRIPTION} — one sentence offering the `operation`-keyed relationship\n * traversal and pointing at `describe` for the include-path syntax.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const RELATION_TOOL_SUMMARY =\n\t\"Traverse and edit relationships between database rows — one operation per call (load, find, link, unlink, links), chosen by the 'operation' field. Call describe('relation') for the include-path syntax.\"\n\n/**\n * Holds the description {@link import('./factories.js').createRelationTool} advertises — a\n * multi-line guide that teaches a small model the operation list and the flat dot-path `include`\n * syntax.\n *\n * @remarks\n * An include path is a flat dot-separated string (`'contacts.account'`), never a nested object —\n * the same small-model ergonomic lever the other tools in this package use for flat args.\n */\nexport const RELATION_TOOL_DESCRIPTION = [\n\t'Traverse and edit relationships between database rows. Every call is ONE operation, chosen by the \"operation\" field. \"manager\" is optional (omit it when only one relation manager is registered).',\n\t'',\n\t'Operations (each takes the fields listed):',\n\t'- load { \"operation\": \"load\", \"model\": \"<model>\", \"key\": \"<row key>\", \"include\"?: [\"<path>\", ...] } — fetch one (or, with an array key, several) row(s) with related rows attached.',\n\t'- find { \"operation\": \"find\", \"model\": \"<model>\", \"include\"?: [\"<path>\", ...], \"limit\"?: <n>, \"offset\"?: <n>, \"sort\"?: \"<column>\", \"direction\"?: \"ascending\"|\"descending\" } — list rows, each with related rows attached.',\n\t'- link { \"operation\": \"link\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — connect two rows through a \"through\" relation.',\n\t'- unlink { \"operation\": \"unlink\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — disconnect two rows.',\n\t'- links { \"operation\": \"links\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\" } — list every key linked to a row through a \"through\" relation.',\n\t'',\n\t'\"include\" is a FLAT dot-path array (not nested objects) — each string names a chain of relations to attach, up to the configured depth cap. Example: \"contacts.account\" attaches each row\\'s contacts, and each contact\\'s account.',\n\t'Example — load a row with two levels of relations:',\n\tJSON.stringify({ operation: 'load', model: 'orders', key: '1', include: ['contacts.account'] }),\n].join('\\n')\n\n/**\n * Holds the default cap on rows a `find` or `links` call returns when the caller omits `limit`,\n * `1000` — the relation tool's default row ceiling.\n */\nexport const RELATION_TOOL_LIMIT = 1000\n\n/**\n * Holds the default cap on how many `include` path segments deep a `load` or `find` call may\n * traverse, `3` — the relation tool's default include-depth ceiling.\n */\nexport const RELATION_TOOL_DEPTH = 3\n\n/**\n * Holds the name {@link import('./factories.js').createInferTool} advertises by default, `'infer'`\n * — the key a model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const INFER_TOOL_NAME = 'infer'\n\n/**\n * Holds the lean {@link import('@orkestrel/tool').ToolInterface.summary}\n * {@link import('./factories.js').createInferTool} advertises in place of\n * {@link INFER_TOOL_DESCRIPTION} — one sentence offering schema inference from example values and\n * pointing at `describe` for the fields it takes.\n *\n * @remarks\n * A `ToolManagerInterface.definitions()` call (`@orkestrel/tool`) advertises\n * `summary ?? description`, so this one-sentence text stands in for the full teaching description;\n * the full text stays retrievable through {@link import('./factories.js').createDescribeTool}.\n */\nexport const INFER_TOOL_SUMMARY =\n\t\"Infer a JSON Schema (as advertised tool parameters) from one or more example values. Call describe('infer') for the required fields.\"\n\n/**\n * Holds the schema-inference protocol {@link import('./factories.js').createInferTool} advertises —\n * the required `samples`, the optional `format`, `enum`, and `candidates` arguments, and a worked\n * example of the bare return and of the `candidates`-wrapped return.\n */\nexport const INFER_TOOL_DESCRIPTION = [\n\t'Infer a JSON Schema from example values, returned in the same shape a tool advertises its parameters.',\n\t'',\n\t'Required:',\n\t' samples - an array of at least one example value to infer the schema from.',\n\t'Optional:',\n\t' format - infer string formats (date-time, email, ...) from the samples. Defaults to false.',\n\t' enum - infer enum constraints from repeated literal values across the samples. Defaults to false.',\n\t' candidates - values to check against the freshly inferred schema. When present, the result',\n\t' is wrapped as { parameters, checks } instead of the bare parameters record, one',\n\t' check per candidate (same index). Every check has the uniform shape',\n\t' { index, valid, coercible, faults? }. `valid` is a STRICT verdict (no coercion)',\n\t' — for example the number 7 is NOT valid against a string slot. `coercible` answers a',\n\t' separate question: would the SAME value be accepted by an endpoint tool call,',\n\t\" whose enforcement NORMALIZES args (7 coerces to '7')? So 7 against a string slot\",\n\t' yields { valid: false, coercible: true, faults: [] } — a strict mismatch that',\n\t' normalization would silently accept, so faults is EMPTY. `faults` only ever',\n\t' populates for a non-coercible mismatch (a wrong type normalization cannot fix,',\n\t' a missing required key, an out-of-enum value); checks never throw, regardless of',\n\t' candidate shape.',\n\t'Example (no candidates):',\n\t` in: ${JSON.stringify({\n\t\tsamples: [\n\t\t\t{ id: 1, name: 'Ada' },\n\t\t\t{ id: 2, name: 'Bob' },\n\t\t],\n\t})}`,\n\t` out: ${JSON.stringify({\n\t\ttype: 'object',\n\t\tproperties: { id: { type: 'integer' }, name: { type: 'string' } },\n\t\trequired: ['id', 'name'],\n\t\tadditionalProperties: false,\n\t})}`,\n\t'Example (with candidates):',\n\t` in: ${JSON.stringify({\n\t\tsamples: [{ id: 1, name: 'Ada' }],\n\t\tcandidates: [\n\t\t\t{ id: 3, name: 'Cy' },\n\t\t\t{ id: 'x', name: 'Cy' },\n\t\t\t{ id: 1, name: 7 },\n\t\t],\n\t})}`,\n\t` out: ${JSON.stringify({\n\t\tparameters: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { id: { type: 'integer' }, name: { type: 'string' } },\n\t\t\trequired: ['id', 'name'],\n\t\t\tadditionalProperties: false,\n\t\t},\n\t\tchecks: [\n\t\t\t{ index: 0, valid: true, coercible: true },\n\t\t\t{ index: 1, valid: false, coercible: false, faults: '<structured faults>' },\n\t\t\t{ index: 2, valid: false, coercible: true, faults: [] },\n\t\t],\n\t})}`,\n].join('\\n')\n","import type { ToolboxErrorCode } from './types.js'\nimport { INTRINSICS, holds, isFunction, isObject } from '@orkestrel/contract'\n\n// Toolbox errors — one error class per domain this package mints its own error for.\n// `@orkestrel/workflow`'s `WorkflowError` and `@orkestrel/workspace`'s `WorkspaceError` already\n// cover their genuine domain failure paths (imported and thrown as-is, never duplicated here\n// under AGENTS' no-superfluous-wrappers law). Neither package error fits this package's own\n// malformed-call and resolution guards, so this package mints one typed error, `ToolboxError`,\n// mirroring `WorkflowError`'s exact shape (`code` and an optional `context`) for the same reason:\n// a thrown, machine-readable, code-bearing error after AGENTS' “narrow untrusted input with\n// guards” boundary rejects a call, never a `{ error }` return. `ToolboxError` is this package's\n// general tool-call error — not scoped to agent delegation alone — so every package-owned `TOOL`\n// misuse shares it rather than minting one error class per tool.\n\n/**\n * Represents a package-owned tool-call failure: malformed input or unresolved configuration (`TOOL`),\n * delegation depth/cycle rejection (`DEPTH`), prompt failure (`DEADLOCK` / `EXPIRE` / `ANSWER`),\n * or a translated upstream database/relation failure (`DATABASE` / `RELATION`).\n *\n * @remarks\n * Carries a machine-readable `code` (see {@link import('./types.js').ToolboxErrorCode}) and\n * an optional `context` bag for structured diagnostics. They are readable through an in-process\n * catch, including around a direct `tool.execute(args, context)` call. The `ToolManagerInterface`\n * (`@orkestrel/tool`) instead flattens every throw to the canonical tool result's top-level\n * `error` message string under AGENTS' “narrow untrusted input with guards” rule.\n *\n * @example\n * ```ts\n * import { ToolboxError, isToolboxError } from '@src/core'\n *\n * try {\n * \tthrow new ToolboxError('TOOL', 'task is required')\n * } catch (error) {\n * \tif (isToolboxError(error)) console.log(error.code) // 'TOOL'\n * }\n * ```\n */\nexport class ToolboxError extends Error {\n\treadonly code: ToolboxErrorCode\n\tdeclare readonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: ToolboxErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/toolbox.ToolboxError'), { value: this })\n\t\tthis.name = 'ToolboxError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link ToolboxError}.\n *\n * @remarks\n * Recognizes the self-brand across package copies and subclasses without requiring a name.\n * Rejects transparent proxies and validates the code and optional context.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is an {@link ToolboxError}; false otherwise\n *\n * @example\n * ```ts\n * import { isToolboxError } from '@src/core'\n *\n * try {\n * \t// ...\n * } catch (error) {\n * \tif (isToolboxError(error)) console.log(error.code)\n * }\n * ```\n */\nexport function isToolboxError(value: unknown): value is ToolboxError {\n\treturn holds(() => {\n\t\tif (\n\t\t\t!(\n\t\t\t\tvalue instanceof Error &&\n\t\t\t\tINTRINSICS.prototype(value) !== Error.prototype &&\n\t\t\t\tINTRINSICS.describe(value, Symbol.for('@orkestrel/toolbox.ToolboxError'))?.value === value\n\t\t\t)\n\t\t)\n\t\t\treturn false\n\t\tconst code = INTRINSICS.reflect.read(value, 'code')\n\t\tconst context = INTRINSICS.reflect.read(value, 'context')\n\t\treturn (\n\t\t\t(code === 'TOOL' ||\n\t\t\t\tcode === 'DEPTH' ||\n\t\t\t\tcode === 'DEADLOCK' ||\n\t\t\t\tcode === 'EXPIRE' ||\n\t\t\t\tcode === 'ANSWER' ||\n\t\t\t\tcode === 'DATABASE' ||\n\t\t\t\tcode === 'RELATION') &&\n\t\t\t(context === undefined || isObject(context) || isFunction(context))\n\t\t)\n\t})\n}\n","import type { Guard } from '@orkestrel/contract'\nimport type {\n\tAgentFunction,\n\tColumnPrimitive,\n\tColumnSpec,\n\tDatabaseDefinition,\n\tWorkflowLineage,\n} from './types.js'\nimport {\n\tattempt,\n\tisArray,\n\tisBoolean,\n\tisFiniteNumber,\n\tisFunction,\n\tisNonEmptyString,\n\tisRecord,\n\tisString,\n\tliteralOf,\n} from '@orkestrel/contract'\n\n// Toolbox guards — the total `(value: unknown) => value is T` narrows this package applies at its\n// untrusted boundaries: an authored lineage, a frozen agent adapter, the small-model column DSL,\n// and a persisted database definition read back from a store.\n\n/**\n * Narrows an unknown value to a valid alternating workflow lineage.\n *\n * @param value - The value to inspect\n * @returns True if `value` is a unique, nonempty-tagged workflow/agent chain; false otherwise\n */\nexport function isWorkflowLineage(value: unknown): value is WorkflowLineage {\n\tconst inspected = attempt(() => {\n\t\tif (!isArray(value)) return false\n\t\tconst seen = new Set<string>()\n\t\tfor (const [index, tag] of value.entries()) {\n\t\t\tif (!isString(tag)) return false\n\t\t\tconst prefix = index % 2 === 0 ? 'workflow:' : 'agent:'\n\t\t\tif (!tag.startsWith(prefix) || tag.length === prefix.length || seen.has(tag)) return false\n\t\t\tseen.add(tag)\n\t\t}\n\t\treturn true\n\t})\n\treturn inspected.success && inspected.value\n}\n\n/**\n * Narrows an unknown callable to Toolbox's frozen contextual agent adapter metadata.\n *\n * @param value - The value to inspect\n * @returns True if it is a frozen {@link AgentFunction} with a frozen valid lineage; false otherwise\n */\nexport function isAgentFunction(value: unknown): value is AgentFunction {\n\tconst inspected = attempt(() => {\n\t\tif (!isFunction(value) || !Object.isFrozen(value)) return false\n\t\tconst category = Reflect.getOwnPropertyDescriptor(value, 'category')\n\t\tconst lineage = Reflect.getOwnPropertyDescriptor(value, 'lineage')\n\t\treturn (\n\t\t\tcategory?.value === 'agent' &&\n\t\t\tlineage !== undefined &&\n\t\t\t'value' in lineage &&\n\t\t\tObject.isFrozen(lineage.value) &&\n\t\t\tisWorkflowLineage(lineage.value)\n\t\t)\n\t})\n\treturn inspected.success && inspected.value\n}\n\n/**\n * Narrows an unknown value to a {@link ColumnSpec}.\n *\n * @param value - The value to inspect\n * @returns True if `value` is a valid {@link ColumnPrimitive} shorthand or a `{ primitive, optional }` record with a valid `primitive`; false otherwise\n */\nexport function isColumnSpec(value: unknown): value is ColumnSpec {\n\tif (isColumnPrimitive(value)) return true\n\tif (!isRecord(value)) return false\n\treturn (\n\t\tisColumnPrimitive(value.primitive) &&\n\t\t(value.optional === undefined || isBoolean(value.optional))\n\t)\n}\n\n/**\n * Narrows an unknown value to a {@link ColumnPrimitive}.\n *\n * @param value - The value to inspect\n * @returns True if `value` is `'string'`, `'integer'`, `'number'`, or `'boolean'`; false otherwise\n */\nexport const isColumnPrimitive: Guard<ColumnPrimitive> = literalOf(\n\t'string',\n\t'integer',\n\t'number',\n\t'boolean',\n)\n\n/**\n * Narrows an unknown value to a {@link DatabaseDefinition} — a non-empty `id` and `driver`, a\n * `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, plus optional\n * `primary`, `indexes`, and finite `version` schema configuration. The boundary guard a\n * {@link import('./types.js').DefinitionStoreInterface} applies to an untrusted persisted blob\n * before trusting it as a definition (never an `as`).\n *\n * @param value - The value to inspect\n * @returns True if `value` is a complete {@link DatabaseDefinition}; false otherwise\n */\nexport function isDatabaseDefinition(value: unknown): value is DatabaseDefinition {\n\tif (!isRecord(value)) return false\n\tif ('keys' in value) return false\n\tif (!isNonEmptyString(value.id) || !isNonEmptyString(value.driver)) return false\n\tif (!isRecord(value.tables)) return false\n\tfor (const table of Object.values(value.tables)) {\n\t\tif (!isRecord(table) || !isRecord(table.columns)) return false\n\t\tfor (const column of Object.values(table.columns)) {\n\t\t\tif (!isColumnSpec(column)) return false\n\t\t}\n\t}\n\tif (value.primary !== undefined) {\n\t\tif (!isRecord(value.primary)) return false\n\t\tfor (const key of Object.values(value.primary)) {\n\t\t\tif (!isNonEmptyString(key)) return false\n\t\t}\n\t}\n\tif (value.indexes !== undefined) {\n\t\tif (!isRecord(value.indexes)) return false\n\t\tfor (const groups of Object.values(value.indexes)) {\n\t\t\tif (!isArray(groups)) return false\n\t\t\tfor (const group of groups) {\n\t\t\t\tif (!isArray(group) || group.length === 0) return false\n\t\t\t\tfor (const column of group) {\n\t\t\t\t\tif (!isNonEmptyString(column)) return false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (value.version !== undefined && !isFiniteNumber(value.version)) return false\n\treturn true\n}\n","import {\n\tarrayShape,\n\tbooleanShape,\n\tintegerShape,\n\tjsonShape,\n\tliteralShape,\n\tnumberShape,\n\tobjectShape,\n\toptionalShape,\n\trecordShape,\n\tstringShape,\n\tunionShape,\n} from '@orkestrel/contract'\nimport { MAX_TIMER_MS } from '@orkestrel/workflow'\n\n// === Prompt / answer shapes (createPromptTool / createAnswerTool call args)\n\n/**\n * Describes the shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` names the\n * terminal identity and `schema` carries the complete multi-field form document.\n *\n * @remarks\n * The contract first requires exact JSON. The handler then delegates schema parsing and semantic\n * validation to `@orkestrel/form`'s `parseForm`, so Toolbox does not duplicate the form schema.\n */\nexport const promptToolShape = objectShape({\n\tto: stringShape({ min: 1, description: 'The terminal identity to address the form to.' }),\n\tschema: jsonShape({\n\t\tdescription:\n\t\t\t'The @orkestrel/form schema to ask, with form metadata and one or more typed fields.',\n\t}),\n})\n\n/**\n * Describes the shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated\n * by `operation`: `'pending'` lists the forms addressed to this tool's terminal, while `'answer'`\n * resolves one by `id` with a complete `values` record.\n *\n * @remarks\n * `values` is first bounded to exact JSON. The handler then narrows it with the originating Form\n * package's `isFormValues` guard before the terminal manager applies it to the parked live form.\n */\nexport const answerToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['pending'], {\n\t\t\tdescription: 'List the forms addressed to this terminal.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['answer'], { description: 'Answer one pending form by id.' }),\n\t\tid: stringShape({ min: 1, description: 'The id of the pending form to answer.' }),\n\t\tvalues: jsonShape({ description: 'The form answers keyed by field name.' }),\n\t}),\n)\n\n// Toolbox shapes — the shape value each `create*Tool` factory (factories.ts) compiles into\n// the lockstep guard, parser, and JSON Schema outputs. `agentToolShape` must agree\n// with the hand-written `AgentToolArguments` (types.ts), which is the source of truth.\n// `workflowStepsShape` / `workflowDraftShape` are Toolbox's authoring boundary over the current\n// `@orkestrel/workflow` definition contract. `workspaceToolShape` is Toolbox's operation boundary\n// over the editing primitives now owned by `@orkestrel/workspace`.\n\n/**\n * Describes the shape of {@link import('./types.js').AgentToolArguments} —\n * {@link import('./factories.js').createAgentTool}'s advertised `parameters`.\n *\n * @remarks\n * `task` is the only required field (a non-empty string); `provider` / `tools` / `system`\n * are per-call overrides of the tool's own configured defaults.\n */\nexport const agentToolShape = objectShape({\n\ttask: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The instructions the sub-agent carries out.',\n\t}),\n\tprovider: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'Registry key of the provider to run the sub-agent against (overrides the default).',\n\t\t}),\n\t),\n\ttools: optionalShape(\n\t\tarrayShape(stringShape({ min: 1 }), {\n\t\t\tdescription:\n\t\t\t\t'Registry keys of the tools loaded into the sub-agent (replaces the default list).',\n\t\t}),\n\t),\n\tsystem: optionalShape(\n\t\tstringShape({\n\t\t\tdescription: \"A system prompt seeding the sub-agent's context (overrides the default).\",\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of {@link import('./types.js').DescribeToolArguments} —\n * {@link import('./factories.js').createDescribeTool}'s advertised `parameters`.\n *\n * @remarks\n * `name` is the only field (a non-empty string) — the registered tool name to look up.\n */\nexport const describeToolShape = objectShape({\n\tname: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The registered name of the tool whose full description to return.',\n\t}),\n})\n\n// === Workflow draft / flat-steps shapes\n\n/**\n * Describes the shape of a {@link import('./types.js').TaskDraft} — identical to a strict task\n * shape except that `id` and `name` are optional.\n */\nexport const taskDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Task id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Task name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional task description.' })),\n\tbehavior: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'The registered behavior name to invoke (a registry key, not a label); omitted completes with JSON null.',\n\t\t}),\n\t),\n\tretries: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tdescription:\n\t\t\t\t'Extra attempts after the first on failure; overrides the phase default. Omitted means none.',\n\t\t}),\n\t),\n\ttimeout: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 0,\n\t\t\tmax: MAX_TIMER_MS,\n\t\t\tdescription:\n\t\t\t\t'Persisted per-attempt deadline in milliseconds (0 disables it); omitted means no deadline.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of a phase in a draft workflow — identical to a strict phase shape except\n * that `id` and `name` are optional and each task takes {@link taskDraftShape}.\n */\nexport const phaseDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Phase id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Phase name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional phase description.' })),\n\ttasks: arrayShape(taskDraftShape, { description: 'The phase tasks; they run CONCURRENTLY.' }),\n\tconcurrency: optionalShape(\n\t\tintegerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'Max tasks in flight at once (a resource throttle); omitted means unbounded.',\n\t\t}),\n\t),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription: 'Per-phase failure-policy override; omitted inherits the workflow bail.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of a draft workflow — identical to a strict workflow shape except that `id`\n * and `name` are optional at the workflow, phase, and task levels, so a small model can omit every\n * identity string and let the tool synthesize them positionally.\n *\n * @remarks\n * The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.\n * `behavior` stays optional like the strict form; omission is the deliberate JSON `null` no-op. A\n * provided `id` / `name` still has `minLength: 1` (so\n * an explicitly-empty `id: ''` is rejected, not auto-filled). After\n * {@link import('./helpers.js').completeDraft} fills the missing ids/names, the result is\n * validated against the strict `createWorkflowContract` (`@orkestrel/workflow`) gate before\n * running.\n */\nexport const workflowDraftShape = objectShape({\n\tid: optionalShape(stringShape({ min: 1, description: 'Workflow id; auto-filled when omitted.' })),\n\tname: optionalShape(\n\t\tstringShape({ min: 1, description: 'Workflow name; defaults to the id when omitted.' }),\n\t),\n\tdescription: optionalShape(stringShape({ description: 'Optional workflow description.' })),\n\tphases: arrayShape(phaseDraftShape, {\n\t\tdescription: 'The workflow phases; they run SEQUENTIALLY, in order.',\n\t}),\n\tbail: optionalShape(\n\t\tliteralShape([true, false], {\n\t\t\tdescription:\n\t\t\t\t'Failure policy: false (default) continues gracefully, true halts on the first failure.',\n\t\t}),\n\t),\n})\n\n/**\n * Describes the shape of one flat step — `{ name }` — the building block of\n * {@link workflowStepsShape}.\n *\n * @remarks\n * `name` is the registered behavior name the step runs (it becomes the task's `behavior`). The tool\n * expands each step into a one-task phase, in order ({@link import('./helpers.js').expandSteps}).\n */\nexport const stepShape = objectShape({\n\tname: stringShape({\n\t\tmin: 1,\n\t\tdescription: 'The registered behavior name this step runs (becomes the task behavior).',\n\t}),\n})\n\n/**\n * Describes the flat authoring shape {@link import('./factories.js').createWorkflowTool} advertises\n * as its `parameters` — the simplest surface a small model can fill:\n * `{ name?, steps: [{ name }] }`.\n *\n * @remarks\n * A deliberately-reduced surface: a flat ordered list of steps, each a `{ name }`. The tool\n * expands it ({@link import('./helpers.js').expandSteps}) into a full\n * {@link import('./types.js').WorkflowDefinition} — one one-task phase per step, in order —\n * then validates against the strict `createWorkflowContract` (`@orkestrel/workflow`) gate. The\n * full nested form is still accepted by the tool (it branches on the args' shape) and is\n * documented as the advanced escape-hatch in the tool's description — but this is what\n * `parameters` advertises.\n */\nexport const workflowStepsShape = objectShape({\n\tname: optionalShape(stringShape({ min: 1, description: 'Optional workflow name.' })),\n\tsteps: arrayShape(stepShape, {\n\t\tdescription: 'The ordered steps to run, one after another (each becomes a one-task phase).',\n\t}),\n})\n\n// === Workspace operation shape\n\n/**\n * Describes the shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union\n * over the workspace edit, read, and navigation operations, discriminated by the `operation`\n * literal (never a bare `kind`). Each variant leads with its `operation`\n * discriminant then its flat fields, every field through `stringShape` / `optionalShape` /\n * `integerShape({ min: 1 })` / `booleanShape`, each carrying a strong field-level `description`.\n *\n * @remarks\n * The union compiles to an `anyOf` JSON Schema, a `unionOf` guard, and a first-match parser\n * automatically ({@link import('./factories.js').createWorkspaceTool} types the result to the\n * hand-written {@link import('./types.js').WorkspaceOperation}). `limit` and the `'splice'`\n * caret components are positive integers (`integerShape({ min: 1 })`); `regex` / `sensitive`\n * are `optionalShape(booleanShape(...))`. The registry arms — `workspaces` (list the\n * workspaces the model can move between) and `switch` (re-point the active one by `id`) — let a\n * model discover then choose which workspace the edit / read arms target.\n */\nexport const workspaceToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['read'], { description: \"Read a whole text file's text by path.\" }),\n\t\tpath: stringShape({ description: 'The path of the file to read.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['list'], { description: 'List every file in the workspace.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['has'], { description: 'Check whether a file exists at the path.' }),\n\t\tpath: stringShape({ description: 'The path to check for.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['search'], {\n\t\t\tdescription: 'Search every text file for a query, returning each hit.',\n\t\t}),\n\t\tquery: stringShape({ description: 'The text (or regular-expression source) to search for.' }),\n\t\tregex: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription:\n\t\t\t\t\t'Treat the query as a regular expression. Defaults to false (a literal substring).',\n\t\t\t}),\n\t\t),\n\t\tsensitive: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription: 'Match case-sensitively. Defaults to true (set false for case-insensitive).',\n\t\t\t}),\n\t\t),\n\t\tlimit: optionalShape(\n\t\t\tintegerShape({\n\t\t\t\tmin: 1,\n\t\t\t\tdescription: 'Stop after this many matches across all files. Omitted means unlimited.',\n\t\t\t}),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['replace'], {\n\t\t\tdescription: 'Replace a query with a replacement across every text file.',\n\t\t}),\n\t\tquery: stringShape({ description: 'The text (or regular-expression source) to replace.' }),\n\t\treplacement: stringShape({ description: 'The text to substitute for each match.' }),\n\t\tregex: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription:\n\t\t\t\t\t'Treat the query as a regular expression. Defaults to false (a literal substring).',\n\t\t\t}),\n\t\t),\n\t\tsensitive: optionalShape(\n\t\t\tbooleanShape({\n\t\t\t\tdescription: 'Match case-sensitively. Defaults to true (set false for case-insensitive).',\n\t\t\t}),\n\t\t),\n\t\tlimit: optionalShape(\n\t\t\tintegerShape({\n\t\t\t\tmin: 1,\n\t\t\t\tdescription: 'Stop after this many replacements across all files. Omitted means unlimited.',\n\t\t\t}),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['write'], {\n\t\t\tdescription: 'Create or overwrite a whole file with content.',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to write.' }),\n\t\tcontent: stringShape({ description: 'The full new contents of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['splice'], {\n\t\t\tdescription:\n\t\t\t\t'Replace a 1-based range of an existing text file (from inclusive, to exclusive) with content.',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the text file to edit.' }),\n\t\tcontent: stringShape({ description: 'The text to splice in place of the range.' }),\n\t\tfromLine: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'The 1-based start line of the range (inclusive).',\n\t\t}),\n\t\tfromColumn: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription:\n\t\t\t\t'The 1-based start column of the range (inclusive; column 1 is the first character).',\n\t\t}),\n\t\ttoLine: integerShape({ min: 1, description: 'The 1-based end line of the range (exclusive).' }),\n\t\ttoColumn: integerShape({\n\t\t\tmin: 1,\n\t\t\tdescription: 'The 1-based end column of the range (exclusive).',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['prepend'], {\n\t\t\tdescription: 'Add content to the start of a file (creating it when absent).',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to prepend to.' }),\n\t\tcontent: stringShape({ description: 'The text to add at the start of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['append'], {\n\t\t\tdescription: 'Add content to the end of a file (creating it when absent).',\n\t\t}),\n\t\tpath: stringShape({ description: 'The path of the file to append to.' }),\n\t\tcontent: stringShape({ description: 'The text to add at the end of the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['move'], {\n\t\t\tdescription: 'Rename or move a file (overwriting an occupied target).',\n\t\t}),\n\t\tfrom: stringShape({ description: 'The current path of the file.' }),\n\t\tto: stringShape({ description: 'The new path for the file.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['remove'], { description: 'Delete a file from the workspace.' }),\n\t\tpath: stringShape({ description: 'The path of the file to remove.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['workspaces'], {\n\t\t\tdescription:\n\t\t\t\t'List the workspaces you can move between (each id, file count, and whether it is active), so you can pick an id to switch to.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['switch'], {\n\t\t\tdescription:\n\t\t\t\t'Switch the active workspace to the one with this id (get ids from the \"workspaces\" operation). Edit and read operations then target it.',\n\t\t}),\n\t\tid: stringShape({\n\t\t\tdescription: 'The id of the workspace to make active (from the \"workspaces\" listing).',\n\t\t}),\n\t}),\n)\n\n// === Database tool shape\n\n/** Describes a {@link import('./types.js').ColumnPrimitive} literal — the leaf {@link columnSpecShape} wraps. */\nexport const columnPrimitiveShape = literalShape(['string', 'integer', 'number', 'boolean'], {\n\tdescription: 'A column primitive: \"string\" | \"integer\" | \"number\" | \"boolean\".',\n})\n\n/** Describes a {@link import('./types.js').ColumnSpec} — a bare {@link columnPrimitiveShape}, or `{ primitive, optional }`. */\nexport const columnSpecShape = unionShape(\n\tcolumnPrimitiveShape,\n\tobjectShape({\n\t\tprimitive: columnPrimitiveShape,\n\t\toptional: optionalShape(\n\t\t\tbooleanShape({ description: 'Whether the column may be absent from a row.' }),\n\t\t),\n\t}),\n)\n\n/** Describes a {@link import('./types.js').TableSpec} — table name to `{ columns }`, each column a {@link columnSpecShape}. */\nexport const tableSpecShape = recordShape(\n\tobjectShape({\n\t\tcolumns: recordShape(columnSpecShape, {\n\t\t\tdescription: 'Column name to its primitive or its { primitive, optional } spec.',\n\t\t}),\n\t}),\n\t{ description: 'Table name to its column layout.' },\n)\n\n/**\n * Describes one key value for the database tool and the relation tool — a string or number; the\n * array form (multiple keys, positional) resolves first, so an array argument is read as many keys\n * rather than one.\n */\nexport const keyShape = unionShape(\n\tarrayShape(unionShape(stringShape(), numberShape()), {\n\t\tdescription: 'Multiple row keys, positional — a miss at an index is undefined there.',\n\t}),\n\tstringShape({ description: 'One row key.' }),\n\tnumberShape({ description: 'One row key.' }),\n)\n\n/** Describes a loose row — a flat object of column name to JSON value. */\nexport const rowShape = recordShape(jsonShape(), {\n\tdescription: 'A row as a flat object of column name to value.',\n})\n\n/**\n * Describes one or many loose rows — the array form resolves first, so an array argument is read as\n * many rows rather than one.\n */\nexport const rowsShape = unionShape(\n\tarrayShape(rowShape, { description: 'Multiple rows.' }),\n\trowShape,\n)\n\n/**\n * Describes one serialized where condition — `values` is always an array, even for a single-value\n * operator.\n */\nexport const conditionShape = objectShape({\n\tcolumn: stringShape({ description: 'The column this condition applies to.' }),\n\toperator: literalShape(\n\t\t[\n\t\t\t'equals',\n\t\t\t'not',\n\t\t\t'above',\n\t\t\t'below',\n\t\t\t'from',\n\t\t\t'to',\n\t\t\t'between',\n\t\t\t'like',\n\t\t\t'glob',\n\t\t\t'starts',\n\t\t\t'ends',\n\t\t\t'any',\n\t\t\t'none',\n\t\t\t'absent',\n\t\t\t'present',\n\t\t],\n\t\t{ description: 'The comparison operator.' },\n\t),\n\tvalues: arrayShape(jsonShape(), {\n\t\tdescription: 'The operand values the operator needs (always an array, even for one value).',\n\t}),\n\tconnector: optionalShape(\n\t\tliteralShape(['and', 'or'], {\n\t\t\tdescription: 'Joins this condition to the next; omit on the last condition.',\n\t\t}),\n\t),\n})\n\n/** Describes one sort term — a `column` to sort by and the `direction` to sort it in. */\nexport const orderShape = objectShape({\n\tcolumn: stringShape({ description: 'The column to sort by.' }),\n\tdirection: literalShape(['ascending', 'descending'], { description: 'The sort direction.' }),\n})\n\n/** Describes the serialized query form — conditions, order, and pagination. */\nexport const queryShape = objectShape({\n\tconditions: optionalShape(\n\t\tarrayShape(conditionShape, { description: 'The WHERE conditions, folded left to right.' }),\n\t),\n\torder: optionalShape(\n\t\tarrayShape(orderShape, { description: 'The sort terms, applied in order.' }),\n\t),\n\tlimit: optionalShape(integerShape({ min: 0, description: 'Max rows to return.' })),\n\toffset: optionalShape(integerShape({ min: 0, description: 'Rows to skip before returning.' })),\n})\n\n/**\n * Describes the shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —\n * discriminated by `operation` into the database operations `'create'`, `'tables'`, `'get'`,\n * `'records'`, `'count'`, `'aggregate'`, `'add'`, `'set'`, `'update'`, `'remove'`, and `'destroy'`.\n *\n * @remarks\n * Every arm carries `id` (the database id). `'create'` carries `tables` (the\n * {@link import('./types.js').TableSpec} column DSL, compiled through\n * {@link import('./compilers.js').expandTables}); `'get'` / `'update'` / `'remove'` carry `key`\n * (one key or an array of keys, positional); `'add'` / `'set'` carry `row` (one row or an array of\n * rows); `'update'` also carries `changes` (a loose partial row); `'records'` / `'count'` /\n * `'aggregate'` carry an optional `query` (the serialized form — `values` is always an array,\n * even for a single-value operator, so a caller never chains method calls or guesses arity).\n */\nexport const databaseToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['create'], { description: 'Define a new database.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttables: tableSpecShape,\n\t\tdriver: optionalShape(\n\t\t\tstringShape({ min: 1, description: 'The registered driver key. Defaults to \"memory\".' }),\n\t\t),\n\t\tprimary: optionalShape(\n\t\t\trecordShape(stringShape({ min: 1 }), {\n\t\t\t\tdescription: 'Table name to its primary-key column.',\n\t\t\t}),\n\t\t),\n\t\tindexes: optionalShape(\n\t\t\trecordShape(\n\t\t\t\tarrayShape(\n\t\t\t\t\tarrayShape(stringShape({ min: 1 }), {\n\t\t\t\t\t\tmin: 1,\n\t\t\t\t\t\tdescription: 'One nonempty index group of column names.',\n\t\t\t\t\t}),\n\t\t\t\t\t{ description: 'Zero or more index groups declared for the table.' },\n\t\t\t\t),\n\t\t\t\t{ description: 'Table name to its index column groups.' },\n\t\t\t),\n\t\t),\n\t\tversion: optionalShape(\n\t\t\tnumberShape({ description: 'The schema version for open-time reconciliation.' }),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['tables'], { description: \"List a database's table names.\" }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['get'], { description: 'Fetch one or more rows by primary key.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['records'], { description: 'List rows matching a query.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['count'], { description: 'Count rows matching a query.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['aggregate'], { description: 'Compute an aggregate over a column.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tfunction: literalShape(['count', 'sum', 'average', 'minimum', 'maximum'], {\n\t\t\tdescription: 'The aggregate function.',\n\t\t}),\n\t\tcolumn: stringShape({ min: 1, description: 'The column to aggregate.' }),\n\t\tquery: optionalShape(queryShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['add'], {\n\t\t\tdescription: 'Insert one or more rows (fails on a duplicate key).',\n\t\t}),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\trow: rowsShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['set'], { description: 'Upsert one or more rows.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\trow: rowsShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['update'], { description: 'Patch one or more existing rows.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t\tchanges: rowShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['remove'], { description: 'Delete one or more rows by key.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tkey: keyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['destroy'], { description: 'Drop a database entirely.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t}),\n)\n\n// === Relation tool shape (createRelationTool call args)\n//\n// Every arm carries an optional `manager` (which registered `RelationManagerInterface` to\n// address — omitted resolves to the sole registered manager) and a required `model` (the table\n// name on that manager). `include` is a flat array of dot-paths (mirrors `databaseToolShape`'s\n// flat-args ergonomic lever), expanded into a live `Include` by\n// {@link import('./helpers.js').expandInclude}.\n\n/** Describes a single row key (not an array) — used by `'link'` / `'unlink'` / `'links'`, which address exactly one owning row. */\nexport const singleKeyShape = unionShape(\n\tstringShape({ description: 'The owning row key.' }),\n\tnumberShape({ description: 'The owning row key.' }),\n)\n\n/** Describes the flat dot-path relation include list, expanded through {@link import('./helpers.js').expandInclude}. */\nexport const includeShape = optionalShape(\n\tarrayShape(\n\t\tstringShape({\n\t\t\tdescription: 'A dot-separated chain of relation names, for example \"contacts.account\".',\n\t\t}),\n\t\t{ description: 'Which relations to attach, as flat dot-paths.' },\n\t),\n)\n\n/** Describes which registered relation manager to address — omitted resolves to the sole registered manager. */\nexport const managerShape = optionalShape(\n\tstringShape({ min: 1, description: 'Which registered relation manager to address.' }),\n)\n\n/**\n * Describes the shape of {@link import('./factories.js').createRelationTool}'s call arguments —\n * discriminated by `operation` into the relation operations `'load'`, `'find'`, `'link'`,\n * `'unlink'`, and `'links'`.\n *\n * @remarks\n * `'load'` fetches one or more rows (positional key/array) with `include` attached. `'find'`\n * fetches rows (pagination / sort only) with `include` attached. `'link'` / `'unlink'` write /\n * remove a `through` junction row; `'links'` lists a `through` relation's linked keys.\n */\nexport const relationToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['load'], {\n\t\t\tdescription: 'Fetch one or more rows by key, with related rows attached.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: keyShape,\n\t\tinclude: includeShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['find'], {\n\t\t\tdescription: 'List rows, with related rows attached.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tinclude: includeShape,\n\t\tlimit: optionalShape(integerShape({ min: 0, description: 'Max rows to return.' })),\n\t\toffset: optionalShape(integerShape({ min: 0, description: 'Rows to skip before returning.' })),\n\t\tsort: optionalShape(stringShape({ min: 1, description: 'The column to sort by.' })),\n\t\tdirection: optionalShape(\n\t\t\tliteralShape(['ascending', 'descending'], { description: 'The sort direction.' }),\n\t\t),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['link'], {\n\t\t\tdescription: 'Connect two rows through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t\ttarget: singleKeyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['unlink'], {\n\t\t\tdescription: 'Disconnect two rows previously linked through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t\ttarget: singleKeyShape,\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['links'], {\n\t\t\tdescription: 'List every key linked to a row through a \"through\" relation.',\n\t\t}),\n\t\tmanager: managerShape,\n\t\tmodel: stringShape({ min: 1, description: 'The model (table) name.' }),\n\t\tkey: singleKeyShape,\n\t\trelation: stringShape({ min: 1, description: 'The \"through\" relation name.' }),\n\t}),\n)\n\n/**\n * Describes the shape of {@link import('./factories.js').createInferTool}'s call arguments — one or more\n * example `samples` to infer a JSON Schema from, plus per-call `format` / `enum` toggles and an\n * optional `candidates` array to check against the inferred schema.\n *\n * @remarks\n * `samples` requires at least one element (`min: 1`) — an empty array parses to `undefined`,\n * surfaced by the handler as a typed `TOOL` {@link import('./errors.js').ToolboxError}. When\n * `candidates` is present (any array, including empty), the handler compiles a contract from the\n * freshly inferred schema and checks each candidate against it with a strict guard (`.is`, no\n * coercion) — the opposite of {@link import('./factories.js').createEndpointTool}'s normalizing\n * `.parse` enforcement.\n */\nexport const inferToolShape = objectShape({\n\tsamples: arrayShape(jsonShape(), {\n\t\tmin: 1,\n\t\tdescription: 'The example values to infer a JSON Schema from (at least one).',\n\t}),\n\tformat: optionalShape(\n\t\tbooleanShape({\n\t\t\tdescription:\n\t\t\t\t'Infer string formats (date-time, email, ...) from the samples. Defaults to false.',\n\t\t}),\n\t),\n\tenum: optionalShape(\n\t\tbooleanShape({\n\t\t\tdescription: 'Infer enum constraints from repeated literal values. Defaults to false.',\n\t\t}),\n\t),\n\tcandidates: optionalShape(\n\t\tarrayShape(jsonShape(), {\n\t\t\tdescription:\n\t\t\t\t'Optional values to check against the freshly inferred schema. When present, the tool ' +\n\t\t\t\t'returns a per-candidate verdict (strict — no coercion) alongside the inferred parameters.',\n\t\t}),\n\t),\n})\n","import type { WorkflowDefinition, WorkflowResult } from '@orkestrel/workflow'\nimport type { DatabaseErrorCode } from '@orkestrel/database'\nimport type {\n\tInclude,\n\tModelInterface,\n\tRelationErrorCode,\n\tRelationManagerInterface,\n} from '@orkestrel/relation'\nimport type { QueryInput } from '@orkestrel/database'\nimport type {\n\tToolboxErrorCode,\n\tClampedQuery,\n\tDatabaseQueryInput,\n\tWorkflowToolResult,\n\tWorkflowLineage,\n} from './types.js'\nimport type { PhaseDraft, TaskDraft, WorkflowDraft, WorkflowSteps } from './types.js'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { isDatabaseError } from '@orkestrel/database'\nimport { isRelationError } from '@orkestrel/relation'\nimport type { ContractInterface, JSONRecord } from '@orkestrel/contract'\nimport { isArray, isObject } from '@orkestrel/contract'\nimport { ToolboxError } from './errors.js'\nimport { isWorkflowLineage } from './validators.js'\n\n// Toolbox owns the workflow tool's lenient-authoring completion, ancestry tags, and boundary\n// projections. Runtime scheduling, named-function resolution, and persistence remain native\n// `@orkestrel/workflow` responsibilities.\n\n/**\n * Returns the ancestry identifier of a workflow in a run chain — `workflow:<id>`.\n *\n * @remarks\n * Namespacing keeps a workflow id and a {@link tagAgent} agent name in one set without\n * collision, so re-entering a workflow or an agent already in the chain is a single `includes`\n * check.\n *\n * @param id - The workflow definition's `id`\n * @returns The namespaced ancestry tag (`workflow:<id>`)\n */\nexport function tagWorkflow(id: string): string {\n\treturn `workflow:${id}`\n}\n\n/**\n * Returns the ancestry identifier of an agent in a run chain — `agent:<name>`.\n *\n * @remarks\n * The agent counterpart of {@link tagWorkflow}: {@link import('./factories.js').createAgentFunction}\n * / {@link import('./factories.js').createWorkflowTool} guard against re-entering an agent or\n * workflow already in the chain (this package's typed `DEPTH` `ToolboxError`). The\n * `agent:` namespace keeps it distinct from a same-string workflow id.\n *\n * @param name - The agent's identifier / registry name\n * @returns The namespaced ancestry tag (`agent:<name>`)\n */\nexport function tagAgent(name: string): string {\n\treturn `agent:${name}`\n}\n\n/**\n * Returns the canonical workflow lineage — validated, copied, and frozen.\n *\n * @param lineage - The configured chain; omitted means a direct root\n * @returns An immutable caller-isolated lineage\n */\nexport function normalizeLineage(lineage: WorkflowLineage = []): WorkflowLineage {\n\tif (!isWorkflowLineage(lineage)) {\n\t\tthrow new ToolboxError('TOOL', 'workflow lineage must alternate unique workflow and agent tags')\n\t}\n\treturn Object.freeze([...lineage])\n}\n\n/**\n * Appends one tag to a workflow lineage and returns a frozen copy.\n *\n * @param lineage - The valid chain to extend\n * @param tag - The workflow or agent tag to append\n * @returns The validated immutable extension\n */\nexport function extendLineage(lineage: WorkflowLineage, tag: string): WorkflowLineage {\n\treturn normalizeLineage([...lineage, tag])\n}\n\n/**\n * Derives the zero-based workflow nesting depth from a valid lineage.\n *\n * @param lineage - The workflow/agent chain\n * @returns Zero for an empty/root lineage, then one per nested workflow\n */\nexport function deriveWorkflowDepth(lineage: WorkflowLineage): number {\n\tconst current = normalizeLineage(lineage)\n\tconst workflows = current.filter((tag) => tag.startsWith('workflow:')).length\n\treturn Math.max(0, workflows - 1)\n}\n\n/**\n * Builds the plain success summary {@link import('./factories.js').createWorkflowTool} returns on a\n * completed run — the universal tool-handler contract: return a plain value on success, appearing\n * identically over both the agent loop and MCP.\n *\n * @remarks\n * The summary is lean: the workflow's terminal `status`, settled-task count, and exact optional\n * native persistence outcome. It carries no synthetic `id` / `name`: a tool handler has no call\n * id; the `ToolManagerInterface` (`@orkestrel/tool`) supplies the canonical envelope's identity.\n *\n * @param result - The terminal `WorkflowResult` (`@orkestrel/workflow`) the run produced\n * @returns The plain success summary — `{ status, count, durable?, fault? }`\n */\nexport function summarizeWorkflow(result: WorkflowResult): WorkflowToolResult {\n\treturn {\n\t\tstatus: result.status,\n\t\tcount: result.results.length,\n\t\t...(result.durable === undefined ? {} : { durable: result.durable }),\n\t\t...(result.fault === undefined ? {} : { fault: result.fault }),\n\t}\n}\n\n// === Draft completion and flat-steps expansion (the tool's lenient authoring surfaces)\n//\n// Pure, deterministic synthesis that turns a widened authoring form into a strict\n// `WorkflowDefinition` (`@orkestrel/workflow`). They auto-fill only omitted identity (a provided\n// id/name is preserved verbatim; an explicitly-empty `id: ''` is rejected upstream by the draft\n// contract, never reached here), so a small model can author a complete tree without emitting an\n// `id` or a `name` anywhere in it. The factory re-validates the result against the strict\n// `createWorkflowContract().is` gate before running (soundness).\n\n/**\n * Completes a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesizes a\n * missing `id` deterministically and positionally, and defaults a missing `name` to its resolved\n * `id`.\n *\n * @remarks\n * The positional id scheme is stable and human-legible: the workflow is `wf`, phase `i` is\n * `phase-<i>`, and task `j` of that phase is `<phaseId>-task-<j>` (so a provided phase id flows\n * into its tasks' synthesized ids). A provided `id` / `name` at any level is kept verbatim —\n * synthesis touches only the omitted ones. A missing `name` defaults to the resolved `id` (never\n * the other way round), so the result always carries an `id` and a `name`. `behavior`, `description`, the per-phase\n * `concurrency` / `bail`, the per-task `retries` / `timeout`, and the workflow `bail` carry over\n * unchanged. The result is a complete {@link WorkflowDefinition}; the caller still validates it\n * against the strict contract.\n *\n * @param draft - The draft workflow (`id` and `name` optional at the workflow, phase, and task levels)\n * @returns A complete {@link WorkflowDefinition} with every id/name filled\n */\nexport function completeDraft(draft: WorkflowDraft): WorkflowDefinition {\n\tconst id = draft.id ?? 'wf'\n\treturn {\n\t\tid,\n\t\tname: draft.name ?? id,\n\t\t...(draft.description === undefined ? {} : { description: draft.description }),\n\t\tphases: draft.phases.map((phase, index) => completePhaseDraft(phase, index)),\n\t\t...(draft.bail === undefined ? {} : { bail: draft.bail }),\n\t}\n}\n\n/**\n * Completes one {@link PhaseDraft} into a strict phase definition — the per-phase step of\n * {@link completeDraft} (phase `index` → `phase-<index>` when its id is omitted).\n *\n * @param phase - The draft phase\n * @param index - The phase's positional index in the workflow\n * @returns A complete phase definition\n */\nexport function completePhaseDraft(\n\tphase: PhaseDraft,\n\tindex: number,\n): WorkflowDefinition['phases'][number] {\n\tconst id = phase.id ?? `phase-${index}`\n\treturn {\n\t\tid,\n\t\tname: phase.name ?? id,\n\t\t...(phase.description === undefined ? {} : { description: phase.description }),\n\t\ttasks: phase.tasks.map((task, taskIndex) => completeTaskDraft(task, id, taskIndex)),\n\t\t...(phase.concurrency === undefined ? {} : { concurrency: phase.concurrency }),\n\t\t...(phase.bail === undefined ? {} : { bail: phase.bail }),\n\t}\n}\n\n/**\n * Completes one {@link TaskDraft} into a strict task definition — the per-task leaf step of\n * {@link completeDraft} (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id\n * is omitted).\n *\n * @param task - The draft task\n * @param phaseId - The (resolved) parent phase id, so the synthesized task id nests under it\n * @param index - The task's positional index within its phase\n * @returns A complete task definition\n */\nexport function completeTaskDraft(\n\ttask: TaskDraft,\n\tphaseId: string,\n\tindex: number,\n): WorkflowDefinition['phases'][number]['tasks'][number] {\n\tconst id = task.id ?? `${phaseId}-task-${index}`\n\treturn {\n\t\tid,\n\t\tname: task.name ?? id,\n\t\t...(task.description === undefined ? {} : { description: task.description }),\n\t\t...(task.behavior === undefined ? {} : { behavior: task.behavior }),\n\t\t...(task.retries === undefined ? {} : { retries: task.retries }),\n\t\t...(task.timeout === undefined ? {} : { timeout: task.timeout }),\n\t}\n}\n\n/**\n * Expands a flat {@link WorkflowSteps} blob into a strict {@link WorkflowDefinition} — each step\n * becomes a one-task phase, in order.\n *\n * @remarks\n * The expansion of the tool's advertised surface: the deliberately-reduced flat form. Each\n * {@link import('./types.js').WorkflowStep} maps to a phase holding exactly one task: the step's\n * `name` becomes the task's `behavior` (the behavior-registry key). Ids/names are auto-filled\n * positionally — it builds an ids-omitted {@link WorkflowDraft} and delegates to\n * {@link completeDraft}, so the lenient surfaces share one synthesis path (step `i` → phase\n * `phase-<i>`, its task `phase-<i>-task-0`). The optional `name` becomes both the workflow's\n * deterministic id and its name, so named flat workflows retain distinct persistence keys;\n * omission keeps the shared draft fallback `wf`. The result is a complete definition the caller\n * validates against the strict contract before running.\n *\n * @param flat - The flat steps blob (`{ name?, steps: [{ name }] }`)\n * @returns A complete {@link WorkflowDefinition} (one one-task phase per step)\n */\nexport function expandSteps(flat: WorkflowSteps): WorkflowDefinition {\n\treturn completeDraft({\n\t\t...(flat.name === undefined ? {} : { id: flat.name, name: flat.name }),\n\t\tphases: flat.steps.map((step) => ({\n\t\t\ttasks: [{ behavior: step.name }],\n\t\t})),\n\t})\n}\n\n/**\n * Maps a caught error to the {@link ToolboxErrorCode} the terminal-tool factory throws with — the\n * pure classification step of that factory's error handling.\n *\n * @remarks\n * Narrows `error` with {@link isTerminalError} (`@orkestrel/terminal`) first: a non-`TerminalError`\n * value returns `undefined`, telling the caller this mapper does not apply (rethrow / handle\n * otherwise). For a genuine `TerminalError`, `'DEADLOCK'` maps to `'DEADLOCK'`, `'EXPIRE'` maps\n * to `'EXPIRE'`, and every other {@link import('@orkestrel/terminal').TerminalErrorCode}\n * (`'TARGET'`, `'LIMIT'`, `'CANCEL'`, `'DRIVER'`, `'DESTROYED'`) maps to the generic `'TOOL'`\n * code. The mapper only classifies — the factory performs the actual throw.\n *\n * @param error - The value caught from a terminal-manager operation (`ask` / `answer` / …)\n * @returns The mapped {@link ToolboxErrorCode}, or `undefined` if `error` is not a `TerminalError`\n */\nexport function inferTerminalCode(error: unknown): ToolboxErrorCode | undefined {\n\tif (!isTerminalError(error)) return undefined\n\tif (error.code === 'DEADLOCK') return 'DEADLOCK'\n\tif (error.code === 'EXPIRE') return 'EXPIRE'\n\treturn 'TOOL'\n}\n\n// === Database- and relation-tool error classification — a caught upstream error maps to the\n// code the owning factory re-throws with.\n\n/**\n * Maps a caught error to the granular {@link DatabaseErrorCode} (`@orkestrel/database`) the code\n * {@link import('./factories.js').createDatabaseTool} throws with — the pure classification step\n * of that factory's error handling, mirroring {@link inferTerminalCode}'s idiom for\n * `@orkestrel/database`.\n *\n * @param error - The value caught from a `@orkestrel/database` table operation\n * @returns The granular {@link DatabaseErrorCode}, or `undefined` if `error` is not a `DatabaseError`\n */\nexport function inferDatabaseCode(error: unknown): DatabaseErrorCode | undefined {\n\treturn isDatabaseError(error) ? error.code : undefined\n}\n\n/**\n * Maps a caught error to the granular {@link RelationErrorCode} (`@orkestrel/relation`) the code\n * {@link import('./factories.js').createRelationTool} throws with — the pure classification step\n * of that factory's error handling, mirroring {@link inferTerminalCode}'s idiom for\n * `@orkestrel/relation`.\n *\n * @param error - The value caught from a `@orkestrel/relation` operation\n * @returns The granular {@link RelationErrorCode}, or `undefined` if `error` is not a `RelationError`\n */\nexport function inferRelationCode(error: unknown): RelationErrorCode | undefined {\n\treturn isRelationError(error) ? error.code : undefined\n}\n\n/**\n * Expands the relation tool's flat dot-path `include` list into a live `@orkestrel/relation`\n * {@link Include} tree — the pure leaf {@link import('./factories.js').createRelationTool} calls\n * before a `'load'` / `'find'` call.\n *\n * @remarks\n * Each path splits on `'.'` into a chain of relation names, deep-merged into one nested\n * `Include` object with a leaf `true`. A longer path subsumes a shorter sibling's bare `true` —\n * `'contacts'` followed by `'contacts.account'` yields `{ contacts: { account: true } }`, never\n * overwriting the deeper chain. An empty segment (`''`, from a leading/trailing/doubled `.`) or a\n * path whose segment count exceeds `depth` throws a typed `TOOL` {@link ToolboxError}.\n *\n * @param paths - The flat dot-path `include` list (or `undefined` — yields `{}`)\n * @param depth - The max segment count a single path may reach\n * @returns The equivalent nested {@link Include}\n *\n * @example\n * ```ts\n * import { expandInclude } from '@src/core'\n *\n * expandInclude(['contacts', 'contacts.account'], 3)\n * // { contacts: { account: true } }\n * ```\n */\nexport function expandInclude(paths: readonly string[] | undefined, depth: number): Include {\n\treturn Iterator.from(paths ?? []).reduce<Include>((include, path) => {\n\t\tconst segments = path.split('.')\n\t\tif (segments.length > depth || segments.some((segment) => segment.length === 0)) {\n\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t}\n\t\tconst ancestors: Include[] = [include]\n\t\tconst last = segments.length - 1\n\t\tfor (const [index, segment] of segments.entries()) {\n\t\t\tif (index === last) break\n\t\t\tconst branch = ancestors.at(-1)\n\t\t\tif (branch === undefined)\n\t\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t\tconst existing = branch[segment]\n\t\t\tancestors.push(isObject(existing) ? existing : {})\n\t\t}\n\t\tconst leaf = segments[last]\n\t\tconst branch = ancestors.at(-1)\n\t\tif (leaf === undefined || branch === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t}\n\t\tconst existing = branch[leaf]\n\t\treturn ancestors.slice(0, -1).reduceRight<Include>(\n\t\t\t(merged, ancestor, index) => {\n\t\t\t\tconst segment = segments[index]\n\t\t\t\tif (segment === undefined)\n\t\t\t\t\tthrow new ToolboxError('TOOL', `malformed include path '${path}'`, { path, depth })\n\t\t\t\treturn { ...ancestor, [segment]: merged }\n\t\t\t},\n\t\t\t{ ...branch, [leaf]: existing === undefined ? true : existing },\n\t\t)\n\t}, {})\n}\n\n/**\n * Resolves which registered {@link RelationManagerInterface} a relation-tool call addresses — the\n * pure manager-resolution leaf {@link import('./factories.js').createRelationTool} calls on\n * every operation.\n *\n * @remarks\n * An explicit `name` must match a key of `managers` (a miss throws a typed `TOOL`\n * {@link ToolboxError} naming the registered managers). An omitted `name` resolves to the sole\n * registered manager when exactly one is registered, else throws the same typed error.\n *\n * @param managers - The tool's registered `RelationManagerInterface` map\n * @param name - The call's optional `manager` field\n * @returns The resolved {@link RelationManagerInterface}\n */\nexport function resolveRelationManager(\n\tmanagers: Readonly<Record<string, RelationManagerInterface>>,\n\tname: string | undefined,\n): RelationManagerInterface {\n\tif (name !== undefined) {\n\t\tconst manager = managers[name]\n\t\tif (manager === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `unknown relation manager '${name}'`, {\n\t\t\t\tmanager: name,\n\t\t\t\tmanagers: Object.keys(managers),\n\t\t\t})\n\t\t}\n\t\treturn manager\n\t}\n\tconst names = Object.keys(managers)\n\tconst [single] = names\n\tif (names.length === 1 && single !== undefined) {\n\t\tconst manager = managers[single]\n\t\tif (manager !== undefined) return manager\n\t}\n\tthrow new ToolboxError('TOOL', 'no relation manager resolved for the call', {\n\t\tmanagers: names,\n\t})\n}\n\n/**\n * Resolves a `model` name against a live {@link RelationManagerInterface} — the pure model-lookup\n * leaf {@link import('./factories.js').createRelationTool} calls on every operation, mirroring\n * {@link resolveRelationManager}'s guard shape.\n *\n * @param manager - The resolved {@link RelationManagerInterface}\n * @param name - The call's `model` field\n * @returns The model's {@link ModelInterface}\n */\nexport function resolveRelationModel(\n\tmanager: RelationManagerInterface,\n\tname: string,\n): ModelInterface {\n\tif (!manager.has(name)) {\n\t\tthrow new ToolboxError('TOOL', `unknown model '${name}'`, {\n\t\t\tmodel: name,\n\t\t\tmodels: manager.names(),\n\t\t})\n\t}\n\treturn manager.model(name)\n}\n\n// === Database-tool operation leaves\n\n/**\n * Returns the canonical live `@orkestrel/database` {@link QueryInput} for the database tool's\n * parsed serialized query — each condition's omitted `connector` defaults to `'and'`.\n *\n * @remarks\n * The wire form ({@link import('./shapers.js').databaseToolShape}) lets a caller drop `connector`\n * on the last condition (it has nothing to join forward to); the compiled `Condition` a live\n * `@orkestrel/database` table call accepts always carries one, so this fills the gap. `order` /\n * `limit` / `offset` pass through unchanged. Pure and total.\n *\n * @param query - The parsed query (or `undefined`)\n * @returns The equivalent live `QueryInput`, or `undefined` when `query` is `undefined`\n */\nexport function normalizeQuery(query: DatabaseQueryInput | undefined): QueryInput | undefined {\n\tif (query === undefined) return undefined\n\tconst conditions = query.conditions?.map((condition) => ({\n\t\t...condition,\n\t\tconnector: condition.connector ?? 'and',\n\t}))\n\treturn {\n\t\t...(conditions === undefined ? {} : { conditions }),\n\t\t...(query.order === undefined ? {} : { order: query.order }),\n\t\t...(query.limit === undefined ? {} : { limit: query.limit }),\n\t\t...(query.offset === undefined ? {} : { offset: query.offset }),\n\t}\n}\n\n/**\n * Picks the effective row limit a tool reads with — the requested count when it sits inside the\n * cap, the cap when it exceeds it, and `0` when either falls below zero.\n *\n * @remarks\n * The one place the database tool's `'records'` clamp ({@link clampQuery}) and the relation tool's\n * `'find'` / `'links'` truncation both take their ceiling from, so a negative construction-time\n * option can never reach a slice. Pure and total.\n *\n * @example\n * ```ts\n * import { resolveLimit } from '@src/core'\n *\n * resolveLimit(undefined, 100) // 100 — an omitted request takes the cap\n * resolveLimit(500, 100) // 100 — a request over the cap is clamped down\n * resolveLimit(-1, 100) // 0 — a negative request floors at zero\n * ```\n *\n * @param requested - The caller's requested row count (or `undefined`)\n * @param cap - The row-count ceiling\n * @returns The effective row limit, never below `0` and never above `cap`\n */\nexport function resolveLimit(requested: number | undefined, cap: number): number {\n\treturn Math.max(0, Math.min(requested ?? cap, cap))\n}\n\n/**\n * Clamps a `'records'` call's query to a row cap, and builds the probe query the caller reads with\n * — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation uses\n * to detect truncation without a separate `count` round trip.\n *\n * @remarks\n * {@link resolveLimit} picks the effective limit, so a caller can never exceed the configured cap\n * by supplying a larger `query.limit`, and can never drive it below `0`. The returned probe query\n * requests one more row than the effective limit (`limit: effective + 1`) — if storage returns\n * that many, the caller knows the true result was truncated (`rows.length > effective`) and slices\n * back down to `effective` before returning.\n *\n * @example\n * ```ts\n * import { clampQuery } from '@src/core'\n *\n * const { query, limit } = clampQuery(undefined, 100)\n * // limit === 100, query.limit === 101 — a probe fetching one extra row\n * const rows = await table.records(query)\n * const truncated = rows.length > limit // true when storage had more than `limit` rows\n * ```\n *\n * @param query - The live query to clamp (or `undefined`)\n * @param cap - The row-count ceiling\n * @returns The probe query (`limit` bumped by one) and the effective `limit`\n */\nexport function clampQuery(query: QueryInput | undefined, cap: number): ClampedQuery {\n\tconst limit = resolveLimit(query?.limit, cap)\n\treturn { query: { ...query, limit: limit + 1 }, limit }\n}\n/**\n * Resolves an owned workflow input through the supplied flat or draft contracts.\n * @example\n * ```ts\n * import { createContract } from '@orkestrel/contract'\n * import { completeDraft, createWorkflowDraftContract, resolveWorkflowTarget, workflowStepsShape } from '@src/core'\n *\n * const definition = completeDraft({ phases: [{ tasks: [{}] }] })\n * const steps: import('@orkestrel/contract').ContractInterface<import('./types.js').WorkflowSteps> = createContract(workflowStepsShape)\n * resolveWorkflowTarget({}, definition, steps, createWorkflowDraftContract()) // definition\n * ```\n */\nexport function resolveWorkflowTarget(\n\towned: JSONRecord,\n\tdefinition: WorkflowDefinition,\n\tsteps: ContractInterface<WorkflowSteps>,\n\tdraft: ContractInterface<WorkflowDraft>,\n): WorkflowDefinition | undefined {\n\tif (Object.keys(owned).length === 0) return definition\n\tif (isArray(owned.steps)) {\n\t\tconst flat = steps.parse(owned)\n\t\treturn flat === undefined ? undefined : expandSteps(flat)\n\t}\n\tconst parsed = draft.parse(owned)\n\treturn parsed === undefined ? undefined : completeDraft(parsed)\n}\n","import type { TableMap } from '@orkestrel/database'\nimport type { ContractShape } from '@orkestrel/contract'\nimport type { ColumnPrimitive, ColumnSpec, TableSpec } from './types.js'\nimport {\n\tbooleanShape,\n\tintegerShape,\n\tisString,\n\tnumberShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\n\n// Toolbox compilers — the config-only `TableSpec` column DSL compiled into the live\n// `@orkestrel/database` `TableMap` a `createDatabase` call accepts. Pure and total: one composite\n// walk over the spec, and the `compileColumn` / `compileColumnPrimitive` leaves it maps with.\n\n/**\n * Compiles a {@link TableSpec} into the `@orkestrel/database` {@link TableMap} it configures —\n * each {@link ColumnSpec} maps to the matching primitive shaper (`'string'` → `stringShape()`,\n * `'integer'` → `integerShape()`, `'number'` → `numberShape()`, `'boolean'` → `booleanShape()`),\n * wrapped in `optionalShape` when the column declares `optional: true`. Total, pure.\n *\n * @param spec - The small-model-facing table layout\n * @returns The compiled `TableMap` a `@orkestrel/database` `createDatabase` call accepts\n */\nexport function expandTables(spec: TableSpec): TableMap {\n\tconst tables: Record<string, Readonly<Record<string, ContractShape>>> = {}\n\tfor (const [table, definition] of Object.entries(spec)) {\n\t\tconst columns: Record<string, ContractShape> = {}\n\t\tfor (const [column, columnSpec] of Object.entries(definition.columns)) {\n\t\t\tcolumns[column] = compileColumn(columnSpec)\n\t\t}\n\t\ttables[table] = columns\n\t}\n\treturn tables\n}\n\n/**\n * Compiles one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf\n * {@link expandTables} maps over.\n *\n * @param spec - The column spec to compile\n * @returns The `@orkestrel/database` column shape, wrapped in `optionalShape` when the spec declares `optional: true`\n */\nexport function compileColumn(spec: ColumnSpec): ContractShape {\n\tconst primitive = isString(spec) ? spec : spec.primitive\n\tconst optional = !isString(spec) && spec.optional === true\n\tconst shape = compileColumnPrimitive(primitive)\n\treturn optional ? optionalShape(shape) : shape\n}\n\n/**\n * Compiles one {@link import('./types.js').ColumnPrimitive} into its primitive\n * `@orkestrel/database` shape — the leaf {@link compileColumn} wraps.\n *\n * @param primitive - The declared column primitive\n * @returns The matching primitive `@orkestrel/database` shape\n */\nexport function compileColumnPrimitive(primitive: ColumnPrimitive): ContractShape {\n\tif (primitive === 'string') return stringShape()\n\tif (primitive === 'integer') return integerShape()\n\tif (primitive === 'number') return numberShape()\n\treturn booleanShape()\n}\n","import type { DatabaseDefinition, DefinitionStoreInterface } from '../types.js'\n\n/**\n * Represents the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of\n * {@link DatabaseDefinition}s keyed by database id, the default store\n * {@link import('../factories.js').createMemoryDefinitionStore} builds. It implements the same\n * {@link DefinitionStoreInterface} contract as\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}: this store copies on\n * write and on read; the table-backed store narrows an untrusted stored blob and reports\n * `undefined` for a malformed one.\n *\n * @remarks\n * A plain `Map<string, DatabaseDefinition>` (the definition is already pure,\n * self-contained config-only JSON, so no encoding is needed for the memory tier). Values are\n * structured-cloned on both write and read, keeping caller mutation outside the store. There is no\n * idle-TTL and no eviction: a persisted definition lives until an explicit `delete`. A durable\n * backend (JSON / SQLite / IndexedDB) swaps in through the same interface without touching a\n * consumer — its driver-pluggable twin is\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore} (the definition as one\n * opaque JSON column).\n *\n * - **`get` resolves the persisted definition for an id**, or `undefined` if none is stored.\n * - **`set` inserts / replaces under the definition's own `id`** (no separate id param).\n * - **`delete` drops a definition by id**; an absent id is a no-op (no throw).\n *\n * The public surface is exactly `get` / `set` / `delete` — no extra members (the method\n * bijection with {@link DefinitionStoreInterface}).\n *\n * @example\n * ```ts\n * import { createMemoryDefinitionStore } from '@src/core'\n *\n * const store = createMemoryDefinitionStore()\n * await store.set({ id: 'shop', driver: 'memory', tables: {} })\n * const definition = await store.get('shop')\n * await store.delete('shop')\n * ```\n */\nexport class MemoryDefinitionStore implements DefinitionStoreInterface {\n\treadonly #definitions = new Map<string, DatabaseDefinition>()\n\n\t/**\n\t * Resolves the persisted definition for `id`, copied out of the backing `Map`.\n\t *\n\t * @param id - The database id to read\n\t * @returns The stored {@link DatabaseDefinition}, or `undefined` when none is stored\n\t */\n\tget(id: string): Promise<DatabaseDefinition | undefined> {\n\t\tconst definition = this.#definitions.get(id)\n\t\treturn Promise.resolve(definition === undefined ? undefined : structuredClone(definition))\n\t}\n\n\t/**\n\t * Inserts or replaces a definition under its own `id`, copied into the backing `Map`.\n\t *\n\t * @param definition - The config to persist; its own `id` is the key (no separate id param)\n\t * @returns A promise settling after the definition is stored\n\t */\n\tset(definition: DatabaseDefinition): Promise<void> {\n\t\tthis.#definitions.set(definition.id, structuredClone(definition))\n\t\treturn Promise.resolve()\n\t}\n\n\t/**\n\t * Drops the definition stored under `id`.\n\t *\n\t * @param id - The database id to drop; an absent id is a no-op, never a throw\n\t * @returns A promise settling after no definition is stored under `id`\n\t */\n\tdelete(id: string): Promise<void> {\n\t\tthis.#definitions.delete(id)\n\t\treturn Promise.resolve()\n\t}\n}\n","import type {\n\tDatabaseDefinition,\n\tDatabaseDefinitionRow,\n\tDefinitionStoreInterface,\n} from '../types.js'\nimport type { TableInterface } from '@orkestrel/database'\nimport { isDatabaseDefinition } from '../validators.js'\n\n/**\n * Represents a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database` layer — a\n * database's durable config state is a row, so persistence reduces to keyed point-access\n * (`get` / `set` / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the\n * plain-`Map` {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}.\n *\n * @remarks\n * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,\n * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /\n * IndexedDB backend swaps in without touching a consumer — the same seam as\n * {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}. The driver defaults to\n * memory ({@link import('../factories.js').createDatabaseDefinitionStore} passes\n * `createMemoryDriver()`), so it also works in memory out of the box; you opt into the durable\n * plumbing by passing a JSON / SQLite / IndexedDB driver.\n *\n * The {@link DatabaseDefinition} is stored as one opaque JSON column — the table is a row of\n * `{ id; definition }` ({@link DatabaseDefinitionRow}). The definition is already a complete,\n * self-contained, pure-JSON config payload (never a live handle), so storing it whole is lossless\n * and keeps the row type flat (`definition` reads back as `unknown`).\n *\n * - **`set(definition)` upserts under the definition's own `id`** (no separate id param) — it\n * writes the row `{ id: definition.id, definition }`.\n * - **`get(id)` resolves the stored definition for an id**, narrowing the opaque JSON column back\n * to a {@link DatabaseDefinition} ({@link import('../validators.js').isDatabaseDefinition} — the\n * boundary narrow for an untrusted storage read), or `undefined` if none is stored\n * or the stored blob is malformed.\n * - **`delete(id)` drops a definition by id**; an absent id is a no-op (no throw).\n *\n * The public surface is exactly `get` / `set` / `delete` — no extra members (the method\n * bijection with {@link DefinitionStoreInterface}).\n *\n * @example\n * ```ts\n * import { createDatabaseDefinitionStore, createMemoryDriver } from '@src/core'\n *\n * const store = createDatabaseDefinitionStore(createMemoryDriver()) // a durable driver swaps in here\n * await store.set({ id: 'shop', driver: 'memory', tables: {} }) // persist the config (one JSON column)\n * const definition = await store.get('shop')\n * await store.delete('shop')\n * ```\n */\nexport class DatabaseDefinitionStore implements DefinitionStoreInterface {\n\treadonly #table: TableInterface<DatabaseDefinitionRow>\n\n\t/**\n\t * Wraps a table as a definition store.\n\t *\n\t * @param table - The {@link TableInterface} holding the definitions — its row is the\n\t * {@link DatabaseDefinitionRow} `{ id; definition }` shape (the definition one opaque JSON column)\n\t */\n\tconstructor(table: TableInterface<DatabaseDefinitionRow>) {\n\t\tthis.#table = table\n\t}\n\n\t/**\n\t * Resolves the persisted definition for `id`, narrowing the opaque JSON column back to a\n\t * {@link DatabaseDefinition}.\n\t *\n\t * @param id - The database id to read\n\t * @returns The stored {@link DatabaseDefinition}, or `undefined` when none is stored or the\n\t * stored blob is malformed\n\t */\n\tasync get(id: string): Promise<DatabaseDefinition | undefined> {\n\t\tconst row = await this.#table.get(id)\n\t\tif (row === undefined) return undefined\n\t\t// The definition crosses back as an untrusted storage read (a structured clone / a JSON\n\t\t// row), so narrow the opaque JSON column with the boundary guard rather than a cast; a\n\t\t// malformed blob resolves `undefined`, never a broken definition.\n\t\treturn isDatabaseDefinition(row.definition) ? row.definition : undefined\n\t}\n\n\t/**\n\t * Inserts or replaces a definition under its own `id` — the written row is `{ id, definition }`.\n\t *\n\t * @param definition - The config to persist; its own `id` is the row key (no separate id param)\n\t * @returns A promise settling after the row is written\n\t */\n\tasync set(definition: DatabaseDefinition): Promise<void> {\n\t\tawait this.#table.set({ id: definition.id, definition })\n\t}\n\n\t/**\n\t * Drops the definition stored under `id`.\n\t *\n\t * @param id - The database id to drop; an absent id is a no-op, never a throw\n\t * @returns A promise settling after no row is stored under `id`\n\t */\n\tasync delete(id: string): Promise<void> {\n\t\tawait this.#table.remove(id)\n\t}\n}\n","import type { DatabaseInterface, DriverInterface, KeyFunction } from '@orkestrel/database'\nimport type { DefinitionStoreInterface } from '../types.js'\nimport { createDatabase } from '@orkestrel/database'\nimport { ToolboxError } from '../errors.js'\nimport { expandTables } from '../compilers.js'\n\n/**\n * Resolves a database definition into a cached live handle for a database tool, over the tool's\n * live handles, its stored definitions, its driver registry, and an optional key generator.\n *\n * @example\n * ```ts\n * import { DatabaseResolver } from '@orkestrel/toolbox'\n *\n * const resolver = new DatabaseResolver(handles, drivers, generator, store)\n * const database = await resolver.resolve('shop')\n * ```\n */\nexport class DatabaseResolver {\n\treadonly #handles: Map<string, DatabaseInterface>\n\treadonly #drivers: Readonly<Record<string, () => DriverInterface>>\n\treadonly #generator: KeyFunction | undefined\n\treadonly #store: DefinitionStoreInterface | undefined\n\n\t/**\n\t * Creates a database resolver over the tool's live state and optional definition store.\n\t *\n\t * @param handles - Initial live database handles cached by id\n\t * @param drivers - Driver factories keyed by definition driver name\n\t * @param generator - Optional key generator supplied to newly created databases\n\t * @param store - Optional persistent definition store\n\t */\n\tconstructor(\n\t\thandles: ReadonlyMap<string, DatabaseInterface>,\n\t\tdrivers: Readonly<Record<string, () => DriverInterface>>,\n\t\tgenerator?: KeyFunction,\n\t\tstore?: DefinitionStoreInterface,\n\t) {\n\t\tthis.#handles = new Map(handles)\n\t\tthis.#drivers = drivers\n\t\tthis.#generator = generator\n\t\tthis.#store = store\n\t}\n\n\t/**\n\t * Determines whether a live database is cached by id.\n\t *\n\t * @param id - Database id\n\t * @returns True if a live handle is cached; false otherwise\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#handles.has(id)\n\t}\n\n\t/**\n\t * Reads a cached database without consulting the definition store.\n\t *\n\t * @param id - Database id\n\t * @returns The cached live database, or `undefined`\n\t */\n\tget(id: string): DatabaseInterface | undefined {\n\t\treturn this.#handles.get(id)\n\t}\n\n\t/**\n\t * Caches a live database by id.\n\t *\n\t * @param id - Database id\n\t * @param database - Live database handle\n\t * @returns Nothing\n\t */\n\tset(id: string, database: DatabaseInterface): void {\n\t\tthis.#handles.set(id, database)\n\t}\n\n\t/**\n\t * Removes a cached live database by id.\n\t *\n\t * @param id - Database id\n\t * @returns Nothing\n\t */\n\tdelete(id: string): void {\n\t\tthis.#handles.delete(id)\n\t}\n\n\t/**\n\t * Resolves a live database by id — the cached handle when one exists, otherwise a database\n\t * constructed from its stored definition.\n\t *\n\t * @param id - Database definition id\n\t * @returns The cached or newly constructed live database\n\t */\n\tasync resolve(id: string): Promise<DatabaseInterface> {\n\t\tconst cached = this.#handles.get(id)\n\t\tif (cached !== undefined) return cached\n\t\tif (this.#store !== undefined) {\n\t\t\tconst definition = await this.#store.get(id)\n\t\t\tif (definition !== undefined) {\n\t\t\t\tconst factory = this.#drivers[definition.driver]\n\t\t\t\tif (factory === undefined) {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown driver '${definition.driver}'`, {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tdriver: definition.driver,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst handle = createDatabase({\n\t\t\t\t\tdriver: factory(),\n\t\t\t\t\ttables: expandTables(definition.tables),\n\t\t\t\t\tname: id,\n\t\t\t\t\t...(definition.primary === undefined ? {} : { primary: definition.primary }),\n\t\t\t\t\t...(definition.indexes === undefined ? {} : { indexes: definition.indexes }),\n\t\t\t\t\t...(definition.version === undefined ? {} : { version: definition.version }),\n\t\t\t\t\t...(this.#generator === undefined ? {} : { generator: this.#generator }),\n\t\t\t\t})\n\t\t\t\tthis.set(id, handle)\n\t\t\t\treturn handle\n\t\t\t}\n\t\t}\n\t\tthrow new ToolboxError('TOOL', `unknown database '${id}'`, { id })\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type { AgentInterface, AgentRegistryInterface } from '@orkestrel/agent'\nimport type { WorkspaceManagerInterface } from '@orkestrel/workspace'\nimport type { ToolInterface, ToolManagerInterface } from '@orkestrel/tool'\nimport type {\n\tWorkflowDefinition,\n\tWorkflowFunction,\n\tWorkflowRegistry,\n\tWorkflowRunnerInterface,\n\tTaskControllerInterface,\n} from '@orkestrel/workflow'\nimport type {\n\tAgentFunction,\n\tAgentFunctionOptions,\n\tWorkflowAgents,\n\tAgentToolOptions,\n\tAnswerToolOptions,\n\tDatabaseDefinition,\n\tDatabaseDefinitionRow,\n\tDatabaseToolOptions,\n\tDefinitionStoreInterface,\n\tEndpointDefinition,\n\tEndpointToolOptions,\n\tInferToolOptions,\n\tPromptToolOptions,\n\tRelationToolOptions,\n\tWorkflowDraft,\n\tWorkflowSteps,\n\tWorkflowToolOptions,\n\tWorkspaceOperation,\n\tWorkspaceToolOptions,\n} from './types.js'\nimport type { DatabaseInterface, DriverInterface, TableInterface } from '@orkestrel/database'\nimport { agentResultToJSON } from '@orkestrel/agent'\nimport { createWorkspaceManager, isTextContent, rangeOf } from '@orkestrel/workspace'\nimport { createTool } from '@orkestrel/tool'\nimport {\n\tattempt,\n\tcloneJSONRecord,\n\tcreateContract,\n\tisArray,\n\tisError,\n\tisFunction,\n\tisNumber,\n\tisRecord,\n\tisString,\n\tparseJSONValue,\n\trawShape,\n\tsamplesToSchema,\n\tschemaToObject,\n\tschemaToParameters,\n\tschemaToShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { createForm, isFormError, isFormValues, parseForm } from '@orkestrel/form'\nimport { createDatabase, createMemoryDriver } from '@orkestrel/database'\nimport { createWorkflowContract } from '@orkestrel/workflow'\nimport { MemoryDefinitionStore } from './stores/MemoryDefinitionStore.js'\nimport { DatabaseDefinitionStore } from './stores/DatabaseDefinitionStore.js'\nimport { DatabaseResolver } from './databases/DatabaseResolver.js'\nimport {\n\tAGENT_TOOL_DEPTH,\n\tAGENT_TOOL_DESCRIPTION,\n\tAGENT_TOOL_NAME,\n\tAGENT_TOOL_SUMMARY,\n\tANSWER_TOOL_DESCRIPTION,\n\tANSWER_TOOL_NAME,\n\tANSWER_TOOL_SUMMARY,\n\tDATABASE_TOOL_DESCRIPTION,\n\tDATABASE_TOOL_LIMIT,\n\tDATABASE_TOOL_MUTATIONS,\n\tDATABASE_TOOL_NAME,\n\tDATABASE_TOOL_SUMMARY,\n\tDESCRIBE_TOOL_DESCRIPTION,\n\tDESCRIBE_TOOL_NAME,\n\tDESCRIBE_TOOL_SUMMARY,\n\tINFER_TOOL_DESCRIPTION,\n\tINFER_TOOL_NAME,\n\tINFER_TOOL_SUMMARY,\n\tMAX_WORKFLOW_CHAIN,\n\tPROMPT_TOOL_DESCRIPTION,\n\tPROMPT_TOOL_NAME,\n\tPROMPT_TOOL_SUMMARY,\n\tRELATION_TOOL_DEPTH,\n\tRELATION_TOOL_DESCRIPTION,\n\tRELATION_TOOL_LIMIT,\n\tRELATION_TOOL_NAME,\n\tRELATION_TOOL_SUMMARY,\n\tWORKFLOW_TOOL_DESCRIPTION,\n\tWORKFLOW_TOOL_NAME,\n\tWORKFLOW_TOOL_SUMMARY,\n\tWORKSPACE_TOOL_DESCRIPTION,\n\tWORKSPACE_TOOL_NAME,\n\tWORKSPACE_TOOL_SUMMARY,\n} from './constants.js'\nimport { ToolboxError, isToolboxError } from './errors.js'\nimport {\n\tclampQuery,\n\tresolveWorkflowTarget,\n\tderiveWorkflowDepth,\n\texpandInclude,\n\textendLineage,\n\tinferDatabaseCode,\n\tinferRelationCode,\n\tinferTerminalCode,\n\tnormalizeLineage,\n\tnormalizeQuery,\n\tresolveLimit,\n\tresolveRelationManager,\n\tresolveRelationModel,\n\tsummarizeWorkflow,\n\ttagAgent,\n\ttagWorkflow,\n} from './helpers.js'\nimport { expandTables } from './compilers.js'\nimport { isAgentFunction } from './validators.js'\nimport {\n\tagentToolShape,\n\tanswerToolShape,\n\tdatabaseToolShape,\n\tdescribeToolShape,\n\tinferToolShape,\n\tpromptToolShape,\n\trelationToolShape,\n\tworkflowDraftShape,\n\tworkflowStepsShape,\n\tworkspaceToolShape,\n} from './shapers.js'\n\n// This package's tool factories. `createWorkflowTool` owns authoring translation and boundary\n// policy while delegating execution/persistence to `@orkestrel/workflow`; `createWorkspaceTool`\n// owns the model-facing operation dispatch over `@orkestrel/workspace`; `createAgentTool` owns\n// sub-agent delegation over an `AgentRegistryInterface`.\n\n/**\n * Wraps a registered tool as a {@link WorkflowFunction} (`@orkestrel/workflow`) — the opt-in\n * adapter that lets a `function`-form task run a `@orkestrel/tool` tool by name.\n *\n * @remarks\n * Composes into a caller's `WorkflowOptions.functions` registry like any other behavior\n * (`{ publish: createToolFunction(tools, 'publish') }`); the pure workflow runner has no\n * knowledge of tools itself. The returned function executes `name` against `tools` with the\n * task's `controller.input` as the call arguments. The adapter resolves the live tool, calls its\n * `execute` method directly, and deep-gates the returned unknown through `parseJSONValue`. The\n * execution context it passes carries the task's own `controller.signal`, so a handler that\n * reads `context.signal` observes the caller's cancellation.\n * Genuine execution throws retain identity. An unregistered name or non-JSON return throws this\n * package's typed `TOOL` `ToolboxError`.\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/tool`) the named tool is registered on\n * @param name - The registered tool's name\n * @returns A {@link WorkflowFunction} that runs the named tool\n *\n * @example\n * ```ts\n * import { createToolFunction } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const tools = createToolManager()\n * tools.add(myPublishTool)\n * const runner = createWorkflowRunner()\n * await runner.execute(definition, { functions: { publish: createToolFunction(tools, 'publish') } })\n * ```\n */\nexport function createToolFunction(tools: ToolManagerInterface, name: string): WorkflowFunction {\n\tif (name === WORKFLOW_TOOL_NAME) {\n\t\tthrow new ToolboxError('TOOL', `tool '${WORKFLOW_TOOL_NAME}' is reserved for live workflows`, {\n\t\t\ttool: name,\n\t\t})\n\t}\n\treturn async (controller) => {\n\t\tconst tool = tools.tool(name)\n\t\tif (tool === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `tool '${name}' is not registered`, { tool: name })\n\t\t}\n\t\tconst result = parseJSONValue(\n\t\t\tawait tool.execute(controller.input, { signal: controller.signal }),\n\t\t)\n\t\tif (result === undefined) {\n\t\t\tthrow new ToolboxError('TOOL', `tool '${name}' returned a non-JSON value`, { tool: name })\n\t\t}\n\t\treturn result\n\t}\n}\n\n/**\n * Wraps a live `AgentInterface` (`@orkestrel/agent`) as a {@link WorkflowFunction}\n * (`@orkestrel/workflow`) — the opt-in adapter that runs the agent to a settled result and carries\n * immutable lineage metadata for contextual Toolbox composition.\n *\n * @remarks\n * Composes into a caller's registry like any other behavior; the pure workflow runner has no\n * knowledge of agents itself. A root adapter derives its workflow lineage from the controller,\n * while a contextual adapter requires an exact match. Repeated agents, repeated workflows, and\n * targets deeper than {@link import('./constants.js').MAX_WORKFLOW_CHAIN} are rejected before\n * agent or runner activity. When {@link import('./types.js').AgentFunctionOptions.runner} is\n * supplied, the adapter binds a recursion-safe {@link createWorkflowTool} onto the agent's\n * `context.tools`, propagating opaque leaves, raw agents, lineage, and the native store. The\n * task's cancellation propagates through the Agent's native per-run signal seam:\n * `agent.generate({ signal: controller.signal })` resolves a partial `AgentResult` on a cancel\n * (never rejects), projected onto its exact JSON fields.\n *\n * A bound agent is single-run. A concurrent branch sharing the same real agent is rejected before\n * its fixed {@link import('./constants.js').WORKFLOW_TOOL_NAME} binding can be replaced. Toolbox\n * cannot serialize opaque external wrappers that hide or bypass the raw agent registry; hosts\n * must give such concurrent work distinct agents.\n *\n * @param agent - The live `AgentInterface` to run\n * @param options - The nested-workflow composition and lineage options\n * @returns A frozen {@link AgentFunction} that runs `agent` to its settled result\n *\n * @example\n * ```ts\n * import { createAgentFunction } from '@src/core'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const runner = createWorkflowRunner()\n * const review = createAgentFunction(myAgent, { runner })\n * await runner.execute(definition, { functions: { review } })\n * ```\n */\nexport function createAgentFunction(\n\tagent: AgentInterface,\n\toptions?: AgentFunctionOptions,\n): AgentFunction {\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('workflow:')) {\n\t\tthrow new ToolboxError('TOOL', 'agent function lineage must end with a workflow tag')\n\t}\n\tconst functions =\n\t\toptions?.functions === undefined ? undefined : Object.freeze({ ...options.functions })\n\tconst agents = options?.agents === undefined ? undefined : Object.freeze({ ...options.agents })\n\tconst metadata: Pick<AgentFunction, 'category' | 'lineage'> = {\n\t\tcategory: 'agent',\n\t\tlineage,\n\t}\n\treturn Object.freeze(\n\t\tObject.assign(async (controller: TaskControllerInterface) => {\n\t\t\tconst workflow = tagWorkflow(controller.task.phase.workflow.id)\n\t\t\tconst current = lineage.length === 0 ? extendLineage(lineage, workflow) : lineage\n\t\t\tif (current.at(-1) !== workflow) {\n\t\t\t\tthrow new ToolboxError('DEPTH', 'agent function workflow does not match its lineage', {\n\t\t\t\t\tworkflow,\n\t\t\t\t\tlineage: [...current],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst depth = deriveWorkflowDepth(current)\n\t\t\t// Reject over-depth or re-entry before the agent, tool registry, or runner becomes active.\n\t\t\tif (depth > MAX_WORKFLOW_CHAIN) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${agent.id}' exceeds max workflow depth`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_CHAIN,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagAgent(agent.id)\n\t\t\tif (current.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${agent.id}' is already an ancestor (cycle)`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t\tlineage: [...current],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst nested = extendLineage(current, tag)\n\t\t\t// Bind the nested workflow tool with this agent appended to the immutable lineage.\n\t\t\tconst runner = options?.runner\n\t\t\tif (runner !== undefined) {\n\t\t\t\tif (agent.status === 'running') {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `agent '${agent.id}' is already running`, {\n\t\t\t\t\t\tagent: agent.id,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst workflowId = controller.task.phase.workflow.id\n\t\t\t\tconst wrapped: WorkflowDefinition = { id: workflowId, name: workflowId, phases: [] }\n\t\t\t\tagent.context.tools.add(\n\t\t\t\t\tcreateWorkflowTool(wrapped, runner, {\n\t\t\t\t\t\tlineage: nested,\n\t\t\t\t\t\t...(functions === undefined ? {} : { functions }),\n\t\t\t\t\t\t...(agents === undefined ? {} : { agents }),\n\t\t\t\t\t\t...(options?.store === undefined ? {} : { store: options.store }),\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\t\t\t// Start synchronously with the task's native per-run signal so Agent owns cancellation,\n\t\t\t// including already-aborted signals and partial-result settlement.\n\t\t\tconst generated = agent.generate({ signal: controller.signal })\n\t\t\tconst result = agentResultToJSON(await generated)\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `agent '${agent.id}' returned a non-JSON result`, {\n\t\t\t\t\tagent: agent.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn result\n\t\t}, metadata),\n\t)\n}\n\n/**\n * Composes opaque host functions and raw agents into one immutable workflow registry.\n *\n * @remarks\n * This is the target-aware composition boundary used by direct runner consumers and\n * {@link createWorkflowTool}. Opaque leaves are copied unchanged, marked agent adapters are\n * rejected from that channel, raw agents are rebound to the supplied lineage, collisions fail\n * closed, and the returned null-prototype record prevents inherited names from becoming phantom\n * Workflow handlers.\n *\n * @param runner - The native runner propagated into contextual agent adapters\n * @param options - Target lineage, opaque functions, raw agents, and native store\n * @returns A frozen null-prototype snapshot of the target workflow's callable registry\n *\n * @example\n * ```ts\n * import { createWorkflowFunctions } from '@src/core'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n *\n * const runner = createWorkflowRunner()\n * const functions = createWorkflowFunctions(runner, {\n * \tfunctions: { publish: async () => 'published' },\n * \tagents: { review: reviewAgent },\n * })\n * await runner.execute(definition, { functions })\n * ```\n */\nexport function createWorkflowFunctions(\n\trunner: WorkflowRunnerInterface,\n\toptions?: WorkflowToolOptions,\n): WorkflowRegistry {\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('workflow:')) {\n\t\tthrow new ToolboxError('TOOL', 'workflow functions lineage must end with a workflow tag')\n\t}\n\tconst functions: WorkflowRegistry =\n\t\toptions?.functions === undefined ? Object.freeze({}) : Object.freeze({ ...options.functions })\n\tconst agents: WorkflowAgents =\n\t\toptions?.agents === undefined ? Object.freeze({}) : Object.freeze({ ...options.agents })\n\tconst composed: Record<string, WorkflowFunction> = {}\n\tObject.setPrototypeOf(composed, null)\n\tfor (const [name, fn] of Object.entries(functions)) {\n\t\tif (!isFunction(fn)) {\n\t\t\tthrow new ToolboxError('TOOL', `workflow function '${name}' is not callable`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tif (isAgentFunction(fn)) {\n\t\t\tthrow new ToolboxError('TOOL', `agent function '${name}' must be supplied through agents`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tcomposed[name] = fn\n\t}\n\tfor (const [name, agent] of Object.entries(agents)) {\n\t\tif (Object.hasOwn(composed, name)) {\n\t\t\tthrow new ToolboxError('TOOL', `workflow function '${name}' collides with an agent`, {\n\t\t\t\tfunction: name,\n\t\t\t})\n\t\t}\n\t\tconst fn = createAgentFunction(agent, {\n\t\t\trunner,\n\t\t\tlineage,\n\t\t\tfunctions,\n\t\t\tagents,\n\t\t\t...(options?.store === undefined ? {} : { store: options.store }),\n\t\t})\n\t\tcomposed[name] = fn\n\t}\n\treturn Object.freeze(composed)\n}\n\n/**\n * Compiles the lenient workflow draft contract {@link createWorkflowTool} parses an authored tree\n * with — a `ContractInterface` over a {@link WorkflowDraft}, whose `id` and `name` are optional at\n * the workflow, phase, and task levels.\n *\n * @returns The compiled {@link import('./types.js').WorkflowDraft} contract\n */\nexport function createWorkflowDraftContract(): ContractInterface<WorkflowDraft> {\n\treturn createContract(workflowDraftShape)\n}\n\n/**\n * Wraps a {@link WorkflowDefinition} as an LLM-callable tool — it advertises the flat authoring\n * shape (`{ name?, steps: [{ name }] }`) as its `parameters`, and its handler completes the\n * authored blob, validates it against the strict contract, and runs it through `runner`, forwarding\n * the caller's optional named functions and native checkpoint store.\n *\n * @remarks\n * A plain `ToolManagerInterface`-compatible tool (`@orkestrel/tool`), reproducing\n * Toolbox's flat / draft / full authoring contract, strict soundness gate, and lineage guard.\n * It is also the propagation carrier\n * {@link createAgentFunction} binds onto a wrapped agent's `context.tools`: because a tool\n * handler receives only the model-supplied `args`, the immutable lineage is closed over at bind\n * time. The authored target is appended and its zero-based depth derived from workflow tags.\n *\n * **Widened authoring surface (additive — the canonical contract and runner stay strict and\n * unchanged).** A 2B model reliably calls the tool but cannot reliably emit the full nested\n * {@link WorkflowDefinition}, whose every `id` and `name` is required across an all-or-nothing\n * tree. So the tool accepts the authoring forms that follow and converges them on the same strict\n * `createWorkflowContract` gate before running (soundness preserved):\n * - the flat shape `{ name?, steps: [{ name }] }` — the advertised `parameters` (the simplest\n * form, {@link import('./helpers.js').expandSteps}'d into one one-task phase per step);\n * - a nested draft with any `id`/`name` omitted — {@link createWorkflowDraftContract}-parsed then\n * {@link import('./helpers.js').completeDraft}'d (missing ids synthesized positionally);\n * - the full nested {@link WorkflowDefinition} — the advanced escape-hatch, accepted as the draft\n * super-set.\n *\n * The universal tool-handler contract: returns the plain run summary\n * (`{ status, count, durable?, fault? }`) on success, throws a typed `ToolboxError` on Toolbox\n * boundary failures — malformed authored args (`TOOL`), or an over-deep / cyclic nested run\n * (`DEPTH`) — and preserves genuine runner `WorkflowError`s. The `ToolManagerInterface` isolates every throw into the canonical tool result's\n * top-level `error`, so nothing escapes the run. `options.lineage` is the propagation carrier\n * across a workflow → agent → workflow chain. Opaque `functions` remain host leaves; raw `agents`\n * are contextually adapted through {@link createWorkflowFunctions}; native checkpoint persistence\n * makes the final snapshot retrievable without a second Toolbox write.\n *\n * @param definition - The workflow the tool runs when called with no authored args\n * @param runner - The `WorkflowRunnerInterface` (`@orkestrel/workflow`) that executes the (nested) workflow\n * @param options - Lineage-aware functions, agents, and optional native store\n * @returns A `ToolInterface` (named {@link import('./constants.js').WORKFLOW_TOOL_NAME}) whose\n * `parameters` advertise the flat authoring schema\n *\n * @example Authoring and running a workflow through the tool with a real ToolManager\n * ```ts\n * import { createWorkflowTool } from '@orkestrel/toolbox'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createWorkflowRunner } from '@orkestrel/workflow'\n * import type { WorkflowDefinition } from '@orkestrel/workflow'\n *\n * const definition: WorkflowDefinition = { id: 'release', name: 'Release', phases: [] }\n * const runner = createWorkflowRunner()\n * const functions = {\n * \tcompile: () => 'compiled',\n * \tpublish: () => 'published',\n * }\n * const tool = createWorkflowTool(definition, runner, { functions })\n *\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * // A small model authors the simple flat shape — no ids/names required.\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'workflow',\n * \targuments: { name: 'release', steps: [{ name: 'compile' }, { name: 'publish' }] },\n * })\n * if (!result.success) throw new Error(result.error)\n * result.value // { status: 'completed', count: 2 } — the single-level envelope; no nested { id, name, value }\n * ```\n *\n * @example\n * ```ts\n * import { createWorkflowTool } from '@src/core'\n * import { createWorkflowRunner, createMemoryWorkflowStore } from '@orkestrel/workflow'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const runner = createWorkflowRunner()\n * const store = createMemoryWorkflowStore()\n * const tool = createWorkflowTool(definition, runner, { store })\n * const tools = createToolManager()\n * tools.add(tool) // authored runs now use native checkpoints through `store`\n * ```\n */\nexport function createWorkflowTool(\n\tdefinition: WorkflowDefinition,\n\trunner: WorkflowRunnerInterface,\n\toptions?: WorkflowToolOptions,\n): ToolInterface {\n\tconst strict = createWorkflowContract()\n\tconst draft = createWorkflowDraftContract()\n\tconst steps: ContractInterface<WorkflowSteps> = createContract(workflowStepsShape)\n\tconst lineage = normalizeLineage(options?.lineage)\n\tif (lineage.length > 0 && !lineage.at(-1)?.startsWith('agent:')) {\n\t\tthrow new ToolboxError('TOOL', 'workflow tool lineage must end with an agent tag')\n\t}\n\tconst functions =\n\t\toptions?.functions === undefined ? undefined : Object.freeze({ ...options.functions })\n\tconst agents = options?.agents === undefined ? undefined : Object.freeze({ ...options.agents })\n\tconst store = options?.store\n\tconst parameters = schemaToParameters(steps.schema)\n\treturn createTool({\n\t\tname: WORKFLOW_TOOL_NAME,\n\t\tdescription: WORKFLOW_TOOL_DESCRIPTION,\n\t\tsummary: WORKFLOW_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst cloned = attempt(() => cloneJSONRecord(args))\n\t\t\tif (!cloned.success) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed workflow definition', {\n\t\t\t\t\tworkflow: definition.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst owned = cloned.value\n\t\t\t// Branch on the owned args snapshot's shape (no ambient context — a tool handler gets only\n\t\t\t// `args`): empty ⇒ the wrapped definition; a `steps` array ⇒ the flat form, parsed and\n\t\t\t// expanded; otherwise the nested draft form, parsed and completed. A parse failure leaves\n\t\t\t// `target` undefined ⇒ the strict gate that follows throws `TOOL`.\n\t\t\tconst target = resolveWorkflowTarget(owned, definition, steps, draft)\n\t\t\t// The soundness gate: whatever authoring form produced `target`, it must satisfy the\n\t\t\t// strict canonical contract before it runs — the leniency never reaches the runner.\n\t\t\tif (target === undefined || !strict.is(target)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed workflow definition', {\n\t\t\t\t\tworkflow: definition.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagWorkflow(target.id)\n\t\t\tif (lineage.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `workflow '${target.id}' is already an ancestor (cycle)`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tlineage: [...lineage],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst targetLineage = extendLineage(lineage, tag)\n\t\t\tconst depth = deriveWorkflowDepth(targetLineage)\n\t\t\tif (depth > MAX_WORKFLOW_CHAIN) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `nested workflow exceeds max depth ${MAX_WORKFLOW_CHAIN}`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_CHAIN,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst registry =\n\t\t\t\tfunctions === undefined && agents === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: createWorkflowFunctions(runner, {\n\t\t\t\t\t\t\tlineage: targetLineage,\n\t\t\t\t\t\t\t...(functions === undefined ? {} : { functions }),\n\t\t\t\t\t\t\t...(agents === undefined ? {} : { agents }),\n\t\t\t\t\t\t\t...(store === undefined ? {} : { store }),\n\t\t\t\t\t\t})\n\t\t\tconst result = await runner.execute(target, {\n\t\t\t\t...(registry === undefined ? {} : { functions: registry }),\n\t\t\t\t...(store === undefined ? {} : { store }),\n\t\t\t})\n\t\t\treturn summarizeWorkflow(result)\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable workspace-editing tool — it advertises the `operation`-discriminated union\n * ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its handler parses\n * the model-supplied args against that contract and dispatches the matched operation against the\n * manager's active workspace, returning the plain result.\n *\n * @remarks\n * Manager-driven: every edit / read op (read / list / has / search / replace / write / splice /\n * prepend / append / move / remove) targets `manager.active`, so the model edits whichever\n * workspace is active and a host can re-point it (`WorkspaceManagerInterface.switch`) between\n * turns. The registry ops make the model self-sufficient: `workspaces` lists the registered\n * workspaces (each `{ id, files, active }`) so it can discover an id, and `switch` re-points the\n * active workspace by id (lenient — an unknown id is a no-op reporting `switched: false`, never a\n * throw).\n *\n * No-active rule (the ergonomic seam): a writing op (write / splice / prepend / append / move /\n * remove / replace) run when `manager.active` is `undefined` auto-creates and activates a default\n * workspace (`manager.add()`) so the model can start writing; a pure-read op (read / list /\n * has / search) against no active workspace returns the empty result (`undefined` / `[]` /\n * `false`), never creating one and never throwing.\n *\n * The handler conforms to the universal tool-handler contract: it `contract.parse`s\n * the args, throws a `TOOL` `ToolboxError` when no operation arm matched (a malformed / unknown\n * operation), else `switch`es on `op.operation` and returns the plain result — letting a\n * `WorkspaceError` raised by the live workspace (`MISSING` / `MODALITY` / `PATTERN` / `RANGE`)\n * propagate uncaught. The range edit is the flat `'splice'` op: its flat caret integers are\n * reassembled into a `Range` (`@orkestrel/workspace`) by `rangeOf` and fed to the workspace's\n * ranged `write`.\n *\n * @param options - `manager` (drive directly) or `store` (build a manager over it); neither ⇒\n * an in-memory-backed manager (see {@link import('./types.js').WorkspaceToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').WORKSPACE_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createWorkspaceTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createWorkspaceTool() // in-memory workspace, no persistence\n * const tools = createToolManager()\n * tools.add(tool)\n * ```\n */\nexport function createWorkspaceTool(options?: WorkspaceToolOptions): ToolInterface {\n\tconst manager: WorkspaceManagerInterface =\n\t\toptions?.manager ??\n\t\tcreateWorkspaceManager(options?.store === undefined ? undefined : { store: options.store })\n\tconst contract: ContractInterface<WorkspaceOperation> = createContract(workspaceToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options?.name ?? WORKSPACE_TOOL_NAME,\n\t\tdescription: options?.description ?? WORKSPACE_TOOL_DESCRIPTION,\n\t\tsummary: WORKSPACE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\texecute(args) {\n\t\t\tconst op = contract.parse(args)\n\t\t\tif (op === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'unknown or malformed operation', { args })\n\t\t\t}\n\t\t\t// Registry ops act on the manager, not a workspace — handle them first.\n\t\t\tif (op.operation === 'workspaces') {\n\t\t\t\tconst activeId = manager.active?.id\n\t\t\t\treturn manager.workspaces().map((workspace) => ({\n\t\t\t\t\tid: workspace.id,\n\t\t\t\t\tfiles: workspace.count,\n\t\t\t\t\tactive: workspace.id === activeId,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tif (op.operation === 'switch') {\n\t\t\t\tconst switched = manager.switch(op.id)\n\t\t\t\t// Lenient: an unknown id leaves `active` unchanged and reports `switched: false`.\n\t\t\t\treturn switched === undefined\n\t\t\t\t\t? { id: op.id, switched: false }\n\t\t\t\t\t: { id: switched.id, switched: true, files: switched.count }\n\t\t\t}\n\t\t\t// Edit and read ops target the active workspace. A writing op auto-creates and activates a\n\t\t\t// default workspace when none is active (the no-active ergonomic seam) — while a pure-read\n\t\t\t// op returns the empty result against no active workspace rather than creating one.\n\t\t\tconst active = manager.active\n\t\t\tswitch (op.operation) {\n\t\t\t\tcase 'read':\n\t\t\t\t\treturn active?.read(op.path)\n\t\t\t\tcase 'list':\n\t\t\t\t\treturn (active?.files() ?? []).map((file) => ({\n\t\t\t\t\t\tpath: file.path,\n\t\t\t\t\t\tstate: file.state,\n\t\t\t\t\t\tsize: file.size,\n\t\t\t\t\t\tlines: file.lines,\n\t\t\t\t\t\tkind: isTextContent(file.content) ? 'text' : 'binary',\n\t\t\t\t\t}))\n\t\t\t\tcase 'has':\n\t\t\t\t\treturn active?.has(op.path) ?? false\n\t\t\t\tcase 'search':\n\t\t\t\t\treturn (\n\t\t\t\t\t\tactive?.search(op.query, {\n\t\t\t\t\t\t\t...(op.regex === undefined ? {} : { regex: op.regex }),\n\t\t\t\t\t\t\t...(op.sensitive === undefined ? {} : { sensitive: op.sensitive }),\n\t\t\t\t\t\t\t...(op.limit === undefined ? {} : { limit: op.limit }),\n\t\t\t\t\t\t}) ?? []\n\t\t\t\t\t)\n\t\t\t\tcase 'replace': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn workspace.replace(op.query, op.replacement, {\n\t\t\t\t\t\t...(op.regex === undefined ? {} : { regex: op.regex }),\n\t\t\t\t\t\t...(op.sensitive === undefined ? {} : { sensitive: op.sensitive }),\n\t\t\t\t\t\t...(op.limit === undefined ? {} : { limit: op.limit }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcase 'write': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.write(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'splice': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.write(\n\t\t\t\t\t\top.path,\n\t\t\t\t\t\top.content,\n\t\t\t\t\t\trangeOf(op.fromLine, op.fromColumn, op.toLine, op.toColumn),\n\t\t\t\t\t)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'prepend': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.prepend(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'append': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\tworkspace.append(op.path, op.content)\n\t\t\t\t\treturn { path: op.path, state: workspace.file(op.path)?.state }\n\t\t\t\t}\n\t\t\t\tcase 'move': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn { from: op.from, to: op.to, moved: workspace.move(op.from, op.to) }\n\t\t\t\t}\n\t\t\t\tcase 'remove': {\n\t\t\t\t\tconst workspace = active ?? manager.add()\n\t\t\t\t\treturn { path: op.path, removed: workspace.remove(op.path) }\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable sub-agent delegation tool — it resolves a live, seeded `AgentInterface`\n * from `registry` and runs it to completion for one delegated `task`.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').agentToolShape}, assembles an `AgentJobInput` (`task` seeds the\n * sub-agent's conversation as a single `user` message; `provider` / `tools` / `system` fall\n * back to the tool's own {@link import('./types.js').AgentToolOptions} defaults), rehydrates the sub-agent through\n * `registry.build`, runs it with `agent.generate()`, and returns the settled\n * `AgentResult.content` string (the sub-agent's final text). A missing / unresolvable `provider`, or a malformed call, throws a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}; a delegation that would exceed\n * {@link import('./constants.js').AGENT_TOOL_DEPTH}, or re-enter an already-delegated agent (a\n * cycle), throws a typed `DEPTH` {@link import('./errors.js').ToolboxError}, each isolated\n * by the `ToolManagerInterface` into the canonical tool result's top-level `error`.\n *\n * `AgentInterface` (`@orkestrel/agent`) exposes no teardown method — a bound sub-agent's\n * lifetime is the single `generate()` call this handler awaits; there is nothing to release\n * afterwards (unlike a store-backed resource, its state lives entirely in the resolved\n * `AgentContextInterface`, owned by the caller's registry).\n *\n * @param registry - The `AgentRegistryInterface` a delegated job resolves against (providers,\n * tools, authorities, schedulers, and the `build` rehydration seam)\n * @param options - Delegation defaults, depth/ancestry bookkeeping, and advertised overrides\n * (see {@link import('./types.js').AgentToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').AGENT_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createAgentTool } from '@src/core'\n * import { createAgentRegistry } from '@orkestrel/agent'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const registry = createAgentRegistry({ providers: { openai: myProvider } })\n * const tool = createAgentTool(registry, { provider: 'openai' })\n * const tools = createToolManager()\n * tools.add(tool) // a model can now delegate a task to a sub-agent\n * ```\n */\nexport function createAgentTool(\n\tregistry: AgentRegistryInterface,\n\toptions?: AgentToolOptions,\n): ToolInterface {\n\tconst contract = createContract(agentToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst depth = options?.depth ?? 0\n\tconst ancestry = options?.ancestry ?? []\n\treturn createTool({\n\t\tname: options?.name ?? AGENT_TOOL_NAME,\n\t\tdescription: options?.description ?? AGENT_TOOL_DESCRIPTION,\n\t\tsummary: AGENT_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed agent-delegation call', { args })\n\t\t\t}\n\t\t\tconst provider = call.provider ?? options?.provider\n\t\t\tif (provider === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'no provider resolved for the delegated agent', {\n\t\t\t\t\ttask: call.task,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (depth + 1 > AGENT_TOOL_DEPTH) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `delegation exceeds max agent depth ${AGENT_TOOL_DEPTH}`, {\n\t\t\t\t\tprovider,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: AGENT_TOOL_DEPTH,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = tagAgent(provider)\n\t\t\tif (ancestry.includes(tag)) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `agent '${provider}' is already an ancestor (cycle)`, {\n\t\t\t\t\tprovider,\n\t\t\t\t\tancestry: [...ancestry],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tools = call.tools ?? options?.tools\n\t\t\tconst system = call.system ?? options?.system\n\t\t\tconst agent = registry.build({\n\t\t\t\tprovider,\n\t\t\t\tmessages: [{ role: 'user', content: call.task }],\n\t\t\t\t...(system === undefined ? {} : { system }),\n\t\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t})\n\t\t\tconst result = await agent.generate()\n\t\t\tif (options?.store !== undefined) {\n\t\t\t\tconst active = agent.context.conversations.active\n\t\t\t\tif (active !== undefined) await options.store.set(active.snapshot())\n\t\t\t}\n\t\t\treturn result.content\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable tool that returns the full `description` of another registered tool by\n * name — the counterpart to the lean `summary` the other tools in this package advertise.\n *\n * @remarks\n * `ToolManagerInterface.definitions()` (`@orkestrel/tool`) advertises `tool.summary ??\n * tool.description` — a lean one-sentence summary stands in for a tool's full teaching\n * description when `summary` is set, keeping the advertised tool list compact for a small model.\n * This tool is the on-demand expansion seam: given a registered tool's `name`, it looks the tool\n * up through `tools.tool(name)` and returns its full `description` (falling back to `summary` when a\n * tool has no `description` of its own, then a placeholder when it has neither).\n *\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').describeToolShape}, returns the plain description string on\n * success, throws a typed `TOOL` {@link import('./errors.js').ToolboxError} on a malformed call\n * or an unknown tool name.\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/tool`) whose registered tools this\n * tool can describe\n * @returns A `ToolInterface` (named {@link import('./constants.js').DESCRIBE_TOOL_NAME})\n *\n * @example\n * ```ts\n * import { createDescribeTool, createWorkflowTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tools = createToolManager()\n * tools.add(createWorkflowTool(definition, runner))\n * tools.add(createDescribeTool(tools))\n * const full = await tools.execute({ id: '1', name: 'describe', arguments: { name: 'workflow' } })\n * full.value // the workflow tool's full teaching description\n * ```\n */\nexport function createDescribeTool(tools: ToolManagerInterface): ToolInterface {\n\tconst contract = createContract(describeToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: DESCRIBE_TOOL_NAME,\n\t\tdescription: DESCRIBE_TOOL_DESCRIPTION,\n\t\tsummary: DESCRIBE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed describe call', { args })\n\t\t\t}\n\t\t\tconst tool = tools.tool(call.name)\n\t\t\tif (tool === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', `unknown tool '${call.name}'`, { name: call.name })\n\t\t\t}\n\t\t\treturn tool.description ?? tool.summary ?? '<no description>'\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable form tool — the ask side of the terminal seam. It asks a multi-field form\n * and blocks until the addressed terminal answers, returning the resolved values record.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').promptToolShape}, parses the call's schema through\n * `@orkestrel/form`, constructs the live form, and passes it to `TerminalManagerInterface.ask`.\n * `from` is fixed at construction\n * ({@link import('./types.js').PromptToolOptions.from}) — never read from the model-supplied\n * args — so a model cannot spoof which terminal is asking. A form cycle rejects with\n * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`\n * {@link import('./errors.js').ToolboxError}; an expired form re-surfaces as `EXPIRE`; an\n * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal\n * and how many brokers the manager holds (`manager.count`). A schema `parseForm` refuses — an\n * unknown control, a duplicate field name, a `'select'` or `'checkbox'` field without usable\n * `choices` — throws a typed `TOOL` error up front, so a malformed schema never parks as a form\n * nobody can answer.\n *\n * @param options - The live manager, the fixed `from` identity, and advertised overrides (see\n * {@link import('./types.js').PromptToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').PROMPT_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createPromptTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createTerminalManager } from '@orkestrel/terminal'\n *\n * const manager = createTerminalManager()\n * manager.add('agent')\n * manager.add('reviewer')\n * const tool = createPromptTool({ manager, from: 'agent' })\n * const tools = createToolManager()\n * tools.add(tool) // the agent can now ask 'reviewer' and block for the answer\n * ```\n */\nexport function createPromptTool(options: PromptToolOptions): ToolInterface {\n\tconst contract = createContract(promptToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options.name ?? PROMPT_TOOL_NAME,\n\t\tdescription: options.description ?? PROMPT_TOOL_DESCRIPTION,\n\t\tsummary: PROMPT_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed ask call', { args })\n\t\t\t}\n\t\t\tconst schema = parseForm(call.schema)\n\t\t\tif (schema === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed form schema', { schema: call.schema })\n\t\t\t}\n\t\t\tfor (const field of schema.fields) {\n\t\t\t\tif (\n\t\t\t\t\t(field.control === 'select' || field.control === 'checkbox') &&\n\t\t\t\t\t!field.choices.some((choice) => choice.disabled !== true)\n\t\t\t\t) {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'TOOL',\n\t\t\t\t\t\t`${field.control} field '${field.name}' has no enabled choices`,\n\t\t\t\t\t\t{ control: field.control, field: field.name },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await options.manager.ask(options.from, call.to, createForm(schema))\n\t\t\t} catch (error) {\n\t\t\t\tif (isFormError(error) && error.code === 'ABANDONED') {\n\t\t\t\t\tthrow new ToolboxError('EXPIRE', `form to '${call.to}' expired before it was answered`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst code = inferTerminalCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tif (code === 'DEADLOCK') {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'DEADLOCK',\n\t\t\t\t\t\t`asking '${call.to}' would create a form cycle`,\n\t\t\t\t\t\tisTerminalError(error) ? error.context : { from: options.from, to: call.to },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (code === 'EXPIRE') {\n\t\t\t\t\tthrow new ToolboxError('EXPIRE', `form to '${call.to}' expired before it was answered`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (isTerminalError(error) && error.code === 'TARGET') {\n\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown terminal '${call.to}'`, {\n\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t\tcount: options.manager.count,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tthrow new ToolboxError('TOOL', `asking '${call.to}' failed`, { to: call.to })\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds an LLM-callable answer tool — the answer side of the terminal seam. It lists the forms\n * addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of them by id.\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`\n * returns a compact list (`{ id, from, schema }`) of every form addressed to `to`.\n * `'answer'` looks the form up by `id`, narrows the supplied `values` through `@orkestrel/form`,\n * and applies it through\n * `TerminalManagerInterface.answer` — a rejected / unknown / unresolvable outcome\n * (`TerminalAnswerResult.error`) re-surfaces as a typed `ANSWER` `ToolboxError`; success returns\n * `{ answered: id }`. `to` is fixed at construction\n * ({@link import('./types.js').AnswerToolOptions.to}) — never read from the model-supplied args —\n * so a model cannot spoof which terminal it is answering for. Concurrent answerers racing on one\n * endpoint are first-write-wins — a late answer to an already-settled form returns a typed\n * `ANSWER` `ToolboxError` (surfaced as a 422 over HTTP).\n *\n * @param options - The live manager, the fixed `to` identity, and advertised overrides (see\n * {@link import('./types.js').AnswerToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').ANSWER_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createAnswerTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n * import { createTerminalManager } from '@orkestrel/terminal'\n *\n * const manager = createTerminalManager()\n * manager.add('reviewer')\n * const tool = createAnswerTool({ manager, to: 'reviewer' })\n * const tools = createToolManager()\n * tools.add(tool) // the reviewer terminal can now list/answer forms addressed to it\n * ```\n */\nexport function createAnswerTool(options: AnswerToolOptions): ToolInterface {\n\tconst contract = createContract(answerToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options.name ?? ANSWER_TOOL_NAME,\n\t\tdescription: options.description ?? ANSWER_TOOL_DESCRIPTION,\n\t\tsummary: ANSWER_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed answer call', { args })\n\t\t\t}\n\t\t\tif (call.operation === 'pending') {\n\t\t\t\treturn options.manager.pending(options.to).map((form) => ({\n\t\t\t\t\tid: form.id,\n\t\t\t\t\tfrom: form.from,\n\t\t\t\t\tschema: form.schema,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tconst form = options.manager.pending(options.to).find((entry) => entry.id === call.id)\n\t\t\tif (form === undefined) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `unknown form '${call.id}'`, {\n\t\t\t\t\tid: call.id,\n\t\t\t\t\treason: 'unknown',\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (!isFormValues(call.values)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed form values', { values: call.values })\n\t\t\t}\n\t\t\tconst result = options.manager.answer(options.to, call.id, call.values)\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t'ANSWER',\n\t\t\t\t\t`failed to answer form '${call.id}': ${result.error.reason}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\treason: result.error.reason,\n\t\t\t\t\t\t...(result.error.reason === 'rejected' ? { errors: result.error.errors } : {}),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { answered: call.id }\n\t\t},\n\t})\n}\n\n// === Database definition stores\n\n/**\n * Creates the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database\n * definitions, the default store the database and relation tools persist their `DatabaseDefinition`\n * configs through.\n *\n * @returns A {@link DefinitionStoreInterface}\n *\n * @example\n * ```ts\n * import { createMemoryDefinitionStore } from '@src/core'\n *\n * const store = createMemoryDefinitionStore()\n * ```\n */\nexport function createMemoryDefinitionStore(): DefinitionStoreInterface {\n\treturn new MemoryDefinitionStore()\n}\n\n/**\n * Creates a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database`\n * layer — the driver-pluggable twin of {@link createMemoryDefinitionStore}, storing each\n * database's definition as one opaque JSON column.\n *\n * @param driver - The {@link DriverInterface} backing the table (default an in-memory driver)\n * @returns A {@link DefinitionStoreInterface}\n *\n * @example\n * ```ts\n * import { createDatabaseDefinitionStore } from '@src/core'\n *\n * const store = createDatabaseDefinitionStore() // in-memory by default\n * ```\n */\nexport function createDatabaseDefinitionStore(\n\tdriver: DriverInterface = createMemoryDriver(),\n): DefinitionStoreInterface {\n\t// The definition is stored as one opaque JSON column (`rawShape`), so the row infers flat —\n\t// `{ id: string; definition: unknown }` = DatabaseDefinitionRow.\n\tconst columns = { id: stringShape(), definition: rawShape({}) }\n\tconst database = createDatabase({ driver, tables: { definitions: columns } })\n\tconst table: TableInterface<DatabaseDefinitionRow> = database.table('definitions')\n\treturn new DatabaseDefinitionStore(table)\n}\n\n// === Database tool\n\n/**\n * Builds an LLM-callable database tool — it creates, queries, and mutates `@orkestrel/database`\n * databases through one `operation`-discriminated call (matching\n * {@link createWorkspaceTool}'s single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').databaseToolShape}, dispatches to the matching operation, and\n * returns a plain result on success. A database is resolved lazily and cached for the tool's\n * lifetime — `'create'` mints one from `tables` ({@link import('./compilers.js').expandTables}) and\n * a registered `driver` key ({@link import('./types.js').DatabaseToolOptions.drivers}, default\n * `{ memory: () => createMemoryDriver() }`); any other operation addressing an uncached id falls\n * back to {@link import('./types.js').DatabaseToolOptions.store} (an unknown id throws a typed\n * `TOOL` {@link import('./errors.js').ToolboxError}). When a `store` is configured, `'create'`\n * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.\n *\n * `'records'` clamps its `query` to\n * {@link import('./types.js').DatabaseToolOptions.limit} (default\n * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) through\n * {@link import('./helpers.js').clampQuery}, reporting `truncated` when storage held more rows\n * than the cap. Every operation's `query` is normalized through\n * {@link import('./helpers.js').normalizeQuery} (defaults an omitted condition `connector` to `'and'`).\n * When {@link import('./types.js').DatabaseToolOptions.readonly} is `true`, every mutating\n * operation throws a typed `TOOL` `ToolboxError` before doing anything. A configured\n * {@link import('./types.js').DatabaseToolOptions.timeout} is passed as a fresh\n * `AbortSignal.timeout(timeout)` only to table operations whose current database API accepts\n * operation options (`records`, `count`, `aggregate`, `add`, `set`, `update`, and `remove`). It is\n * not an outer deadline for resolution, construction, schema inspection, `get`, or `close`. A typed `@orkestrel/database`\n * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `ToolboxError` carrying the\n * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`\n * ({@link import('./helpers.js').inferDatabaseCode}); an `ToolboxError` thrown by this tool's own\n * guards passes through unwrapped.\n *\n * A lazily re-minted database over the default in-memory driver yields an empty database — only\n * the {@link import('./types.js').DatabaseDefinition} schema persists in `store`, never rows;\n * durable rows need a persistent driver factory registered in\n * {@link import('./types.js').DatabaseToolOptions.drivers}. `'destroy'` closes whatever handle is\n * cached for the id, including an embedder-supplied\n * {@link import('./types.js').DatabaseToolOptions.databases} handle — the embedder relinquishes\n * that handle's lifecycle to this tool for any id it wires in. This tool assumes the\n * single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent calls\n * against one id are not serialized by this tool. `'get'` is uncapped by\n * {@link import('./types.js').DatabaseToolOptions.limit} (bounded only by the caller's `key` array\n * size), unlike `'records'` / `'find'` / `'links'`.\n *\n * @param options - The tool's configuration (see {@link import('./types.js').DatabaseToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').DATABASE_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createDatabaseTool } from '@src/core'\n *\n * const tool = createDatabaseTool()\n * await tool.execute(\n * \t{\n * \t\toperation: 'create',\n * \t\tid: 'shop',\n * \t\ttables: { products: { columns: { name: 'string', price: 'number' } } },\n * \t},\n * \t{ signal: new AbortController().signal },\n * )\n * ```\n */\nexport function createDatabaseTool(options: DatabaseToolOptions = {}): ToolInterface {\n\tif (\n\t\toptions.timeout !== undefined &&\n\t\t(options.timeout < 0 || !isNumber(options.timeout) || !Number.isSafeInteger(options.timeout))\n\t) {\n\t\tthrow new ToolboxError('TOOL', 'database timeout must be a nonnegative safe integer', {\n\t\t\ttimeout: options.timeout,\n\t\t})\n\t}\n\tconst contract = createContract(databaseToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst handles = new Map<string, DatabaseInterface>(Object.entries(options.databases ?? {}))\n\tconst drivers = options.drivers ?? { memory: createMemoryDriver }\n\tconst generator = options.generator\n\tconst cap = options.limit ?? DATABASE_TOOL_LIMIT\n\tconst store = options.store\n\tconst resolver =\n\t\tstore === undefined\n\t\t\t? new DatabaseResolver(handles, drivers, generator)\n\t\t\t: new DatabaseResolver(handles, drivers, generator, store)\n\n\treturn createTool({\n\t\tname: options.name ?? DATABASE_TOOL_NAME,\n\t\tdescription: options.description ?? DATABASE_TOOL_DESCRIPTION,\n\t\tsummary: DATABASE_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed database call', { args })\n\t\t\t}\n\t\t\tif (options.readonly === true && DATABASE_TOOL_MUTATIONS.includes(call.operation)) {\n\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t'TOOL',\n\t\t\t\t\t`operation '${call.operation}' is disabled in readonly mode`,\n\t\t\t\t\t{ operation: call.operation },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst read: Readonly<{ signal?: AbortSignal }> | undefined =\n\t\t\t\toptions.timeout === undefined ? undefined : { signal: AbortSignal.timeout(options.timeout) }\n\t\t\ttry {\n\t\t\t\tswitch (call.operation) {\n\t\t\t\t\tcase 'create': {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tresolver.has(call.id) ||\n\t\t\t\t\t\t\t(store !== undefined && (await store.get(call.id)) !== undefined)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new ToolboxError('TOOL', `database '${call.id}' already exists`, {\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst name = call.driver ?? 'memory'\n\t\t\t\t\t\tconst factory = drivers[name]\n\t\t\t\t\t\tif (factory === undefined) {\n\t\t\t\t\t\t\tthrow new ToolboxError('TOOL', `unknown driver '${name}'`, {\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst tables = call.tables\n\t\t\t\t\t\tconst primary = call.primary\n\t\t\t\t\t\tconst indexes = call.indexes\n\t\t\t\t\t\tconst version = call.version\n\t\t\t\t\t\tconst handle = createDatabase({\n\t\t\t\t\t\t\tdriver: factory(),\n\t\t\t\t\t\t\ttables: expandTables(tables),\n\t\t\t\t\t\t\tname: call.id,\n\t\t\t\t\t\t\t...(primary === undefined ? {} : { primary }),\n\t\t\t\t\t\t\t...(indexes === undefined ? {} : { indexes }),\n\t\t\t\t\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t\t\t\t\t...(generator === undefined ? {} : { generator }),\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst definition: DatabaseDefinition = {\n\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\ttables,\n\t\t\t\t\t\t\t...(primary === undefined ? {} : { primary }),\n\t\t\t\t\t\t\t...(indexes === undefined ? {} : { indexes }),\n\t\t\t\t\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (store !== undefined) await store.set(definition)\n\t\t\t\t\t\tresolver.set(call.id, handle)\n\t\t\t\t\t\treturn { id: call.id, tables: Object.keys(tables) }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'tables': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst tables = Object.keys(handle.export()).map((name) => {\n\t\t\t\t\t\t\tconst table = handle.table(name)\n\t\t\t\t\t\t\treturn { name, primary: table.primary, columns: table.contract.schema }\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn { tables }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'get': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst rows = await table.get(keys)\n\t\t\t\t\t\treturn many ? { rows } : { row: rows[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'records': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst { query: probe, limit } = clampQuery(normalizeQuery(call.query), cap)\n\t\t\t\t\t\tconst rows = await table.records(probe, read)\n\t\t\t\t\t\tconst truncated = rows.length > limit\n\t\t\t\t\t\tconst sliced = rows.slice(0, limit)\n\t\t\t\t\t\treturn { rows: sliced, count: sliced.length, truncated, limit }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'count': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst count = await table.count(normalizeQuery(call.query), read)\n\t\t\t\t\t\treturn { count }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'aggregate': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst value = await table.aggregate(\n\t\t\t\t\t\t\tcall.function,\n\t\t\t\t\t\t\tcall.column,\n\t\t\t\t\t\t\tnormalizeQuery(call.query),\n\t\t\t\t\t\t\tread,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn { value }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'add': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.row)\n\t\t\t\t\t\tconst rows = isArray(call.row) ? call.row : [call.row]\n\t\t\t\t\t\tconst keys = await table.add(rows, read)\n\t\t\t\t\t\treturn many ? { keys } : { key: keys[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'set': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.row)\n\t\t\t\t\t\tconst rows = isArray(call.row) ? call.row : [call.row]\n\t\t\t\t\t\tconst keys = await table.set(rows, read)\n\t\t\t\t\t\treturn many ? { keys } : { key: keys[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'update': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst changes = call.changes\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst updated = await table.update(keys, changes, read)\n\t\t\t\t\t\treturn many ? { updated } : { updated: updated[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'remove': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst table = handle.table(call.table)\n\t\t\t\t\t\tconst many = isArray(call.key)\n\t\t\t\t\t\tconst keys = isArray(call.key) ? call.key : [call.key]\n\t\t\t\t\t\tconst removed = await table.remove(keys, read)\n\t\t\t\t\t\treturn many ? { removed } : { removed: removed[0] }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'destroy': {\n\t\t\t\t\t\tconst cached = resolver.get(call.id)\n\t\t\t\t\t\tconst persisted =\n\t\t\t\t\t\t\tstore !== undefined && cached === undefined\n\t\t\t\t\t\t\t\t? (await store.get(call.id)) !== undefined\n\t\t\t\t\t\t\t\t: false\n\t\t\t\t\t\tif (cached !== undefined) {\n\t\t\t\t\t\t\tawait cached.close()\n\t\t\t\t\t\t\tresolver.delete(call.id)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (store !== undefined) await store.delete(call.id)\n\t\t\t\t\t\treturn { id: call.id, destroyed: cached !== undefined || persisted }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (isToolboxError(error)) throw error\n\t\t\t\tconst code = inferDatabaseCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', isError(error) ? error.message : String(error), {\n\t\t\t\t\tcode,\n\t\t\t\t\toperation: call.operation,\n\t\t\t\t\tid: call.id,\n\t\t\t\t\t...('table' in call ? { table: call.table } : {}),\n\t\t\t\t})\n\t\t\t}\n\t\t},\n\t})\n}\n\n// === Relation tool\n\n/**\n * Builds an LLM-callable relation tool — it traverses and edits `@orkestrel/relation` relationships\n * through one `operation`-discriminated call (matching {@link createDatabaseTool}'s\n * single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').relationToolShape}, resolves the addressed\n * {@link import('@orkestrel/relation').RelationManagerInterface} — an explicit `manager` field\n * must match a key of {@link import('./types.js').RelationToolOptions.managers}, an omitted one\n * resolves to the sole registered manager, either miss throwing a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}\n * ({@link import('./helpers.js').resolveRelationManager}) — then resolves `model` against it\n * ({@link import('./helpers.js').resolveRelationModel}, same typed-`TOOL`-on-miss shape), and\n * dispatches to the matched operation, returning a plain result on success.\n *\n * `'load'` / `'find'` expand the call's flat dot-path `include` list into a live\n * `@orkestrel/relation` `Include` tree through {@link import('./helpers.js').expandInclude}, capped\n * at {@link import('./types.js').RelationToolOptions.depth} (default\n * {@link import('./constants.js').RELATION_TOOL_DEPTH}) — a path exceeding the cap, or carrying an\n * empty segment, throws a typed `TOOL` error. `'load'` dispatches on whether `key` is an array\n * (positional many-key form — an array key is read as many keys rather than one) or a single key.\n * `'find'` and `'links'` clamp their\n * result to {@link import('./types.js').RelationToolOptions.limit} (default\n * {@link import('./constants.js').RELATION_TOOL_LIMIT}), taken through\n * {@link import('./helpers.js').resolveLimit} — `'find'` probes one row past the effective limit to\n * report `truncated`; `'links'` (which has no upstream pagination) fetches the full linked-key\n * list and slices/truncates it the same way. `'link'` / `'unlink'` write / remove one `through` junction\n * row.\n *\n * A typed `@orkestrel/relation` failure (`RelationError`) re-surfaces as a typed `RELATION`\n * `ToolboxError` carrying the original {@link import('@orkestrel/relation').RelationErrorCode}\n * in `context.code`; a typed `@orkestrel/database` failure underneath it (`DatabaseError`)\n * re-surfaces as a typed `DATABASE` `ToolboxError`, mirroring {@link createDatabaseTool}'s error\n * mapping; an `ToolboxError` thrown by this tool's own guards (malformed args, an unknown\n * manager/model) passes through unwrapped.\n *\n * @param options - The tool's configuration (see {@link import('./types.js').RelationToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').RELATION_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createRelationTool } from '@src/core'\n *\n * const tool = createRelationTool({ managers: { shop: manager } })\n * await tool.execute(\n * \t{ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] },\n * \t{ signal: new AbortController().signal },\n * )\n * ```\n */\nexport function createRelationTool(options: RelationToolOptions): ToolInterface {\n\tconst contract = createContract(relationToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst depth = options.depth ?? RELATION_TOOL_DEPTH\n\tconst cap = options.limit ?? RELATION_TOOL_LIMIT\n\treturn createTool({\n\t\tname: options.name ?? RELATION_TOOL_NAME,\n\t\tdescription: options.description ?? RELATION_TOOL_DESCRIPTION,\n\t\tsummary: RELATION_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst call = contract.parse(args)\n\t\t\tif (call === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed relation call', { args })\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst manager = resolveRelationManager(options.managers, call.manager)\n\t\t\t\tconst model = resolveRelationModel(manager, call.model)\n\t\t\t\tswitch (call.operation) {\n\t\t\t\t\tcase 'load': {\n\t\t\t\t\t\tconst include = expandInclude(call.include, depth)\n\t\t\t\t\t\tif (isString(call.key) || isNumber(call.key)) {\n\t\t\t\t\t\t\tconst row = await model.load(call.key, include)\n\t\t\t\t\t\t\treturn { row }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst rows = await model.load(call.key, include)\n\t\t\t\t\t\treturn { rows }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'find': {\n\t\t\t\t\t\tconst include = expandInclude(call.include, depth)\n\t\t\t\t\t\tconst effective = resolveLimit(call.limit, cap)\n\t\t\t\t\t\tconst rows = await model.find(include, {\n\t\t\t\t\t\t\tlimit: effective + 1,\n\t\t\t\t\t\t\t...(call.offset === undefined ? {} : { offset: call.offset }),\n\t\t\t\t\t\t\t...(call.sort === undefined ? {} : { sort: call.sort }),\n\t\t\t\t\t\t\t...(call.direction === undefined ? {} : { direction: call.direction }),\n\t\t\t\t\t\t})\n\t\t\t\t\t\tconst truncated = rows.length > effective\n\t\t\t\t\t\tconst sliced = rows.slice(0, effective)\n\t\t\t\t\t\treturn { rows: sliced, count: sliced.length, truncated, limit: effective }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'link': {\n\t\t\t\t\t\tawait model.link(call.key, call.relation, call.target)\n\t\t\t\t\t\treturn { linked: true }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'unlink': {\n\t\t\t\t\t\tawait model.unlink(call.key, call.relation, call.target)\n\t\t\t\t\t\treturn { unlinked: true }\n\t\t\t\t\t}\n\t\t\t\t\tcase 'links': {\n\t\t\t\t\t\tconst effective = resolveLimit(undefined, cap)\n\t\t\t\t\t\tconst keys = await model.links(call.key, call.relation)\n\t\t\t\t\t\tconst truncated = keys.length > effective\n\t\t\t\t\t\tconst sliced = keys.slice(0, effective)\n\t\t\t\t\t\treturn { keys: sliced, count: sliced.length, truncated, limit: effective }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (isToolboxError(error)) throw error\n\t\t\t\tconst relation = inferRelationCode(error)\n\t\t\t\tif (relation !== undefined) {\n\t\t\t\t\tthrow new ToolboxError('RELATION', isError(error) ? error.message : String(error), {\n\t\t\t\t\t\tcode: relation,\n\t\t\t\t\t\toperation: call.operation,\n\t\t\t\t\t\tmodel: call.model,\n\t\t\t\t\t\t...('relation' in call ? { relation: call.relation } : {}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst database = inferDatabaseCode(error)\n\t\t\t\tif (database === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', isError(error) ? error.message : String(error), {\n\t\t\t\t\tcode: database,\n\t\t\t\t\toperation: call.operation,\n\t\t\t\t})\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * Builds a standalone LLM-callable tool that infers a JSON Schema from example values — the utility\n * half of the bridge from an existing API or database into an MCP tool (the other half,\n * {@link createEndpointTool}, wraps one concrete endpoint).\n *\n * @remarks\n * The universal tool-handler contract: validates the call args against\n * {@link import('./shapers.js').inferToolShape} (`samples` non-empty, `format` / `enum` optional\n * booleans, `candidates` an optional array), infers a schema through `@orkestrel/contract`'s\n * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` through `schemaToObject` (mirrors\n * the tool-parameters convention every other `create*Tool` factory advertises), and returns the\n * resulting parameters record. An empty `samples` array fails `inferToolShape`'s `min: 1` bound —\n * `contract.parse` returns `undefined` and the handler throws a typed `TOOL`\n * {@link import('./errors.js').ToolboxError}.\n *\n * When `candidates` is absent, the return is the bare parameters record — unchanged from before\n * this array existed. When `candidates` is present (any array, including empty), the handler\n * compiles a separate per-call contract from the raw inferred schema (through `@orkestrel/contract`'s\n * `schemaToShape`, not the `schemaToObject`-wrapped parameters — a bare-value sample checks a\n * bare-value candidate) and returns `{ parameters, checks }`, one check per candidate at the same\n * index. Every entry has a uniform shape — `{ index, valid, coercible }`, with `faults` added only\n * when `valid` is `false`: `valid` is the strict guard verdict (`checker.is(candidate)`), the\n * opposite of {@link createEndpointTool}'s enforcement, which coerces (`7` becomes `'7'` for a\n * string slot) — here a conformance report answers \"does this value conform as-is\": `7` against a\n * string slot is `valid: false`, full stop. `coercible` answers a separate question — \"would the\n * normalizing parse accept this value\", that is would {@link createEndpointTool}'s default enforcement\n * admit it (`checker.parse(candidate) !== undefined`) — computed for every candidate regardless of\n * `valid`; by the house parse/guard round-trip, a `valid: true` entry is\n * always also `coercible: true`. `@orkestrel/contract`'s `explain` mirrors the normalizing\n * `parse`'s leniency, not `is`'s strictness — so a strictly-invalid but coercible candidate (`7`\n * against a string slot) yields `{ valid: false, coercible: true, faults: [] }`: empty faults, because\n * the mismatch the normalizing parse would silently fix is not one `explain` reports. `faults`\n * therefore only ever populates for a non-coercible mismatch — a wrong type the parse can't coerce\n * (a boolean in a string slot), a missing required key, or an out-of-enum value — where\n * `coercible: false`. `checker.is` / `.parse` / `.explain` are all total over JSON-safe input — a\n * JSON-safe hostile candidate (a `__proto__`-carrying object, deeply nested data) reaches each of them\n * and yields a bounded, non-throwing per-candidate verdict; a non-JSON-safe candidate (for example a\n * throwing-getter `Proxy`) never reaches the checker at all — it fails the outer `args` parse\n * against {@link import('./shapers.js').inferToolShape} and rejects the whole call with the same\n * `TOOL` {@link import('./errors.js').ToolboxError} a malformed `samples`/`format`/`enum` throws,\n * with no per-candidate verdict produced.\n *\n * @param options - Advertised `name` / `description` overrides (see\n * {@link import('./types.js').InferToolOptions})\n * @returns A `ToolInterface` (named {@link import('./constants.js').INFER_TOOL_NAME} by default)\n *\n * @example\n * ```ts\n * import { createInferTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createInferTool()\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'infer',\n * \targuments: { samples: [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bob' }] },\n * })\n * // result.value -> { type: 'object', properties: { id: {...}, name: {...} }, ... }\n *\n * // with candidates, the result is wrapped with per-candidate verdicts\n * const checked = await tools.execute({\n * \tid: 'call-2',\n * \tname: 'infer',\n * \targuments: {\n * \t\tsamples: [{ id: 1, name: 'Ada' }],\n * \t\tcandidates: [{ id: 2, name: 'Bob' }, { id: 'x', name: 'Cy' }],\n * \t},\n * })\n * // checked.value -> { parameters: {...}, checks: [\n * // { index: 0, valid: true, coercible: true },\n * // { index: 1, valid: false, coercible: false, faults: [...] },\n * // ] }\n * ```\n */\nexport function createInferTool(options?: InferToolOptions): ToolInterface {\n\tconst contract = createContract(inferToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\treturn createTool({\n\t\tname: options?.name ?? INFER_TOOL_NAME,\n\t\tdescription: options?.description ?? INFER_TOOL_DESCRIPTION,\n\t\tsummary: INFER_TOOL_SUMMARY,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\tasync execute(args) {\n\t\t\tconst parsed = contract.parse(args)\n\t\t\tif (parsed === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed infer arguments', { args })\n\t\t\t}\n\t\t\tconst schema = samplesToSchema(parsed.samples, {\n\t\t\t\tformat: parsed.format ?? false,\n\t\t\t\tenum: parsed.enum ?? false,\n\t\t\t})\n\t\t\tconst result = schemaToParameters(schemaToObject(schema))\n\t\t\tif (result === undefined) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'could not infer a schema', { args })\n\t\t\t}\n\t\t\tif (parsed.candidates === undefined) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t\tconst checker = createContract(schemaToShape(schema))\n\t\t\tconst checks = parsed.candidates.map((candidate, index) => {\n\t\t\t\tconst valid = checker.is(candidate)\n\t\t\t\tconst coercible = checker.parse(candidate) !== undefined\n\t\t\t\treturn valid\n\t\t\t\t\t? { index, valid, coercible }\n\t\t\t\t\t: { index, valid, coercible, faults: checker.explain(candidate) }\n\t\t\t})\n\t\t\treturn { parameters: result, checks }\n\t\t},\n\t})\n}\n\n/**\n * Wraps one concrete endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable\n * `ToolInterface` — the endpoint half of the bridge from an existing API or database into an MCP\n * tool (the other half, {@link createInferTool}, is a standalone inference utility).\n *\n * @remarks\n * `parameters` is inferred once at construction from `definition.samples` through\n * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s\n * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` through `schemaToObject` —\n * the same object-rooted schema is both the advertised `parameters` and, by default\n * ({@link import('./types.js').EndpointToolOptions.validate} `true`), the enforced contract:\n * `@orkestrel/contract`'s `schemaToShape` compiles it once (through `createContract`) into a\n * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.execute` — a\n * normalizing parse, not a strict type check: a scalar is coerced to its inferred type where the\n * house parsers coerce (a number to/from a numeric string, a boolean from `'1'`/`'0'`/`'true'`/\n * `'false'`/`1`/`0`), so `definition.execute` receives the coerced value (for example `7` sent for a\n * string slot arrives as `'7'`), not the raw call value. A call whose `args` fails to parse into\n * a record — a required key missing, or a value not coercible to its slot's type — throws a\n * typed `TOOL` {@link import('./errors.js').ToolboxError} carrying the compiled contract's\n * structured `explain` faults, and `definition.execute` is never called. `format` annotations are\n * never asserted, and a key outside the closed inferred schema is silently dropped rather than\n * rejected (see {@link import('./types.js').EndpointToolOptions.validate}). With\n * `validate: false`, the tool's `execute` passes through the model-supplied `args` to\n * `definition.execute` without re-validation — the raw-passthrough opt-out. The execution context\n * the tool's `execute` receives reaches `definition.execute` unchanged whichever way `args` are\n * handled, so a handler that reads `context.signal` observes the caller's cancellation. Either way,\n * the definition's return flows back as the tool call's plain result; a throw propagates uncaught,\n * isolated by the `ToolManagerInterface` (`@orkestrel/tool`) into the canonical error envelope\n * — never caught or re-wrapped here.\n *\n * @param definition - The endpoint's identity, non-empty samples, and local handler (see\n * {@link import('./types.js').EndpointDefinition})\n * @param options - Construction-time inference tuning and the validate opt-out (see\n * {@link import('./types.js').EndpointToolOptions})\n * @returns A `ToolInterface` named `definition.name`\n *\n * @example\n * ```ts\n * import { createEndpointTool } from '@src/core'\n * import { createToolManager } from '@orkestrel/tool'\n *\n * const tool = createEndpointTool({\n * \tname: 'lookupUser',\n * \tdescription: 'Look up a user by id.',\n * \tsamples: [{ id: '1', name: 'Ada' }, { id: '2', name: 'Bob' }],\n * \texecute: (args) => ({ id: args.id, name: 'Ada' }),\n * })\n * const tools = createToolManager()\n * tools.add(tool)\n *\n * // conforming args (all required keys present) parse and reach the definition's `execute`\n * const result = await tools.execute({\n * \tid: 'call-1',\n * \tname: 'lookupUser',\n * \targuments: { id: '1', name: 'Ada' },\n * })\n * // result.value -> { id: '1', name: 'Ada' }\n *\n * // a nonconforming call (id is not coercible to the required string) is rejected before\n * // the definition's `execute` runs\n * const rejected = await tools.execute({\n * \tid: 'call-2',\n * \tname: 'lookupUser',\n * \targuments: { id: true, name: 'Ada' },\n * })\n * // rejected.error -> the TOOL ToolboxError message\n * ```\n */\nexport function createEndpointTool(\n\tdefinition: EndpointDefinition,\n\toptions?: EndpointToolOptions,\n): ToolInterface {\n\tif (definition.samples.length === 0) {\n\t\tthrow new ToolboxError('TOOL', 'endpoint requires at least one sample', {\n\t\t\tname: definition.name,\n\t\t})\n\t}\n\tconst objectSchema = schemaToObject(\n\t\tsamplesToSchema(definition.samples, {\n\t\t\tformat: options?.format ?? false,\n\t\t\tenum: options?.enum ?? false,\n\t\t}),\n\t)\n\tconst parameters = schemaToParameters(objectSchema)\n\tconst validate = options?.validate ?? true\n\tif (!validate) {\n\t\treturn createTool({\n\t\t\tname: definition.name,\n\t\t\tdescription: definition.description,\n\t\t\t...(parameters === undefined ? {} : { parameters }),\n\t\t\texecute(args, context) {\n\t\t\t\treturn definition.execute(args, context)\n\t\t\t},\n\t\t})\n\t}\n\tconst contract = createContract(schemaToShape(objectSchema))\n\treturn createTool({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\t...(parameters === undefined ? {} : { parameters }),\n\t\texecute(args, context) {\n\t\t\tconst parsed = contract.parse(args)\n\t\t\tif (parsed === undefined || !isRecord(parsed)) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'malformed endpoint call arguments', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tfaults: contract.explain(args),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn definition.execute(parsed, context)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,IAAa,kBAAkB;;;;;;;;;;;;;AAc/B,IAAa,mBAAmB;;;;;;;;;;;;AAahC,IAAa,qBACZ;;;;;AAMD,IAAa,yBAAyB;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,KAAK,UAAU,EACd,MAAM,uDACP,CAAC;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;AAYX,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,qBAAqB;;;;;;;;;;;;AAalC,IAAa,6BAA4C,OAAO,OAAO;CACtE,MAAM;CACN,OAAO,OAAO,OAAO,CAAC,OAAO,OAAO,EAAE,MAAM,UAAU,CAAC,GAAG,OA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