@orkestrel/toolbox 0.0.4 → 0.0.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#definitions","#table","#handles","#drivers","#generator","#store"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/shapers.ts","../../../src/core/helpers.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 (AGENTS §5).\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 * The name {@link import('./factories.js').createAgentTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const AGENT_TOOL_NAME = 'agent'\n\n/**\n * The maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may\n * reach — 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_DEPTH} (rather than the two guards\n * sharing one reference): the two guards bound DIFFERENT chains (workflow nesting vs. 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 * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createAgentTool}\n * advertises in place of {@link AGENT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 should carry 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 * The maximum nesting depth a workflow → agent → workflow chain may reach — 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_DEPTH = 8\n\n/**\n * The name {@link import('./factories.js').createWorkflowTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under, and the name\n * {@link import('./factories.js').createAgentFunction} binds the depth/cycle-aware workflow tool\n * 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 + run a NESTED workflow\n * (bounded by {@link MAX_WORKFLOW_DEPTH}).\n */\nexport const WORKFLOW_TOOL_NAME = 'workflow'\n\n/**\n * A complete FLAT authoring example — the PRIMARY way a small model authors a workflow through\n * {@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 `run` 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 * A minimal NESTED authoring example — the ADVANCED escape-hatch form a model may use instead of\n * the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).\n *\n * @remarks\n * The full four-level 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\trun: 'compile',\n\t\t\t\t}),\n\t\t\t]),\n\t\t}),\n\t]),\n})\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createWorkflowTool}\n * advertises in place of {@link WORKFLOW_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 \"run\" (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 * The name {@link import('./factories.js').createWorkspaceTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const WORKSPACE_TOOL_NAME = 'workspace'\n\n/**\n * A valid {@link import('./types.js').WorkspaceOperation} object — the canonical example embedded\n * 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 * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createWorkspaceTool}\n * advertises in place of {@link WORKSPACE_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 * The name {@link import('./factories.js').createDescribeTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n *\n * @remarks\n * Net-new: pairs with the other three tools' lean {@link AGENT_TOOL_SUMMARY} /\n * {@link WORKFLOW_TOOL_SUMMARY} / {@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 * 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 * The DESCRIPTION {@link import('./factories.js').createDescribeTool} advertises.\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 * The name {@link import('./factories.js').createPromptTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const PROMPT_TOOL_NAME = 'ask'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createPromptTool}\n * advertises in place of {@link PROMPT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@link import('./factories.js').createDescribeTool}.\n */\nexport const PROMPT_TOOL_SUMMARY =\n\t\"Ask another terminal a question and BLOCK until it answers; the call resolves with the answered value. Call describe('ask') for the required fields.\"\n\n/** The full prompt protocol {@link import('./factories.js').createPromptTool} advertises. */\nexport const PROMPT_TOOL_DESCRIPTION = [\n\t'Ask another terminal a question and block until it answers. This call does not return until the addressed terminal answers, or the prompt fails.',\n\t'',\n\t'Required:',\n\t' to - the terminal name to ask.',\n\t' form - the prompt kind: one of \"input\", \"password\", \"confirm\", \"select\", \"checkbox\", \"editor\".',\n\t' message - the question shown to the answering terminal.',\n\t'Optional:',\n\t' options - form-specific options (e.g. choices for \"select\"/\"checkbox\").',\n\t'A cycle (two terminals asking each other) or an expired prompt fails the call with a typed error.',\n\t'Example:',\n\tJSON.stringify({ to: 'reviewer', form: 'confirm', message: 'Approve the release?' }),\n].join('\\n')\n\n/**\n * The name {@link import('./factories.js').createAnswerTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const ANSWER_TOOL_NAME = 'answer'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createAnswerTool}\n * advertises in place of {@link ANSWER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@link import('./factories.js').createDescribeTool}.\n */\nexport const ANSWER_TOOL_SUMMARY =\n\t\"List prompts addressed to this terminal, or answer one by id. Call describe('answer') for the required fields.\"\n\n/** The pending/answer protocol {@link import('./factories.js').createAnswerTool} advertises. */\nexport const ANSWER_TOOL_DESCRIPTION = [\n\t'List the prompts currently 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 prompt currently addressed to this terminal (id, form, message, options, time).',\n\t'- answer { \"operation\": \"answer\", \"id\": \"<prompt id>\", \"value\": <answer value> } — answer the prompt with that id; \"value\" must match the prompt\\'s form (a string for \"input\"/\"password\"/\"editor\", a boolean for \"confirm\", a choice for \"select\", an array of choices for \"checkbox\").',\n\t'Example — list pending prompts:',\n\tJSON.stringify({ operation: 'pending' }),\n\t'Example — answer one:',\n\tJSON.stringify({ operation: 'answer', id: 'abc123', value: true }),\n].join('\\n')\n\n/**\n * The name the upcoming `createDatabaseTool` factory will advertise by default — the key a model\n * calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n *\n * @remarks\n * SRC-1 of a 3-unit spine: this unit lands the persistence + schema foundation\n * ({@link import('./types.js').DatabaseDefinition}, {@link import('./types.js').DefinitionStoreInterface},\n * {@link import('./helpers.js').expandTables}); `createDatabaseTool` itself is built in a later unit.\n */\nexport const DATABASE_TOOL_NAME = 'database'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} the upcoming database tool\n * will advertise in place of {@link DATABASE_TOOL_DESCRIPTION}.\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 * The DESCRIPTION the upcoming database tool will advertise — a multi-line guide that teaches a\n * small model the operation list, the SERIALIZED query form, and the {@link import('./types.js').TableSpec}\n * 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\" | { \"type\": \"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 type string (\"string\" | \"integer\" | \"number\" | \"boolean\"), or { \"type\": \"<type>\", \"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: { name: 'string', price: 'number', notes: { type: 'string', optional: true } },\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/** The default cap on rows a `records` call returns when the caller omits `query.limit` — the upcoming database tool's default row ceiling. */\nexport const DATABASE_TOOL_LIMIT = 1000\n\n/** 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 * The name `createRelationTool` advertises by default — the key a model calls and the\n * `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const RELATION_TOOL_NAME = 'relation'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} the relation tool advertises\n * in place of {@link RELATION_TOOL_DESCRIPTION}.\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 * The DESCRIPTION the relation tool advertises — a multi-line guide that teaches a small model\n * the operation list and the flat dot-path `include` 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/** The default cap on rows a `find` / `links` call returns when the caller omits `limit` — the relation tool's default row ceiling. */\nexport const RELATION_TOOL_LIMIT = 1000\n\n/** The default cap on how many `include` path segments deep a `load` / `find` call may traverse — the relation tool's default include-depth ceiling. */\nexport const RELATION_TOOL_DEPTH = 3\n\n/**\n * The name {@link import('./factories.js').createInferTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const INFER_TOOL_NAME = 'infer'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createInferTool}\n * advertises in place of {@link INFER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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/** The schema-inference protocol {@link import('./factories.js').createInferTool} advertises. */\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' — e.g. 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'\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` + optional `context`) for the same reason: a\n// thrown, machine-readable, code-bearing error after AGENTS' “narrow untrusted input with guards”\n// boundary rejects a call, never a `{ error }` return. `ToolboxError` is this package's general\n// TOOL-CALL error — not scoped to agent delegation alone — so every package-owned `TOOL` misuse\n// shares it rather than minting one error class per tool.\n\n/**\n * 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)` 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 * Type guard narrowing an unknown caught value to an {@link ToolboxError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link ToolboxError}\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 value instanceof ToolboxError\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// `validate` is DECLARATIVE-ONLY here — a `Validator` is a function and cannot cross a JSON\n// Schema / contract boundary, so `promptToolShape`'s inline `validate` field keeps only the\n// primitive (`boolean` / `number` / `string`) rule fields `ValidationRules`\n// (`@orkestrel/terminal`) accepts; `custom` (a bare `Validator`) is DROPPED — mirrors\n// `serializeValidationRules`'s own function-stripping (`@orkestrel/terminal`).\n\n/**\n * The shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` (the\n * terminal identity to address), `form` (which of the six {@link import('@orkestrel/terminal').PromptType}\n * forms to ask), `message`, an optional `timeout` override, and every per-form optional field\n * FLATTENED onto one object (mirrors `workspaceToolShape`'s flat-arm style, but a single shared\n * shape rather than a discriminated union — `form` alone does not vary the REQUIRED fields, only\n * which of the optional ones apply, so a flat shape stays faithful without duplicating `to` /\n * `message` / `timeout` across six near-identical arms).\n *\n * @remarks\n * `choices` backs `'select'` / `'checkbox'`; `default` backs `'input'` / `'confirm'` / `'select'`\n * (a string for the first two forms' text default, `'true'`/`'false'` string for confirm — the\n * contract layer cannot vary a field's type by a sibling field's value, so `default` stays a\n * string and the handler coerces per form); `mask` backs `'password'`; `min` / `max` backs\n * `'checkbox'`; `validate` (declarative only) backs the four text-shaped forms\n * (`'input'` / `'password'` / `'confirm'` / `'editor'`).\n */\nexport const promptToolShape = objectShape({\n\tto: stringShape({ min: 1, description: 'The terminal identity to address the prompt to.' }),\n\tform: literalShape(['input', 'password', 'confirm', 'select', 'checkbox', 'editor'], {\n\t\tdescription: 'Which prompt form to ask.',\n\t}),\n\tmessage: stringShape({ min: 1, description: \"The prompt's question.\" }),\n\tdefault: optionalShape(\n\t\tstringShape({\n\t\t\tdescription:\n\t\t\t\t\"The default answer if the responder submits blank — 'input' / 'editor' text, 'confirm' 'true'/'false', or a 'select' choice value.\",\n\t\t}),\n\t),\n\tchoices: optionalShape(\n\t\tarrayShape(\n\t\t\tobjectShape({\n\t\t\t\tname: stringShape({\n\t\t\t\t\tmin: 1,\n\t\t\t\t\tdescription: 'The choice label shown to the answering party.',\n\t\t\t\t}),\n\t\t\t\tvalue: stringShape({\n\t\t\t\t\tmin: 1,\n\t\t\t\t\tdescription: 'The value submitted when this choice is picked.',\n\t\t\t\t}),\n\t\t\t\tdescription: optionalShape(\n\t\t\t\t\tstringShape({ description: 'An optional one-line elaboration.' }),\n\t\t\t\t),\n\t\t\t}),\n\t\t\t{ description: \"The selectable choices for 'select' / 'checkbox'.\" },\n\t\t),\n\t),\n\tmask: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription: \"The mask character 'password' renders in place of input.\",\n\t\t}),\n\t),\n\tmin: optionalShape(\n\t\tintegerShape({ min: 0, description: \"The minimum number of 'checkbox' selections required.\" }),\n\t),\n\tmax: optionalShape(\n\t\tintegerShape({ min: 0, description: \"The maximum number of 'checkbox' selections allowed.\" }),\n\t),\n\tvalidate: optionalShape(\n\t\tobjectShape({\n\t\t\trequired: optionalShape(booleanShape({ description: 'Reject an empty (trimmed) input.' })),\n\t\t\tminimum: optionalShape(\n\t\t\t\tintegerShape({\n\t\t\t\t\tmin: 0,\n\t\t\t\t\tdescription: 'Reject an input shorter than this many characters.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\tmaximum: optionalShape(\n\t\t\t\tintegerShape({\n\t\t\t\t\tmin: 0,\n\t\t\t\t\tdescription: 'Reject an input longer than this many characters.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\tpattern: optionalShape(\n\t\t\t\tstringShape({\n\t\t\t\t\tdescription: 'Reject an input that fails this regular-expression source.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\temail: optionalShape(booleanShape({ description: 'Require a valid email-address shape.' })),\n\t\t\turl: optionalShape(booleanShape({ description: 'Require a valid URL shape.' })),\n\t\t\tnumeric: optionalShape(booleanShape({ description: 'Require a numeric value.' })),\n\t\t\tinteger: optionalShape(booleanShape({ description: 'Require an integer value.' })),\n\t\t\talphanumeric: optionalShape(\n\t\t\t\tbooleanShape({ description: 'Require letters and digits only.' }),\n\t\t\t),\n\t\t}),\n\t),\n\ttimeout: optionalShape(\n\t\tintegerShape({ min: 0, description: 'Milliseconds to wait before the prompt expires.' }),\n\t),\n})\n\n/**\n * The shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated\n * by `operation`: `'pending'` lists the prompts addressed to this tool's terminal, `'answer'`\n * resolves one by `id` with a `value`.\n *\n * @remarks\n * `value`'s type varies by the ORIGINAL prompt's form (`string` for `'input'` / `'password'` /\n * `'select'` / `'editor'`, `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`) —\n * `unionShape(stringShape(), booleanShape(), arrayShape(stringShape()))` expresses that\n * union directly, so `value` is typed as the full `string | boolean | readonly string[]` union\n * here (no lossy string-only fallback needed).\n */\nexport const answerToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['pending'], {\n\t\t\tdescription: 'List the prompts currently addressed to this terminal.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['answer'], { description: 'Answer one pending prompt by id.' }),\n\t\tid: stringShape({ min: 1, description: 'The id of the pending prompt to answer.' }),\n\t\tvalue: unionShape(\n\t\t\tstringShape({ description: 'A text / select / editor answer.' }),\n\t\t\tbooleanShape({ description: 'A confirm answer.' }),\n\t\t\tarrayShape(stringShape(), { description: 'A checkbox answer — the checked values.' }),\n\t\t),\n\t}),\n)\n\n// Toolbox shapes — the shape VALUE each `create*Tool` factory (factories.ts) compiles into\n// the lockstep guard + parser + JSON Schema outputs (AGENTS §14). `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 * 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 should carry 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 * 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 * The shape of a {@link import('./types.js').TaskDraft} — identical to a strict task shape\n * EXCEPT `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\trun: 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 * The shape of a PHASE in a draft workflow — identical to a strict phase shape EXCEPT `id` and\n * `name` are OPTIONAL, and its tasks are {@link taskDraftShape}s.\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 * The shape of a DRAFT workflow — identical to a strict workflow shape EXCEPT `id` and `name`\n * are OPTIONAL at all three levels (workflow / phase / task), so a small model can omit the six\n * identity strings and let the tool synthesize them positionally.\n *\n * @remarks\n * The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.\n * `run` 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 * The shape of ONE flat step — `{ name }` — the building block of {@link workflowStepsShape}.\n *\n * @remarks\n * `name` is the REGISTERED behavior name the step runs (it becomes the task's `run`). 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 run).',\n\t}),\n})\n\n/**\n * The FLAT authoring shape {@link import('./factories.js').createWorkflowTool} advertises as its\n * `parameters` — the simplest surface a small model can fill: `{ 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 * The shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union\n * over the 13 workspace edit / read / navigation operations, discriminated by the `operation`\n * literal (never a bare `kind`; AGENTS §4.4). Each variant leads with its `operation`\n * discriminant then its FLAT fields, every field via `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 + 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 four `'splice'`\n * caret components are POSITIVE integers (`integerShape({ min: 1 })`); `regex` / `sensitive`\n * are `optionalShape(booleanShape(...))`. The two 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 (SRC-2 — the tool factory itself; SRC-1 landed the persistence + the\n// TableSpec DSL this shape's `tables` field compiles the SAME way `expandTables` does)\n\n/** A {@link import('./types.js').ColumnKind} literal — the leaf {@link columnSpecShape} wraps. */\nexport const columnKindShape = literalShape(['string', 'integer', 'number', 'boolean'], {\n\tdescription: 'A column type: \"string\" | \"integer\" | \"number\" | \"boolean\".',\n})\n\n/** A {@link import('./types.js').ColumnSpec} — a bare {@link columnKindShape}, or `{ type, optional }`. */\nexport const columnSpecShape = unionShape(\n\tcolumnKindShape,\n\tobjectShape({\n\t\ttype: columnKindShape,\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/** 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, { description: 'Column name to its type.' }),\n\t}),\n\t{ description: 'Table name to its column layout.' },\n)\n\n/** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */\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/** A loose row — a flat object of column name to JSON value; the array form (multiple rows) resolves FIRST per AGENTS §9.2. */\nexport const rowShape = recordShape(jsonShape(), {\n\tdescription: 'A row as a flat object of column name to value.',\n})\n\n/** One or many loose rows — the array form resolves FIRST per AGENTS §9.2. */\nexport const rowsShape = unionShape(\n\tarrayShape(rowShape, { description: 'Multiple rows.' }),\n\trowShape,\n)\n\n/** One SERIALIZED WHERE condition — `values` is ALWAYS an array, even for a single-value operator. */\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/** One sort term. */\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/** 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 * The shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —\n * discriminated by `operation` into the 11 database operations (`'create'` / `'tables'` /\n * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /\n * `'remove'` / `'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 via\n * {@link import('./helpers.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, SRC-3)\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/** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */\nexport const relationKeyShape = 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/** 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/** Flat dot-path relation include list, expanded via {@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, e.g. \"contacts.account\".',\n\t\t}),\n\t\t{ description: 'Which relations to attach, as flat dot-paths.' },\n\t),\n)\n\n/** 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 * The shape of {@link import('./factories.js').createRelationTool}'s call arguments —\n * discriminated by `operation` into the 5 relation operations (`'load'` / `'find'` / `'link'` /\n * `'unlink'` / `'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: relationKeyShape,\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 * 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 { PromptType } from '@orkestrel/terminal'\nimport type { TableMap } from '@orkestrel/database'\nimport type { DatabaseErrorCode } from '@orkestrel/database'\nimport type {\n\tInclude,\n\tModelInterface,\n\tRelationErrorCode,\n\tRelationManagerInterface,\n} from '@orkestrel/relation'\nimport type { Condition, ConditionConnector, OrderDirection, QueryInput } from '@orkestrel/database'\nimport type { ContractShape } from '@orkestrel/contract'\nimport type {\n\tAgentFunction,\n\tToolboxErrorCode,\n\tColumnKind,\n\tColumnSpec,\n\tDatabaseDefinition,\n\tTableSpec,\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 { ToolboxError } from './errors.js'\nimport {\n\tattempt,\n\tbooleanShape,\n\tintegerShape,\n\tisFiniteNumber,\n\tisNonEmptyString,\n\tisRecord,\n\tisString,\n\tnumberShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\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 * The ancestry identifier of a workflow in a run chain — `workflow:<id>`.\n *\n * @remarks\n * Namespacing keeps a workflow id and an {@link agentTag} 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 workflowTag(id: string): string {\n\treturn `workflow:${id}`\n}\n\n/**\n * The ancestry identifier of an agent in a run chain — `agent:<name>`.\n *\n * @remarks\n * The agent counterpart of {@link workflowTag}: {@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 agentTag(name: string): string {\n\treturn `agent:${name}`\n}\n\n/**\n * Narrow an unknown value to a valid alternating workflow lineage.\n *\n * @param value - The value to inspect\n * @returns Whether `value` is a unique, nonempty-tagged workflow/agent chain\n */\nexport function isWorkflowLineage(value: unknown): value is WorkflowLineage {\n\tconst inspected = attempt(() => {\n\t\tif (!Array.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 * Build a validated, copied, and frozen workflow lineage value.\n *\n * @param lineage - The configured chain; omitted means a direct root\n * @returns An immutable caller-isolated lineage\n */\nexport function lineageOf(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 * Append one tag to a workflow lineage and return 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 lineageOf([...lineage, tag])\n}\n\n/**\n * Derive 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 = lineageOf(lineage)\n\tconst workflows = current.filter((tag) => tag.startsWith('workflow:')).length\n\treturn Math.max(0, workflows - 1)\n}\n\n/**\n * Narrow an unknown callable to Toolbox's frozen contextual agent adapter metadata.\n *\n * @param value - The value to inspect\n * @returns Whether it is a frozen {@link AgentFunction} with a frozen valid lineage\n */\nexport function isAgentFunction(value: unknown): value is AgentFunction {\n\tconst inspected = attempt(() => {\n\t\tif (typeof value !== 'function' || !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 * Build the plain success summary {@link import('./factories.js').createWorkflowTool} returns on\n * a completed run — the universal tool-handler contract (AGENTS §14): return a plain value on\n * success, appearing 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 workflowToolSummary(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 + 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\n// the six required `id`/`name` strings. The factory re-validates the result against the STRICT\n// `createWorkflowContract().is` gate before running (soundness).\n\n/**\n * Complete a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesize any\n * MISSING `id` deterministically + positionally, and default any MISSING `name` to its\n * (now-resolved) `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 has both. `run`, `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/name optional at all three 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 * Complete 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 * Complete 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.run === undefined ? {} : { run: task.run }),\n\t\t...(task.retries === undefined ? {} : { retries: task.retries }),\n\t\t...(task.timeout === undefined ? {} : { timeout: task.timeout }),\n\t}\n}\n\n/**\n * Expand 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 `run` (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 two 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: [{ run: step.name }],\n\t\t})),\n\t})\n}\n\n// === Terminal-tool answer coercion + error-code mapping (the tool's answer surface)\n\n/**\n * Normalize an LLM-supplied answer `value` to the type {@link PromptType} `form` expects, so a\n * caller that only ever emits strings can still answer a typed prompt.\n *\n * @remarks\n * `'confirm'` coerces to a `boolean` — a `boolean` passes through, and the strings `'true'` /\n * `'false'` (case-insensitively) map to it; any other string is truthy-coerced via\n * `Boolean(value)`. `'checkbox'` coerces to `readonly string[]` — an array passes through\n * (stringifying each entry), a comma-separated string splits + trims into one, and any other\n * single (non-comma) string becomes a one-item array. Every other form (`'input'` / `'password'`\n * / `'select'` / `'editor'`) coerces to a plain `string` — a string passes through verbatim; a\n * non-string, non-object scalar (`number` / `boolean`) stringifies via `String(value)`; an\n * object or array (no lossless string form) falls back to `''` rather than serializing garbage.\n * Pure and total — never throws.\n *\n * @param form - The {@link PromptType} the answer is being coerced FOR\n * @param value - The raw, LLM-supplied answer value\n * @returns The coerced answer — `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`,\n * `string` otherwise\n */\nexport function coerceAnswer(\n\tform: PromptType,\n\tvalue: unknown,\n): string | boolean | readonly string[] {\n\tif (form === 'confirm') {\n\t\tif (typeof value === 'boolean') return value\n\t\tif (typeof value === 'string') {\n\t\t\tconst lower = value.trim().toLowerCase()\n\t\t\tif (lower === 'true') return true\n\t\t\tif (lower === 'false') return false\n\t\t}\n\t\treturn Boolean(value)\n\t}\n\tif (form === 'checkbox') {\n\t\tif (Array.isArray(value)) return value.map((entry) => String(entry))\n\t\tif (typeof value === 'string') {\n\t\t\tif (value.includes(',')) return value.split(',').map((entry) => entry.trim())\n\t\t\treturn [value]\n\t\t}\n\t\treturn [String(value)]\n\t}\n\t// The remaining text-shaped forms ('input'/'password'/'select'/'editor').\n\tif (typeof value === 'string') return value\n\tif (typeof value === 'object' && value !== null) return ''\n\treturn String(value)\n}\n\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the terminal-tool factory should throw\n * with — the 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'`, `'CANCEL'`, `'DRIVER'`) maps to the generic `'TOOL'` code. The mapper only\n * 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 terminalToolCode(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-tool foundation (SRC-1 — persistence + the TableSpec DSL; the tool factories land\n// in a later unit) — the config-only `DatabaseDefinition` compiles into a live `@orkestrel/database`\n// `TableMap`, and its store twins narrow an untrusted persisted blob back to the type.\n\n/** Narrow an unknown value to a {@link ColumnSpec} — a valid {@link import('./types.js').ColumnKind} shorthand, or `{ type, optional }` with a valid `type`. */\nexport function isColumnSpec(value: unknown): value is ColumnSpec {\n\tif (isColumnKind(value)) return true\n\tif (!isRecord(value)) return false\n\treturn (\n\t\tisColumnKind(value.type) &&\n\t\t(value.optional === undefined || typeof value.optional === 'boolean')\n\t)\n}\n\n/** Narrow an unknown value to a {@link import('./types.js').ColumnKind}. */\nexport function isColumnKind(value: unknown): value is ColumnKind {\n\treturn value === 'string' || value === 'integer' || value === 'number' || value === 'boolean'\n}\n\n/**\n * Compile 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, kind] of Object.entries(definition.columns)) {\n\t\t\tcolumns[column] = columnShape(kind)\n\t\t}\n\t\ttables[table] = columns\n\t}\n\treturn tables\n}\n\n/** Compile one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf {@link expandTables} maps over. */\nexport function columnShape(spec: ColumnSpec): ContractShape {\n\tconst kind = isString(spec) ? spec : spec.type\n\tconst optional = !isString(spec) && spec.optional === true\n\tconst shape = kindShape(kind)\n\treturn optional ? optionalShape(shape) : shape\n}\n\n/** Map one {@link import('./types.js').ColumnKind} to its primitive `@orkestrel/database` shape — the leaf {@link columnShape} wraps. */\nexport function kindShape(kind: ColumnKind): ContractShape {\n\tif (kind === 'string') return stringShape()\n\tif (kind === 'integer') return integerShape()\n\tif (kind === 'number') return numberShape()\n\treturn booleanShape()\n}\n\n/**\n * Narrow an unknown value to a {@link DatabaseDefinition} — a non-empty `id` + `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 */\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 (!Array.isArray(groups)) return false\n\t\t\tfor (const group of groups) {\n\t\t\t\tif (!Array.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\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the upcoming database tool should throw\n * with — the pure classification step of that factory's error handling, mirroring\n * {@link terminalToolCode}'s idiom for `@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 databaseToolCode(error: unknown): DatabaseErrorCode | undefined {\n\treturn isDatabaseError(error) ? error.code : undefined\n}\n\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the upcoming relation tool should throw\n * with — the pure classification step of that factory's error handling, mirroring\n * {@link terminalToolCode}'s idiom for `@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 relationToolCode(error: unknown): RelationErrorCode | undefined {\n\treturn isRelationError(error) ? error.code : undefined\n}\n\n/**\n * Expand 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 = typeof existing === 'object' ? 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 * Resolve 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 relationManagerOf(\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 * Resolve 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 relationManagerOf}'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 relationModelOf(manager: RelationManagerInterface, name: string): 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.models(),\n\t\t})\n\t}\n\treturn manager.model(name)\n}\n\n// === Database-tool operation leaves (SRC-2 — `createDatabaseTool` itself)\n\n/**\n * Normalize the database tool's parsed SERIALIZED query into a live `@orkestrel/database`\n * {@link QueryInput} — default each condition's OMITTED `connector` 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 queryOf(\n\tquery:\n\t\t| Readonly<{\n\t\t\t\tconditions?: readonly Readonly<{\n\t\t\t\t\tcolumn: string\n\t\t\t\t\toperator: Condition['operator']\n\t\t\t\t\tvalues: readonly unknown[]\n\t\t\t\t\tconnector?: ConditionConnector\n\t\t\t\t}>[]\n\t\t\t\torder?: readonly Readonly<{ column: string; direction: OrderDirection }>[]\n\t\t\t\tlimit?: number\n\t\t\t\toffset?: number\n\t\t }>\n\t\t| undefined,\n): 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 * Clamp a `'records'` call's query to a row cap, and build the PROBE query the caller reads\n * with — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation\n * uses to detect truncation without a separate `count` round trip.\n *\n * @remarks\n * The effective limit is `min(query?.limit ?? cap, cap)`, floored at `0` (so a caller can never\n * exceed the configured cap by supplying a larger `query.limit`). 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(\n\tquery: QueryInput | undefined,\n\tcap: number,\n): Readonly<{ query: QueryInput; limit: number }> {\n\tconst limit = Math.max(0, Math.min(query?.limit ?? cap, cap))\n\treturn { query: { ...query, limit: limit + 1 }, limit }\n}\n","import type { DatabaseDefinition, DefinitionStoreInterface } from '../types.js'\n\n/**\n * 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. The EXACT twin of\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}.\n *\n * @remarks\n * A plain `Map<string, DatabaseDefinition>` (AGENTS §21 — 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 §22 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\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\tset(definition: DatabaseDefinition): Promise<void> {\n\t\t// Insert / replace under the definition's OWN id (no separate id param).\n\t\tthis.#definitions.set(definition.id, structuredClone(definition))\n\t\treturn Promise.resolve()\n\t}\n\n\tdelete(id: string): Promise<void> {\n\t\t// Drop by id; `Map.delete` of an absent id is already a no-op (no throw).\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 '../helpers.js'\n\n/**\n * 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('../helpers.js').isDatabaseDefinition} — the\n * AGENTS §14 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 §22 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 * Wrap 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/** Resolve the persisted definition for `id`, narrowing the opaque JSON column back to a `DatabaseDefinition`. */\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 (AGENTS\n\t\t// §14); a malformed blob resolves `undefined`, never a broken definition.\n\t\treturn isDatabaseDefinition(row.definition) ? row.definition : undefined\n\t}\n\n\t/** Insert or replace under the definition's OWN `id` (no separate id param) — the row is `{ id, definition }`. */\n\tasync set(definition: DatabaseDefinition): Promise<void> {\n\t\tawait this.#table.set({ id: definition.id, definition })\n\t}\n\n\t/** Drop a definition by id; an absent id is a no-op (no throw). */\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 '../helpers.js'\n\n/**\n * Resolve database definitions into cached live handles for database tools.\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 * Create 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 * Determine whether a live database is cached by id.\n\t *\n\t * @param id - Database id\n\t * @returns Whether a live handle is cached\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#handles.has(id)\n\t}\n\n\t/**\n\t * Read 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 * Cache 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 * Remove 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 * Resolve a cached or stored database by id.\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\tWorkflowFunctions,\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\tisRecord,\n\tparseJSONValue,\n\trawShape,\n\tsamplesToSchema,\n\tschemaToObject,\n\tschemaToParameters,\n\tschemaToShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { isTerminalError } from '@orkestrel/terminal'\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_DEPTH,\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\tagentTag,\n\tclampQuery,\n\tcoerceAnswer,\n\tcompleteDraft,\n\tderiveWorkflowDepth,\n\textendLineage,\n\tlineageOf,\n\tqueryOf,\n\tdatabaseToolCode,\n\texpandInclude,\n\texpandSteps,\n\texpandTables,\n\trelationManagerOf,\n\trelationModelOf,\n\trelationToolCode,\n\tterminalToolCode,\n\tisAgentFunction,\n\tworkflowTag,\n\tworkflowToolSummary,\n} from './helpers.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 * Wrap 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`.\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(await tool.execute(controller.input))\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 * Wrap 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_DEPTH} 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 = lineageOf(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 = workflowTag(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_DEPTH) {\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_DEPTH,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = agentTag(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 * Compose 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): WorkflowFunctions {\n\tconst lineage = lineageOf(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: WorkflowFunctions =\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 (typeof fn !== 'function') {\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 * Compile the lenient workflow draft contract used by {@link createWorkflowTool}.\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 * Wrap a {@link WorkflowDefinition} as an LLM-callable tool — it ADVERTISES the SIMPLE flat\n * authoring shape (`{ name?, steps: [{ name }] }`) as its `parameters` so even a small model can\n * author a complete tree, and its handler EXPANDS / COMPLETES the authored blob, validates it\n * against the STRICT contract, and runs it through `runner`, forwarding the caller's optional\n * 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 + runner stay STRICT and\n * unchanged).** A 2B model reliably CALLS the tool but cannot reliably emit the full four-level\n * nested {@link WorkflowDefinition} (six required `id`/`name` strings, an all-or-nothing tree).\n * So the tool ACCEPTS three authoring forms 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 (AGENTS §14): 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\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 = lineageOf(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 +\n\t\t\t// expanded; otherwise the nested DRAFT form, parsed + completed. A parse failure leaves\n\t\t\t// `target` undefined ⇒ the strict gate below 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 (Array.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 = workflowTag(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_DEPTH) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `nested workflow exceeds max depth ${MAX_WORKFLOW_DEPTH}`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_DEPTH,\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 workflowToolSummary(result)\n\t\t},\n\t})\n}\n\n/**\n * Build an LLM-callable workspace-editing tool — it ADVERTISES the `operation`-discriminated\n * 13-op union ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its\n * handler PARSES the model-supplied args against that contract and DISPATCHES the matched\n * operation against the manager's ACTIVE workspace (the registry ops drive the manager itself),\n * returning the plain result. A malformed operation throws this package's `ToolboxError`; a\n * genuine workspace-domain failure propagates `@orkestrel/workspace`'s typed `WorkspaceError`.\n * EITHER drives a caller-supplied {@link WorkspaceToolOptions.manager} directly, OR\n * constructs a fresh `WorkspaceManagerInterface` (`@orkestrel/workspace`) over\n * {@link import('./types.js').WorkspaceToolOptions.store} (via `@orkestrel/workspace`'s\n * `createWorkspaceManager`); neither given constructs a manager backed by\n * `@orkestrel/workspace`'s in-memory store default.\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. Two 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 + activates a default\n * workspace (`manager.add()`) so the model can just 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 (AGENTS §14): 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 (`MODALITY` / `PATTERN` / `RANGE`) PROPAGATE\n * uncaught. The range edit is the FLAT `'splice'` op: its four 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 / read ops target the ACTIVE workspace. A WRITING op ensures a target — auto-creating\n\t\t\t// + activating a default workspace when none is active (the no-active ergonomic seam) — while\n\t\t\t// a pure-READ 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 * Build an LLM-callable sub-agent delegation tool — 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 (AGENTS §14): 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 via\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} — both 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 = agentTag(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 * Build 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 * (`AGENT_TOOL_SUMMARY` / `WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY`).\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 via `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 (AGENTS §14): 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 * Build an LLM-callable prompt tool — the ASK side of the terminal seam. Asks\n * {@link import('./types.js').PromptToolOptions.to} a question and BLOCKS until it answers,\n * returning the resolved answer value.\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): validates the call args against\n * {@link import('./shapers.js').promptToolShape}, dispatches to the matching\n * `TerminalManagerInterface.ask` overload (`@orkestrel/terminal`) for the call's `form`, and\n * RETURNS the resolved answer on success. `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 prompt CYCLE rejects with\n * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`\n * {@link import('./errors.js').ToolboxError}; an expired prompt re-surfaces as `EXPIRE`; an\n * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal\n * plus the known ones (`manager.terminals()`).\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\tif (\n\t\t\t\t(call.form === 'select' || call.form === 'checkbox') &&\n\t\t\t\t(call.choices ?? []).length === 0\n\t\t\t) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'select/checkbox requires at least one choice', {\n\t\t\t\t\tto: call.to,\n\t\t\t\t\tform: call.form,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tswitch (call.form) {\n\t\t\t\t\tcase 'input':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'editor':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'password':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.mask === undefined ? {} : { mask: call.mask }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'confirm':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default === 'true' }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'select':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\tchoices: call.choices ?? [],\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'checkbox':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\tchoices: call.choices ?? [],\n\t\t\t\t\t\t\t...(call.min === undefined ? {} : { min: call.min }),\n\t\t\t\t\t\t\t...(call.max === undefined ? {} : { max: call.max }),\n\t\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst code = terminalToolCode(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 form a prompt 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(\n\t\t\t\t\t\t'EXPIRE',\n\t\t\t\t\t\t`prompt to '${call.to}' expired before it was answered`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t\t},\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\tknown: options.manager.terminals(),\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 * Build an LLM-callable answer tool — the ANSWER side of the terminal seam. Lists the prompts\n * currently addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of\n * them by id.\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): validates the call args against\n * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`\n * returns a compact list (`{ id, from, form, message }`) of every prompt currently addressed to\n * `to` (`TerminalManagerInterface.pending`, `@orkestrel/terminal`). `'answer'` looks the prompt\n * up by `id` (an unknown id throws a typed `ANSWER` {@link import('./errors.js').ToolboxError}),\n * normalizes the model-supplied `value` to the prompt's own form\n * ({@link import('./helpers.js').coerceAnswer}), and applies it via\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 prompt 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 prompts 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((prompt) => ({\n\t\t\t\t\tid: prompt.id,\n\t\t\t\t\tfrom: prompt.from,\n\t\t\t\t\tform: prompt.form,\n\t\t\t\t\tmessage: prompt.message,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tconst prompt = options.manager.pending(options.to).find((entry) => entry.id === call.id)\n\t\t\tif (prompt === undefined) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `unknown prompt '${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\tconst coerced = coerceAnswer(prompt.form, call.value)\n\t\t\tconst result = options.manager.answer(options.to, call.id, coerced)\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `failed to answer prompt '${call.id}': ${result.error}`, {\n\t\t\t\t\tid: call.id,\n\t\t\t\t\treason: result.error,\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 (SRC-1 — the tool factories land in a later unit)\n\n/**\n * Create the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database\n * definitions, the DEFAULT store the upcoming database / relation tools will persist their\n * `DatabaseDefinition` 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 * Create 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 (SRC-2 — createDatabaseTool itself)\n\n/**\n * Build an LLM-callable database tool — create, query, and mutate `@orkestrel/database`\n * databases through one `operation`-discriminated call (AGENTS §14, matching\n * {@link createWorkspaceTool}'s single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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('./helpers.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}) via\n * {@link import('./helpers.js').clampQuery}, reporting `truncated` when storage held more rows\n * than the cap. Every operation's `query` is normalized via\n * {@link import('./helpers.js').queryOf} (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').databaseToolCode}); 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 * \toperation: 'create',\n * \tid: 'shop',\n * \ttables: { products: { columns: { name: 'string', price: 'number' } } },\n * })\n * ```\n */\nexport function createDatabaseTool(options: DatabaseToolOptions = {}): ToolInterface {\n\tif (\n\t\toptions.timeout !== undefined &&\n\t\t(options.timeout < 0 || !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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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(queryOf(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(queryOf(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\tqueryOf(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 = Array.isArray(call.row)\n\t\t\t\t\t\tconst rows = Array.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 = Array.isArray(call.row)\n\t\t\t\t\t\tconst rows = Array.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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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 = databaseToolCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', error instanceof 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 (SRC-3 — createRelationTool, the final unit of the database / relation spine)\n\n/**\n * Build an LLM-callable relation tool — traverse and edit `@orkestrel/relation` relationships\n * through one `operation`-discriminated call (AGENTS §14, matching {@link createDatabaseTool}'s\n * single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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').relationManagerOf}) — then resolves `model` against it\n * ({@link import('./helpers.js').relationModelOf}, 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 via {@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, AGENTS §9.2) or a single key. `'find'` and `'links'` clamp their\n * result to {@link import('./types.js').RelationToolOptions.limit} (default\n * {@link import('./constants.js').RELATION_TOOL_LIMIT}) — `'find'` probes one row past the\n * effective limit (mirroring {@link import('./helpers.js').clampQuery}'s idiom) to report\n * `truncated`; `'links'` (which has no upstream pagination) fetches the FULL linked-key list and\n * 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({ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] })\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 = relationManagerOf(options.managers, call.manager)\n\t\t\t\tconst model = relationModelOf(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 (typeof call.key === 'string' || typeof call.key === 'number') {\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 = Math.min(call.limit ?? cap, 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 keys = await model.links(call.key, call.relation)\n\t\t\t\t\t\tconst truncated = keys.length > cap\n\t\t\t\t\t\tconst sliced = keys.slice(0, cap)\n\t\t\t\t\t\treturn { keys: sliced, count: sliced.length, truncated, limit: cap }\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 = relationToolCode(error)\n\t\t\t\tif (relation !== undefined) {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'RELATION',\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: relation,\n\t\t\t\t\t\t\toperation: call.operation,\n\t\t\t\t\t\t\tmodel: call.model,\n\t\t\t\t\t\t\t...('relation' in call ? { relation: call.relation } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst database = databaseToolCode(error)\n\t\t\t\tif (database === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', error instanceof 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 * Build a standalone LLM-callable tool that infers a JSON Schema from example values — the\n * utility half of the \"existing API/DB → MCP tool\" bridge (the other half,\n * {@link createEndpointTool}, wraps one CONCRETE endpoint).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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 via `@orkestrel/contract`'s\n * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` via `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 (via `@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\", i.e. 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 guarantee (AGENTS §14), a `valid: true` entry is\n * ALWAYS also `coercible: true`. `@orkestrel/contract` 0.0.7'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, since\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 all three\n * and yields a bounded, non-throwing per-candidate verdict; a NON-JSON-safe candidate (e.g. 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 * Wrap one CONCRETE endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable\n * `ToolInterface` — the endpoint half of the \"existing API/DB → MCP tool\" bridge (the other half,\n * {@link createInferTool}, is a standalone inference utility).\n *\n * @remarks\n * `parameters` is inferred ONCE at construction from `definition.samples` via\n * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s\n * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` via `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` 0.0.7's `schemaToShape` compiles it ONCE (via `createContract`) into a\n * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.invoke` — 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.invoke` receives the COERCED value (e.g. `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.invoke` 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`, `execute` PASSES THROUGH the model-supplied `args` to `definition.invoke`\n * WITHOUT re-validation — the pre-0.0.7 behavior, preserved as an explicit opt-out. Either way,\n * `invoke`'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 * (AGENTS §14) — 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 + 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 * \tinvoke: (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 `invoke`\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 * // `invoke` 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) {\n\t\t\t\treturn definition.invoke(args)\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) {\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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AAQ,IAAI;GAC9B,CAAC;GAEF,OAAO,WAAW,OAAO,MAAM;EAChC;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"index.js","names":["#definitions","#table","#handles","#drivers","#generator","#store"],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/shapers.ts","../../../src/core/helpers.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 (AGENTS §5).\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 * The name {@link import('./factories.js').createAgentTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const AGENT_TOOL_NAME = 'agent'\n\n/**\n * The maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may\n * reach — 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_DEPTH} (rather than the two guards\n * sharing one reference): the two guards bound DIFFERENT chains (workflow nesting vs. 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 * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createAgentTool}\n * advertises in place of {@link AGENT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 should carry 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 * The maximum nesting depth a workflow → agent → workflow chain may reach — 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_DEPTH = 8\n\n/**\n * The name {@link import('./factories.js').createWorkflowTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under, and the name\n * {@link import('./factories.js').createAgentFunction} binds the depth/cycle-aware workflow tool\n * 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 + run a NESTED workflow\n * (bounded by {@link MAX_WORKFLOW_DEPTH}).\n */\nexport const WORKFLOW_TOOL_NAME = 'workflow'\n\n/**\n * A complete FLAT authoring example — the PRIMARY way a small model authors a workflow through\n * {@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 `run` 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 * A minimal NESTED authoring example — the ADVANCED escape-hatch form a model may use instead of\n * the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).\n *\n * @remarks\n * The full four-level 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\trun: 'compile',\n\t\t\t\t}),\n\t\t\t]),\n\t\t}),\n\t]),\n})\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createWorkflowTool}\n * advertises in place of {@link WORKFLOW_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 \"run\" (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 * The name {@link import('./factories.js').createWorkspaceTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const WORKSPACE_TOOL_NAME = 'workspace'\n\n/**\n * A valid {@link import('./types.js').WorkspaceOperation} object — the canonical example embedded\n * 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 * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createWorkspaceTool}\n * advertises in place of {@link WORKSPACE_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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 * 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 * The name {@link import('./factories.js').createDescribeTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n *\n * @remarks\n * Net-new: pairs with the other three tools' lean {@link AGENT_TOOL_SUMMARY} /\n * {@link WORKFLOW_TOOL_SUMMARY} / {@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 * 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 * The DESCRIPTION {@link import('./factories.js').createDescribeTool} advertises.\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 * The name {@link import('./factories.js').createPromptTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const PROMPT_TOOL_NAME = 'ask'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createPromptTool}\n * advertises in place of {@link PROMPT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@link import('./factories.js').createDescribeTool}.\n */\nexport const PROMPT_TOOL_SUMMARY =\n\t\"Ask another terminal a question and BLOCK until it answers; the call resolves with the answered value. Call describe('ask') for the required fields.\"\n\n/** The full prompt protocol {@link import('./factories.js').createPromptTool} advertises. */\nexport const PROMPT_TOOL_DESCRIPTION = [\n\t'Ask another terminal a question and block until it answers. This call does not return until the addressed terminal answers, or the prompt fails.',\n\t'',\n\t'Required:',\n\t' to - the terminal name to ask.',\n\t' form - the prompt kind: one of \"input\", \"password\", \"confirm\", \"select\", \"checkbox\", \"editor\".',\n\t' message - the question shown to the answering terminal.',\n\t'Optional:',\n\t' options - form-specific options (e.g. choices for \"select\"/\"checkbox\").',\n\t'A cycle (two terminals asking each other) or an expired prompt fails the call with a typed error.',\n\t'Example:',\n\tJSON.stringify({ to: 'reviewer', form: 'confirm', message: 'Approve the release?' }),\n].join('\\n')\n\n/**\n * The name {@link import('./factories.js').createAnswerTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const ANSWER_TOOL_NAME = 'answer'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createAnswerTool}\n * advertises in place of {@link ANSWER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@link import('./factories.js').createDescribeTool}.\n */\nexport const ANSWER_TOOL_SUMMARY =\n\t\"List prompts addressed to this terminal, or answer one by id. Call describe('answer') for the required fields.\"\n\n/** The pending/answer protocol {@link import('./factories.js').createAnswerTool} advertises. */\nexport const ANSWER_TOOL_DESCRIPTION = [\n\t'List the prompts currently 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 prompt currently addressed to this terminal (id, form, message, options, time).',\n\t'- answer { \"operation\": \"answer\", \"id\": \"<prompt id>\", \"value\": <answer value> } — answer the prompt with that id; \"value\" must match the prompt\\'s form (a string for \"input\"/\"password\"/\"editor\", a boolean for \"confirm\", a choice for \"select\", an array of choices for \"checkbox\").',\n\t'Example — list pending prompts:',\n\tJSON.stringify({ operation: 'pending' }),\n\t'Example — answer one:',\n\tJSON.stringify({ operation: 'answer', id: 'abc123', value: true }),\n].join('\\n')\n\n/**\n * The name the upcoming `createDatabaseTool` factory will advertise by default — the key a model\n * calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n *\n * @remarks\n * SRC-1 of a 3-unit spine: this unit lands the persistence + schema foundation\n * ({@link import('./types.js').DatabaseDefinition}, {@link import('./types.js').DefinitionStoreInterface},\n * {@link import('./helpers.js').expandTables}); `createDatabaseTool` itself is built in a later unit.\n */\nexport const DATABASE_TOOL_NAME = 'database'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} the upcoming database tool\n * will advertise in place of {@link DATABASE_TOOL_DESCRIPTION}.\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 * The DESCRIPTION the upcoming database tool will advertise — a multi-line guide that teaches a\n * small model the operation list, the SERIALIZED query form, and the {@link import('./types.js').TableSpec}\n * 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\" | { \"type\": \"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 type string (\"string\" | \"integer\" | \"number\" | \"boolean\"), or { \"type\": \"<type>\", \"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: { name: 'string', price: 'number', notes: { type: 'string', optional: true } },\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/** The default cap on rows a `records` call returns when the caller omits `query.limit` — the upcoming database tool's default row ceiling. */\nexport const DATABASE_TOOL_LIMIT = 1000\n\n/** 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 * The name `createRelationTool` advertises by default — the key a model calls and the\n * `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const RELATION_TOOL_NAME = 'relation'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} the relation tool advertises\n * in place of {@link RELATION_TOOL_DESCRIPTION}.\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 * The DESCRIPTION the relation tool advertises — a multi-line guide that teaches a small model\n * the operation list and the flat dot-path `include` 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/** The default cap on rows a `find` / `links` call returns when the caller omits `limit` — the relation tool's default row ceiling. */\nexport const RELATION_TOOL_LIMIT = 1000\n\n/** The default cap on how many `include` path segments deep a `load` / `find` call may traverse — the relation tool's default include-depth ceiling. */\nexport const RELATION_TOOL_DEPTH = 3\n\n/**\n * The name {@link import('./factories.js').createInferTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/tool`) registers under.\n */\nexport const INFER_TOOL_NAME = 'infer'\n\n/**\n * The lean {@link import('@orkestrel/tool').ToolInterface.summary} {@link import('./factories.js').createInferTool}\n * advertises in place of {@link INFER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/tool`) advertises `summary ?? description`, so this one-sentence text stands in\n * for the full teaching description; the full text stays retrievable via\n * {@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/** The schema-inference protocol {@link import('./factories.js').createInferTool} advertises. */\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' — e.g. 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'\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` + optional `context`) for the same reason: a\n// thrown, machine-readable, code-bearing error after AGENTS' “narrow untrusted input with guards”\n// boundary rejects a call, never a `{ error }` return. `ToolboxError` is this package's general\n// TOOL-CALL error — not scoped to agent delegation alone — so every package-owned `TOOL` misuse\n// shares it rather than minting one error class per tool.\n\n/**\n * 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)` 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 * Type guard narrowing an unknown caught value to an {@link ToolboxError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link ToolboxError}\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 value instanceof ToolboxError\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// `validate` is DECLARATIVE-ONLY here — a `Validator` is a function and cannot cross a JSON\n// Schema / contract boundary, so `promptToolShape`'s inline `validate` field keeps only the\n// primitive (`boolean` / `number` / `string`) rule fields `ValidationRules`\n// (`@orkestrel/terminal`) accepts; `custom` (a bare `Validator`) is DROPPED — mirrors\n// `serializeValidationRules`'s own function-stripping (`@orkestrel/terminal`).\n\n/**\n * The shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` (the\n * terminal identity to address), `form` (which of the six {@link import('@orkestrel/terminal').PromptType}\n * forms to ask), `message`, an optional `timeout` override, and every per-form optional field\n * FLATTENED onto one object (mirrors `workspaceToolShape`'s flat-arm style, but a single shared\n * shape rather than a discriminated union — `form` alone does not vary the REQUIRED fields, only\n * which of the optional ones apply, so a flat shape stays faithful without duplicating `to` /\n * `message` / `timeout` across six near-identical arms).\n *\n * @remarks\n * `choices` backs `'select'` / `'checkbox'`; `default` backs `'input'` / `'confirm'` / `'select'`\n * (a string for the first two forms' text default, `'true'`/`'false'` string for confirm — the\n * contract layer cannot vary a field's type by a sibling field's value, so `default` stays a\n * string and the handler coerces per form); `mask` backs `'password'`; `min` / `max` backs\n * `'checkbox'`; `validate` (declarative only) backs the four text-shaped forms\n * (`'input'` / `'password'` / `'confirm'` / `'editor'`).\n */\nexport const promptToolShape = objectShape({\n\tto: stringShape({ min: 1, description: 'The terminal identity to address the prompt to.' }),\n\tform: literalShape(['input', 'password', 'confirm', 'select', 'checkbox', 'editor'], {\n\t\tdescription: 'Which prompt form to ask.',\n\t}),\n\tmessage: stringShape({ min: 1, description: \"The prompt's question.\" }),\n\tdefault: optionalShape(\n\t\tstringShape({\n\t\t\tdescription:\n\t\t\t\t\"The default answer if the responder submits blank — 'input' / 'editor' text, 'confirm' 'true'/'false', or a 'select' choice value.\",\n\t\t}),\n\t),\n\tchoices: optionalShape(\n\t\tarrayShape(\n\t\t\tobjectShape({\n\t\t\t\tname: stringShape({\n\t\t\t\t\tmin: 1,\n\t\t\t\t\tdescription: 'The choice label shown to the answering party.',\n\t\t\t\t}),\n\t\t\t\tvalue: stringShape({\n\t\t\t\t\tmin: 1,\n\t\t\t\t\tdescription: 'The value submitted when this choice is picked.',\n\t\t\t\t}),\n\t\t\t\tdescription: optionalShape(\n\t\t\t\t\tstringShape({ description: 'An optional one-line elaboration.' }),\n\t\t\t\t),\n\t\t\t}),\n\t\t\t{ description: \"The selectable choices for 'select' / 'checkbox'.\" },\n\t\t),\n\t),\n\tmask: optionalShape(\n\t\tstringShape({\n\t\t\tmin: 1,\n\t\t\tdescription: \"The mask character 'password' renders in place of input.\",\n\t\t}),\n\t),\n\tmin: optionalShape(\n\t\tintegerShape({ min: 0, description: \"The minimum number of 'checkbox' selections required.\" }),\n\t),\n\tmax: optionalShape(\n\t\tintegerShape({ min: 0, description: \"The maximum number of 'checkbox' selections allowed.\" }),\n\t),\n\tvalidate: optionalShape(\n\t\tobjectShape({\n\t\t\trequired: optionalShape(booleanShape({ description: 'Reject an empty (trimmed) input.' })),\n\t\t\tminimum: optionalShape(\n\t\t\t\tintegerShape({\n\t\t\t\t\tmin: 0,\n\t\t\t\t\tdescription: 'Reject an input shorter than this many characters.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\tmaximum: optionalShape(\n\t\t\t\tintegerShape({\n\t\t\t\t\tmin: 0,\n\t\t\t\t\tdescription: 'Reject an input longer than this many characters.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\tpattern: optionalShape(\n\t\t\t\tstringShape({\n\t\t\t\t\tdescription: 'Reject an input that fails this regular-expression source.',\n\t\t\t\t}),\n\t\t\t),\n\t\t\temail: optionalShape(booleanShape({ description: 'Require a valid email-address shape.' })),\n\t\t\turl: optionalShape(booleanShape({ description: 'Require a valid URL shape.' })),\n\t\t\tnumeric: optionalShape(booleanShape({ description: 'Require a numeric value.' })),\n\t\t\tinteger: optionalShape(booleanShape({ description: 'Require an integer value.' })),\n\t\t\talphanumeric: optionalShape(\n\t\t\t\tbooleanShape({ description: 'Require letters and digits only.' }),\n\t\t\t),\n\t\t}),\n\t),\n\ttimeout: optionalShape(\n\t\tintegerShape({ min: 0, description: 'Milliseconds to wait before the prompt expires.' }),\n\t),\n})\n\n/**\n * The shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated\n * by `operation`: `'pending'` lists the prompts addressed to this tool's terminal, `'answer'`\n * resolves one by `id` with a `value`.\n *\n * @remarks\n * `value`'s type varies by the ORIGINAL prompt's form (`string` for `'input'` / `'password'` /\n * `'select'` / `'editor'`, `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`) —\n * `unionShape(stringShape(), booleanShape(), arrayShape(stringShape()))` expresses that\n * union directly, so `value` is typed as the full `string | boolean | readonly string[]` union\n * here (no lossy string-only fallback needed).\n */\nexport const answerToolShape = unionShape(\n\tobjectShape({\n\t\toperation: literalShape(['pending'], {\n\t\t\tdescription: 'List the prompts currently addressed to this terminal.',\n\t\t}),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['answer'], { description: 'Answer one pending prompt by id.' }),\n\t\tid: stringShape({ min: 1, description: 'The id of the pending prompt to answer.' }),\n\t\tvalue: unionShape(\n\t\t\tstringShape({ description: 'A text / select / editor answer.' }),\n\t\t\tbooleanShape({ description: 'A confirm answer.' }),\n\t\t\tarrayShape(stringShape(), { description: 'A checkbox answer — the checked values.' }),\n\t\t),\n\t}),\n)\n\n// Toolbox shapes — the shape VALUE each `create*Tool` factory (factories.ts) compiles into\n// the lockstep guard + parser + JSON Schema outputs (AGENTS §14). `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 * 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 should carry 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 * 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 * The shape of a {@link import('./types.js').TaskDraft} — identical to a strict task shape\n * EXCEPT `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\trun: 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 * The shape of a PHASE in a draft workflow — identical to a strict phase shape EXCEPT `id` and\n * `name` are OPTIONAL, and its tasks are {@link taskDraftShape}s.\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 * The shape of a DRAFT workflow — identical to a strict workflow shape EXCEPT `id` and `name`\n * are OPTIONAL at all three levels (workflow / phase / task), so a small model can omit the six\n * identity strings and let the tool synthesize them positionally.\n *\n * @remarks\n * The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.\n * `run` 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 * The shape of ONE flat step — `{ name }` — the building block of {@link workflowStepsShape}.\n *\n * @remarks\n * `name` is the REGISTERED behavior name the step runs (it becomes the task's `run`). 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 run).',\n\t}),\n})\n\n/**\n * The FLAT authoring shape {@link import('./factories.js').createWorkflowTool} advertises as its\n * `parameters` — the simplest surface a small model can fill: `{ 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 * The shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union\n * over the 13 workspace edit / read / navigation operations, discriminated by the `operation`\n * literal (never a bare `kind`; AGENTS §4.4). Each variant leads with its `operation`\n * discriminant then its FLAT fields, every field via `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 + 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 four `'splice'`\n * caret components are POSITIVE integers (`integerShape({ min: 1 })`); `regex` / `sensitive`\n * are `optionalShape(booleanShape(...))`. The two 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 (SRC-2 — the tool factory itself; SRC-1 landed the persistence + the\n// TableSpec DSL this shape's `tables` field compiles the SAME way `expandTables` does)\n\n/** A {@link import('./types.js').ColumnKind} literal — the leaf {@link columnSpecShape} wraps. */\nexport const columnKindShape = literalShape(['string', 'integer', 'number', 'boolean'], {\n\tdescription: 'A column type: \"string\" | \"integer\" | \"number\" | \"boolean\".',\n})\n\n/** A {@link import('./types.js').ColumnSpec} — a bare {@link columnKindShape}, or `{ type, optional }`. */\nexport const columnSpecShape = unionShape(\n\tcolumnKindShape,\n\tobjectShape({\n\t\ttype: columnKindShape,\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/** 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, { description: 'Column name to its type.' }),\n\t}),\n\t{ description: 'Table name to its column layout.' },\n)\n\n/** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */\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/** A loose row — a flat object of column name to JSON value; the array form (multiple rows) resolves FIRST per AGENTS §9.2. */\nexport const rowShape = recordShape(jsonShape(), {\n\tdescription: 'A row as a flat object of column name to value.',\n})\n\n/** One or many loose rows — the array form resolves FIRST per AGENTS §9.2. */\nexport const rowsShape = unionShape(\n\tarrayShape(rowShape, { description: 'Multiple rows.' }),\n\trowShape,\n)\n\n/** One SERIALIZED WHERE condition — `values` is ALWAYS an array, even for a single-value operator. */\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/** One sort term. */\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/** 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 * The shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —\n * discriminated by `operation` into the 11 database operations (`'create'` / `'tables'` /\n * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /\n * `'remove'` / `'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 via\n * {@link import('./helpers.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, SRC-3)\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/** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */\nexport const relationKeyShape = 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/** 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/** Flat dot-path relation include list, expanded via {@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, e.g. \"contacts.account\".',\n\t\t}),\n\t\t{ description: 'Which relations to attach, as flat dot-paths.' },\n\t),\n)\n\n/** 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 * The shape of {@link import('./factories.js').createRelationTool}'s call arguments —\n * discriminated by `operation` into the 5 relation operations (`'load'` / `'find'` / `'link'` /\n * `'unlink'` / `'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: relationKeyShape,\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 * 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 { PromptType } from '@orkestrel/terminal'\nimport type { TableMap } from '@orkestrel/database'\nimport type { DatabaseErrorCode } from '@orkestrel/database'\nimport type {\n\tInclude,\n\tModelInterface,\n\tRelationErrorCode,\n\tRelationManagerInterface,\n} from '@orkestrel/relation'\nimport type { Condition, ConditionConnector, OrderDirection, QueryInput } from '@orkestrel/database'\nimport type { ContractShape } from '@orkestrel/contract'\nimport type {\n\tAgentFunction,\n\tToolboxErrorCode,\n\tColumnKind,\n\tColumnSpec,\n\tDatabaseDefinition,\n\tTableSpec,\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 { ToolboxError } from './errors.js'\nimport {\n\tattempt,\n\tbooleanShape,\n\tintegerShape,\n\tisFiniteNumber,\n\tisNonEmptyString,\n\tisRecord,\n\tisString,\n\tnumberShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\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 * The ancestry identifier of a workflow in a run chain — `workflow:<id>`.\n *\n * @remarks\n * Namespacing keeps a workflow id and an {@link agentTag} 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 workflowTag(id: string): string {\n\treturn `workflow:${id}`\n}\n\n/**\n * The ancestry identifier of an agent in a run chain — `agent:<name>`.\n *\n * @remarks\n * The agent counterpart of {@link workflowTag}: {@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 agentTag(name: string): string {\n\treturn `agent:${name}`\n}\n\n/**\n * Narrow an unknown value to a valid alternating workflow lineage.\n *\n * @param value - The value to inspect\n * @returns Whether `value` is a unique, nonempty-tagged workflow/agent chain\n */\nexport function isWorkflowLineage(value: unknown): value is WorkflowLineage {\n\tconst inspected = attempt(() => {\n\t\tif (!Array.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 * Build a validated, copied, and frozen workflow lineage value.\n *\n * @param lineage - The configured chain; omitted means a direct root\n * @returns An immutable caller-isolated lineage\n */\nexport function lineageOf(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 * Append one tag to a workflow lineage and return 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 lineageOf([...lineage, tag])\n}\n\n/**\n * Derive 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 = lineageOf(lineage)\n\tconst workflows = current.filter((tag) => tag.startsWith('workflow:')).length\n\treturn Math.max(0, workflows - 1)\n}\n\n/**\n * Narrow an unknown callable to Toolbox's frozen contextual agent adapter metadata.\n *\n * @param value - The value to inspect\n * @returns Whether it is a frozen {@link AgentFunction} with a frozen valid lineage\n */\nexport function isAgentFunction(value: unknown): value is AgentFunction {\n\tconst inspected = attempt(() => {\n\t\tif (typeof value !== 'function' || !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 * Build the plain success summary {@link import('./factories.js').createWorkflowTool} returns on\n * a completed run — the universal tool-handler contract (AGENTS §14): return a plain value on\n * success, appearing 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 workflowToolSummary(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 + 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\n// the six required `id`/`name` strings. The factory re-validates the result against the STRICT\n// `createWorkflowContract().is` gate before running (soundness).\n\n/**\n * Complete a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesize any\n * MISSING `id` deterministically + positionally, and default any MISSING `name` to its\n * (now-resolved) `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 has both. `run`, `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/name optional at all three 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 * Complete 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 * Complete 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.run === undefined ? {} : { run: task.run }),\n\t\t...(task.retries === undefined ? {} : { retries: task.retries }),\n\t\t...(task.timeout === undefined ? {} : { timeout: task.timeout }),\n\t}\n}\n\n/**\n * Expand 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 `run` (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 two 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: [{ run: step.name }],\n\t\t})),\n\t})\n}\n\n// === Terminal-tool answer coercion + error-code mapping (the tool's answer surface)\n\n/**\n * Normalize an LLM-supplied answer `value` to the type {@link PromptType} `form` expects, so a\n * caller that only ever emits strings can still answer a typed prompt.\n *\n * @remarks\n * `'confirm'` coerces to a `boolean` — a `boolean` passes through, and the strings `'true'` /\n * `'false'` (case-insensitively) map to it; any other string is truthy-coerced via\n * `Boolean(value)`. `'checkbox'` coerces to `readonly string[]` — an array passes through\n * (stringifying each entry), a comma-separated string splits + trims into one, and any other\n * single (non-comma) string becomes a one-item array. Every other form (`'input'` / `'password'`\n * / `'select'` / `'editor'`) coerces to a plain `string` — a string passes through verbatim; a\n * non-string, non-object scalar (`number` / `boolean`) stringifies via `String(value)`; an\n * object or array (no lossless string form) falls back to `''` rather than serializing garbage.\n * Pure and total — never throws.\n *\n * @param form - The {@link PromptType} the answer is being coerced FOR\n * @param value - The raw, LLM-supplied answer value\n * @returns The coerced answer — `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`,\n * `string` otherwise\n */\nexport function coerceAnswer(\n\tform: PromptType,\n\tvalue: unknown,\n): string | boolean | readonly string[] {\n\tif (form === 'confirm') {\n\t\tif (typeof value === 'boolean') return value\n\t\tif (typeof value === 'string') {\n\t\t\tconst lower = value.trim().toLowerCase()\n\t\t\tif (lower === 'true') return true\n\t\t\tif (lower === 'false') return false\n\t\t}\n\t\treturn Boolean(value)\n\t}\n\tif (form === 'checkbox') {\n\t\tif (Array.isArray(value)) return value.map((entry) => String(entry))\n\t\tif (typeof value === 'string') {\n\t\t\tif (value.includes(',')) return value.split(',').map((entry) => entry.trim())\n\t\t\treturn [value]\n\t\t}\n\t\treturn [String(value)]\n\t}\n\t// The remaining text-shaped forms ('input'/'password'/'select'/'editor').\n\tif (typeof value === 'string') return value\n\tif (typeof value === 'object' && value !== null) return ''\n\treturn String(value)\n}\n\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the terminal-tool factory should throw\n * with — the 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'`, `'CANCEL'`, `'DRIVER'`) maps to the generic `'TOOL'` code. The mapper only\n * 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 terminalToolCode(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-tool foundation (SRC-1 — persistence + the TableSpec DSL; the tool factories land\n// in a later unit) — the config-only `DatabaseDefinition` compiles into a live `@orkestrel/database`\n// `TableMap`, and its store twins narrow an untrusted persisted blob back to the type.\n\n/** Narrow an unknown value to a {@link ColumnSpec} — a valid {@link import('./types.js').ColumnKind} shorthand, or `{ type, optional }` with a valid `type`. */\nexport function isColumnSpec(value: unknown): value is ColumnSpec {\n\tif (isColumnKind(value)) return true\n\tif (!isRecord(value)) return false\n\treturn (\n\t\tisColumnKind(value.type) &&\n\t\t(value.optional === undefined || typeof value.optional === 'boolean')\n\t)\n}\n\n/** Narrow an unknown value to a {@link import('./types.js').ColumnKind}. */\nexport function isColumnKind(value: unknown): value is ColumnKind {\n\treturn value === 'string' || value === 'integer' || value === 'number' || value === 'boolean'\n}\n\n/**\n * Compile 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, kind] of Object.entries(definition.columns)) {\n\t\t\tcolumns[column] = columnShape(kind)\n\t\t}\n\t\ttables[table] = columns\n\t}\n\treturn tables\n}\n\n/** Compile one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf {@link expandTables} maps over. */\nexport function columnShape(spec: ColumnSpec): ContractShape {\n\tconst kind = isString(spec) ? spec : spec.type\n\tconst optional = !isString(spec) && spec.optional === true\n\tconst shape = kindShape(kind)\n\treturn optional ? optionalShape(shape) : shape\n}\n\n/** Map one {@link import('./types.js').ColumnKind} to its primitive `@orkestrel/database` shape — the leaf {@link columnShape} wraps. */\nexport function kindShape(kind: ColumnKind): ContractShape {\n\tif (kind === 'string') return stringShape()\n\tif (kind === 'integer') return integerShape()\n\tif (kind === 'number') return numberShape()\n\treturn booleanShape()\n}\n\n/**\n * Narrow an unknown value to a {@link DatabaseDefinition} — a non-empty `id` + `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 */\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 (!Array.isArray(groups)) return false\n\t\t\tfor (const group of groups) {\n\t\t\t\tif (!Array.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\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the upcoming database tool should throw\n * with — the pure classification step of that factory's error handling, mirroring\n * {@link terminalToolCode}'s idiom for `@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 databaseToolCode(error: unknown): DatabaseErrorCode | undefined {\n\treturn isDatabaseError(error) ? error.code : undefined\n}\n\n/**\n * Map a caught error to the {@link ToolboxErrorCode} the upcoming relation tool should throw\n * with — the pure classification step of that factory's error handling, mirroring\n * {@link terminalToolCode}'s idiom for `@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 relationToolCode(error: unknown): RelationErrorCode | undefined {\n\treturn isRelationError(error) ? error.code : undefined\n}\n\n/**\n * Expand 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 = typeof existing === 'object' ? 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 * Resolve 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 relationManagerOf(\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 * Resolve 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 relationManagerOf}'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 relationModelOf(manager: RelationManagerInterface, name: string): 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.models(),\n\t\t})\n\t}\n\treturn manager.model(name)\n}\n\n// === Database-tool operation leaves (SRC-2 — `createDatabaseTool` itself)\n\n/**\n * Normalize the database tool's parsed SERIALIZED query into a live `@orkestrel/database`\n * {@link QueryInput} — default each condition's OMITTED `connector` 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 queryOf(\n\tquery:\n\t\t| Readonly<{\n\t\t\t\tconditions?: ReadonlyArray<\n\t\t\t\t\tReadonly<{\n\t\t\t\t\t\tcolumn: string\n\t\t\t\t\t\toperator: Condition['operator']\n\t\t\t\t\t\tvalues: readonly unknown[]\n\t\t\t\t\t\tconnector?: ConditionConnector\n\t\t\t\t\t}>\n\t\t\t\t>\n\t\t\t\torder?: ReadonlyArray<Readonly<{ column: string; direction: OrderDirection }>>\n\t\t\t\tlimit?: number\n\t\t\t\toffset?: number\n\t\t }>\n\t\t| undefined,\n): 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 * Clamp a `'records'` call's query to a row cap, and build the PROBE query the caller reads\n * with — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation\n * uses to detect truncation without a separate `count` round trip.\n *\n * @remarks\n * The effective limit is `min(query?.limit ?? cap, cap)`, floored at `0` (so a caller can never\n * exceed the configured cap by supplying a larger `query.limit`). 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(\n\tquery: QueryInput | undefined,\n\tcap: number,\n): Readonly<{ query: QueryInput; limit: number }> {\n\tconst limit = Math.max(0, Math.min(query?.limit ?? cap, cap))\n\treturn { query: { ...query, limit: limit + 1 }, limit }\n}\n","import type { DatabaseDefinition, DefinitionStoreInterface } from '../types.js'\n\n/**\n * 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. The EXACT twin of\n * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}.\n *\n * @remarks\n * A plain `Map<string, DatabaseDefinition>` (AGENTS §21 — 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 §22 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\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\tset(definition: DatabaseDefinition): Promise<void> {\n\t\t// Insert / replace under the definition's OWN id (no separate id param).\n\t\tthis.#definitions.set(definition.id, structuredClone(definition))\n\t\treturn Promise.resolve()\n\t}\n\n\tdelete(id: string): Promise<void> {\n\t\t// Drop by id; `Map.delete` of an absent id is already a no-op (no throw).\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 '../helpers.js'\n\n/**\n * 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('../helpers.js').isDatabaseDefinition} — the\n * AGENTS §14 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 §22 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 * Wrap 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/** Resolve the persisted definition for `id`, narrowing the opaque JSON column back to a `DatabaseDefinition`. */\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 (AGENTS\n\t\t// §14); a malformed blob resolves `undefined`, never a broken definition.\n\t\treturn isDatabaseDefinition(row.definition) ? row.definition : undefined\n\t}\n\n\t/** Insert or replace under the definition's OWN `id` (no separate id param) — the row is `{ id, definition }`. */\n\tasync set(definition: DatabaseDefinition): Promise<void> {\n\t\tawait this.#table.set({ id: definition.id, definition })\n\t}\n\n\t/** Drop a definition by id; an absent id is a no-op (no throw). */\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 '../helpers.js'\n\n/**\n * Resolve database definitions into cached live handles for database tools.\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 * Create 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 * Determine whether a live database is cached by id.\n\t *\n\t * @param id - Database id\n\t * @returns Whether a live handle is cached\n\t */\n\thas(id: string): boolean {\n\t\treturn this.#handles.has(id)\n\t}\n\n\t/**\n\t * Read 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 * Cache 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 * Remove 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 * Resolve a cached or stored database by id.\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\tWorkflowFunctions,\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\tisRecord,\n\tparseJSONValue,\n\trawShape,\n\tsamplesToSchema,\n\tschemaToObject,\n\tschemaToParameters,\n\tschemaToShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { isTerminalError } from '@orkestrel/terminal'\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_DEPTH,\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\tagentTag,\n\tclampQuery,\n\tcoerceAnswer,\n\tcompleteDraft,\n\tderiveWorkflowDepth,\n\textendLineage,\n\tlineageOf,\n\tqueryOf,\n\tdatabaseToolCode,\n\texpandInclude,\n\texpandSteps,\n\texpandTables,\n\trelationManagerOf,\n\trelationModelOf,\n\trelationToolCode,\n\tterminalToolCode,\n\tisAgentFunction,\n\tworkflowTag,\n\tworkflowToolSummary,\n} from './helpers.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 * Wrap 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`.\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(await tool.execute(controller.input))\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 * Wrap 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_DEPTH} 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 = lineageOf(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 = workflowTag(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_DEPTH) {\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_DEPTH,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst tag = agentTag(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 * Compose 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): WorkflowFunctions {\n\tconst lineage = lineageOf(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: WorkflowFunctions =\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 (typeof fn !== 'function') {\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 * Compile the lenient workflow draft contract used by {@link createWorkflowTool}.\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 * Wrap a {@link WorkflowDefinition} as an LLM-callable tool — it ADVERTISES the SIMPLE flat\n * authoring shape (`{ name?, steps: [{ name }] }`) as its `parameters` so even a small model can\n * author a complete tree, and its handler EXPANDS / COMPLETES the authored blob, validates it\n * against the STRICT contract, and runs it through `runner`, forwarding the caller's optional\n * 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 + runner stay STRICT and\n * unchanged).** A 2B model reliably CALLS the tool but cannot reliably emit the full four-level\n * nested {@link WorkflowDefinition} (six required `id`/`name` strings, an all-or-nothing tree).\n * So the tool ACCEPTS three authoring forms 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 (AGENTS §14): 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\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 = lineageOf(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 +\n\t\t\t// expanded; otherwise the nested DRAFT form, parsed + completed. A parse failure leaves\n\t\t\t// `target` undefined ⇒ the strict gate below 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 (Array.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 = workflowTag(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_DEPTH) {\n\t\t\t\tthrow new ToolboxError('DEPTH', `nested workflow exceeds max depth ${MAX_WORKFLOW_DEPTH}`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tdepth,\n\t\t\t\t\tmax: MAX_WORKFLOW_DEPTH,\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 workflowToolSummary(result)\n\t\t},\n\t})\n}\n\n/**\n * Build an LLM-callable workspace-editing tool — it ADVERTISES the `operation`-discriminated\n * 13-op union ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its\n * handler PARSES the model-supplied args against that contract and DISPATCHES the matched\n * operation against the manager's ACTIVE workspace (the registry ops drive the manager itself),\n * returning the plain result. A malformed operation throws this package's `ToolboxError`; a\n * genuine workspace-domain failure propagates `@orkestrel/workspace`'s typed `WorkspaceError`.\n * EITHER drives a caller-supplied {@link WorkspaceToolOptions.manager} directly, OR\n * constructs a fresh `WorkspaceManagerInterface` (`@orkestrel/workspace`) over\n * {@link import('./types.js').WorkspaceToolOptions.store} (via `@orkestrel/workspace`'s\n * `createWorkspaceManager`); neither given constructs a manager backed by\n * `@orkestrel/workspace`'s in-memory store default.\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. Two 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 + activates a default\n * workspace (`manager.add()`) so the model can just 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 (AGENTS §14): 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 (`MODALITY` / `PATTERN` / `RANGE`) PROPAGATE\n * uncaught. The range edit is the FLAT `'splice'` op: its four 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 / read ops target the ACTIVE workspace. A WRITING op ensures a target — auto-creating\n\t\t\t// + activating a default workspace when none is active (the no-active ergonomic seam) — while\n\t\t\t// a pure-READ 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 * Build an LLM-callable sub-agent delegation tool — 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 (AGENTS §14): 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 via\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} — both 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 = agentTag(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 * Build 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 * (`AGENT_TOOL_SUMMARY` / `WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY`).\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 via `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 (AGENTS §14): 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 * Build an LLM-callable prompt tool — the ASK side of the terminal seam. Asks\n * {@link import('./types.js').PromptToolOptions.to} a question and BLOCKS until it answers,\n * returning the resolved answer value.\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): validates the call args against\n * {@link import('./shapers.js').promptToolShape}, dispatches to the matching\n * `TerminalManagerInterface.ask` overload (`@orkestrel/terminal`) for the call's `form`, and\n * RETURNS the resolved answer on success. `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 prompt CYCLE rejects with\n * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`\n * {@link import('./errors.js').ToolboxError}; an expired prompt re-surfaces as `EXPIRE`; an\n * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal\n * plus the known ones (`manager.terminals()`).\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\tif (\n\t\t\t\t(call.form === 'select' || call.form === 'checkbox') &&\n\t\t\t\t(call.choices ?? []).length === 0\n\t\t\t) {\n\t\t\t\tthrow new ToolboxError('TOOL', 'select/checkbox requires at least one choice', {\n\t\t\t\t\tto: call.to,\n\t\t\t\t\tform: call.form,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tswitch (call.form) {\n\t\t\t\t\tcase 'input':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'editor':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'password':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.mask === undefined ? {} : { mask: call.mask }),\n\t\t\t\t\t\t\t...(call.validate === undefined ? {} : { validate: call.validate }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'confirm':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default === 'true' }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'select':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\tchoices: call.choices ?? [],\n\t\t\t\t\t\t\t...(call.default === undefined ? {} : { default: call.default }),\n\t\t\t\t\t\t})\n\t\t\t\t\tcase 'checkbox':\n\t\t\t\t\t\treturn await options.manager.ask(options.from, call.to, call.form, {\n\t\t\t\t\t\t\tmessage: call.message,\n\t\t\t\t\t\t\tchoices: call.choices ?? [],\n\t\t\t\t\t\t\t...(call.min === undefined ? {} : { min: call.min }),\n\t\t\t\t\t\t\t...(call.max === undefined ? {} : { max: call.max }),\n\t\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst code = terminalToolCode(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 form a prompt 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(\n\t\t\t\t\t\t'EXPIRE',\n\t\t\t\t\t\t`prompt to '${call.to}' expired before it was answered`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tto: call.to,\n\t\t\t\t\t\t},\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\tknown: options.manager.terminals(),\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 * Build an LLM-callable answer tool — the ANSWER side of the terminal seam. Lists the prompts\n * currently addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of\n * them by id.\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): validates the call args against\n * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`\n * returns a compact list (`{ id, from, form, message }`) of every prompt currently addressed to\n * `to` (`TerminalManagerInterface.pending`, `@orkestrel/terminal`). `'answer'` looks the prompt\n * up by `id` (an unknown id throws a typed `ANSWER` {@link import('./errors.js').ToolboxError}),\n * normalizes the model-supplied `value` to the prompt's own form\n * ({@link import('./helpers.js').coerceAnswer}), and applies it via\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 prompt 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 prompts 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((prompt) => ({\n\t\t\t\t\tid: prompt.id,\n\t\t\t\t\tfrom: prompt.from,\n\t\t\t\t\tform: prompt.form,\n\t\t\t\t\tmessage: prompt.message,\n\t\t\t\t}))\n\t\t\t}\n\t\t\tconst prompt = options.manager.pending(options.to).find((entry) => entry.id === call.id)\n\t\t\tif (prompt === undefined) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `unknown prompt '${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\tconst coerced = coerceAnswer(prompt.form, call.value)\n\t\t\tconst result = options.manager.answer(options.to, call.id, coerced)\n\t\t\tif (!result.success) {\n\t\t\t\tthrow new ToolboxError('ANSWER', `failed to answer prompt '${call.id}': ${result.error}`, {\n\t\t\t\t\tid: call.id,\n\t\t\t\t\treason: result.error,\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 (SRC-1 — the tool factories land in a later unit)\n\n/**\n * Create the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database\n * definitions, the DEFAULT store the upcoming database / relation tools will persist their\n * `DatabaseDefinition` 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 * Create 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 (SRC-2 — createDatabaseTool itself)\n\n/**\n * Build an LLM-callable database tool — create, query, and mutate `@orkestrel/database`\n * databases through one `operation`-discriminated call (AGENTS §14, matching\n * {@link createWorkspaceTool}'s single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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('./helpers.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}) via\n * {@link import('./helpers.js').clampQuery}, reporting `truncated` when storage held more rows\n * than the cap. Every operation's `query` is normalized via\n * {@link import('./helpers.js').queryOf} (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').databaseToolCode}); 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 * \toperation: 'create',\n * \tid: 'shop',\n * \ttables: { products: { columns: { name: 'string', price: 'number' } } },\n * })\n * ```\n */\nexport function createDatabaseTool(options: DatabaseToolOptions = {}): ToolInterface {\n\tif (\n\t\toptions.timeout !== undefined &&\n\t\t(options.timeout < 0 || !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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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(queryOf(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(queryOf(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\tqueryOf(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 = Array.isArray(call.row)\n\t\t\t\t\t\tconst rows = Array.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 = Array.isArray(call.row)\n\t\t\t\t\t\tconst rows = Array.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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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 = Array.isArray(call.key)\n\t\t\t\t\t\tconst keys = Array.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 = databaseToolCode(error)\n\t\t\t\tif (code === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', error instanceof 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 (SRC-3 — createRelationTool, the final unit of the database / relation spine)\n\n/**\n * Build an LLM-callable relation tool — traverse and edit `@orkestrel/relation` relationships\n * through one `operation`-discriminated call (AGENTS §14, matching {@link createDatabaseTool}'s\n * single-tool-many-operations shape).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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').relationManagerOf}) — then resolves `model` against it\n * ({@link import('./helpers.js').relationModelOf}, 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 via {@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, AGENTS §9.2) or a single key. `'find'` and `'links'` clamp their\n * result to {@link import('./types.js').RelationToolOptions.limit} (default\n * {@link import('./constants.js').RELATION_TOOL_LIMIT}) — `'find'` probes one row past the\n * effective limit (mirroring {@link import('./helpers.js').clampQuery}'s idiom) to report\n * `truncated`; `'links'` (which has no upstream pagination) fetches the FULL linked-key list and\n * 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({ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] })\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 = relationManagerOf(options.managers, call.manager)\n\t\t\t\tconst model = relationModelOf(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 (typeof call.key === 'string' || typeof call.key === 'number') {\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 = Math.min(call.limit ?? cap, 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 keys = await model.links(call.key, call.relation)\n\t\t\t\t\t\tconst truncated = keys.length > cap\n\t\t\t\t\t\tconst sliced = keys.slice(0, cap)\n\t\t\t\t\t\treturn { keys: sliced, count: sliced.length, truncated, limit: cap }\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 = relationToolCode(error)\n\t\t\t\tif (relation !== undefined) {\n\t\t\t\t\tthrow new ToolboxError(\n\t\t\t\t\t\t'RELATION',\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcode: relation,\n\t\t\t\t\t\t\toperation: call.operation,\n\t\t\t\t\t\t\tmodel: call.model,\n\t\t\t\t\t\t\t...('relation' in call ? { relation: call.relation } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst database = databaseToolCode(error)\n\t\t\t\tif (database === undefined) throw error\n\t\t\t\tthrow new ToolboxError('DATABASE', error instanceof 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 * Build a standalone LLM-callable tool that infers a JSON Schema from example values — the\n * utility half of the \"existing API/DB → MCP tool\" bridge (the other half,\n * {@link createEndpointTool}, wraps one CONCRETE endpoint).\n *\n * @remarks\n * The universal tool-handler contract (AGENTS §14): 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 via `@orkestrel/contract`'s\n * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` via `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 (via `@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\", i.e. 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 guarantee (AGENTS §14), a `valid: true` entry is\n * ALWAYS also `coercible: true`. `@orkestrel/contract` 0.0.7'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, since\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 all three\n * and yields a bounded, non-throwing per-candidate verdict; a NON-JSON-safe candidate (e.g. 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 * Wrap one CONCRETE endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable\n * `ToolInterface` — the endpoint half of the \"existing API/DB → MCP tool\" bridge (the other half,\n * {@link createInferTool}, is a standalone inference utility).\n *\n * @remarks\n * `parameters` is inferred ONCE at construction from `definition.samples` via\n * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s\n * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` via `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` 0.0.7's `schemaToShape` compiles it ONCE (via `createContract`) into a\n * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.invoke` — 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.invoke` receives the COERCED value (e.g. `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.invoke` 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`, `execute` PASSES THROUGH the model-supplied `args` to `definition.invoke`\n * WITHOUT re-validation — the pre-0.0.7 behavior, preserved as an explicit opt-out. Either way,\n * `invoke`'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 * (AGENTS §14) — 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 + 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 * \tinvoke: (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 `invoke`\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 * // `invoke` 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) {\n\t\t\t\treturn definition.invoke(args)\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) {\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\tf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