@orkestrel/tool 0.0.6 → 0.0.8

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","#key","#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// Tool-package constants — UPPER_SNAKE, `Object.freeze`d, every member exported (AGENTS §5).\n// The workflow tool's name/description/examples/depth-bound and the workspace tool's\n// name/description are OWNED here now — ported byte-faithfully from `@orkestrel/workflow` /\n// `@orkestrel/agent` ahead of the upstream cleanup that drops the authoring surface from those\n// packages (this package becomes the defining home). Only the net-new agent tool's constants\n// were already net-new to this package.\n\n/**\n * The name {@link import('./factories.js').createAgentTool} advertises by default — the key a\n * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) 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 DESCRIPTION {@link import('./factories.js').createAgentTool} advertises — a short guide\n * that teaches a model how to delegate a task to a sub-agent.\n *\n * @remarks\n * Mirrors {@link WORKFLOW_TOOL_DESCRIPTION} / `WORKSPACE_TOOL_DESCRIPTION`'s teaching style: names\n * the required `task` field, and documents the optional per-call `provider` / `tools` /\n * `system` overrides.\n */\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createAgentTool}\n * advertises in place of {@link AGENT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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 * OWNED here now (ported from `@orkestrel/workflow`, whose engine no longer uses it — only the\n * tool-authoring guards this package now owns consume it). The limit lives in ONE place: an\n * agent-function-wrapped agent running at this depth can no longer author + run a NESTED\n * workflow through its bound workflow tool (that would be depth `MAX_WORKFLOW_DEPTH + 1`), so\n * the over-deep invocation is REJECTED (a typed `DEPTH` `WorkflowError` throw, `@orkestrel/workflow`).\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/agent`) 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 * OWNED here now (ported from `@orkestrel/workflow`). 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 * OWNED here now (ported from `@orkestrel/workflow`). 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 * OWNED here now (ported from `@orkestrel/workflow`). 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 DESCRIPTION {@link import('./factories.js').createWorkflowTool} advertises — a multi-line\n * guide that teaches a small model how to author a complete workflow tree.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/workflow`). Presents the SIMPLE flat shape\n * (`{ name, steps: [{ name }] }`) as the PRIMARY way with one complete worked example\n * ({@link WORKFLOW_TOOL_FLAT_EXAMPLE}), names that a step's `name` is a REGISTERED name (not a\n * human label), and documents the full nested `WorkflowDefinition` as the ADVANCED form with a\n * minimal example ({@link WORKFLOW_TOOL_NESTED_EXAMPLE}). The `parameters` the tool advertises\n * are the FLAT shape's schema; the nested form is the documented escape-hatch (the tool accepts\n * both).\n */\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkflowTool}\n * advertises in place of {@link WORKFLOW_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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'- the top-level \"name\" (the workflow name) is optional. 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 has a \"run\" (a registered behavior name):',\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/agent`) registers under.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/agent`).\n */\nexport const WORKSPACE_TOOL_NAME = 'workspace'\n\n/**\n * A valid `WorkspaceOperation` (`@orkestrel/agent`) object — the canonical example embedded\n * VERBATIM in {@link WORKSPACE_TOOL_DESCRIPTION}.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/agent`). 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 DESCRIPTION {@link import('./factories.js').createWorkspaceTool} advertises — a multi-line\n * guide that teaches a small model how to drive a workspace through the single\n * `operation`-keyed tool.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/agent`). Mirrors {@link WORKFLOW_TOOL_DESCRIPTION}'s\n * teaching style: names the `operation` discriminant field, enumerates all 13 operations with\n * their FLAT fields, gives a worked example for the common ones, and embeds\n * {@link WORKSPACE_TOOL_EXAMPLE} verbatim.\n */\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkspaceTool}\n * advertises in place of {@link WORKSPACE_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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, \"exact\"?: bool, \"limit\"?: int } — find lines matching the query across all files.',\n\t'- replace { \"operation\": \"replace\", \"query\": \"<text>\", \"replacement\": \"<text>\", \"regex\"?: bool, \"exact\"?: 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), \"exact\" 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/agent`) 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/agent').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/agent`) registers under.\n */\nexport const PROMPT_TOOL_NAME = 'ask'\n\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createPromptTool}\n * advertises in place of {@link PROMPT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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/agent`) registers under.\n */\nexport const ANSWER_TOOL_NAME = 'answer'\n\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createAnswerTool}\n * advertises in place of {@link ANSWER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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/agent`) 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/agent').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, migrate, destroy), chosen by the 'operation' field. Call describe('database') for the full operation list, the criteria 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 criteria form, and the {@link import('./types.js').TableSpec}\n * column DSL.\n *\n * @remarks\n * The criteria 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 } } } } } — 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>\", \"criteria\"?: <Criteria> } — list rows matching criteria.',\n\t'- count { \"operation\": \"count\", \"id\": \"<database id>\", \"table\": \"<table>\", \"criteria\"?: <Criteria> } — count rows matching criteria.',\n\t'- aggregate { \"operation\": \"aggregate\", \"id\": \"<database id>\", \"table\": \"<table>\", \"column\": \"<column>\", \"function\": \"count\" | \"sum\" | \"average\" | \"minimum\" | \"maximum\", \"criteria\"?: <Criteria> } — 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>\", \"row\": { ... } } — patch an existing row.',\n\t'- remove { \"operation\": \"remove\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — delete a row by key.',\n\t'- migrate { \"operation\": \"migrate\", \"id\": \"<database id>\", \"tables\": { ... } } — replace the table layout in place.',\n\t'- destroy { \"operation\": \"destroy\", \"id\": \"<database id>\" } — drop a database entirely.',\n\t'',\n\t'Criteria 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\"/\"migrate\" \"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'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 with criteria:',\n\tJSON.stringify({\n\t\toperation: 'records',\n\t\tid: 'shop',\n\t\ttable: 'products',\n\t\tcriteria: { conditions: [{ column: 'price', operator: 'below', values: [50] }] },\n\t}),\n].join('\\n')\n\n/** The default cap on rows a `records` / `remove` call returns (or acts on) when the caller omits `criteria.limit` — the upcoming database tool's default row ceiling. */\nexport const DATABASE_TOOL_LIMIT = 1000\n\n/** The database tool's mutating operations — disabled by `DatabaseToolOptions.readonly`. */\nexport const DATABASE_TOOL_MUTATIONS = new Set([\n\t'create',\n\t'add',\n\t'set',\n\t'update',\n\t'remove',\n\t'migrate',\n\t'destroy',\n])\n\n/**\n * The name `createRelationTool` advertises by default — the key a model calls and the\n * `ToolManagerInterface` (`@orkestrel/agent`) registers under.\n */\nexport const RELATION_TOOL_NAME = 'relation'\n\n/**\n * The lean {@link import('@orkestrel/agent').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/agent`) registers under.\n */\nexport const INFER_TOOL_NAME = 'infer'\n\n/**\n * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createInferTool}\n * advertises in place of {@link INFER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`\n * (`@orkestrel/agent`) 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\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 { AgentToolErrorCode } from './types.js'\n\n// Tool-package errors — one error class per domain this package mints its own error for.\n// `@orkestrel/workflow`'s `WorkflowError` and `@orkestrel/agent`'s `WorkspaceError` already\n// cover the workflow tool + workspace tool's failure paths (imported and thrown as-is, never\n// duplicated here per §6). `createAgentTool` / `createDescribeTool` are net-new and none of\n// `@orkestrel/agent`'s error classes fit a pre-run validation / guard failure (`AgentJobError`\n// REQUIRES a settled partial `AgentResult` it cannot construct before a run starts;\n// `ConversationError` / `ProviderAbortError` / `WorkspaceError` are each scoped to an unrelated\n// domain) — so this package mints ONE typed error, `AgentToolError`, mirroring `WorkflowError`'s\n// exact shape (`code` + optional `context`) for the same reason: a thrown, machine-readable,\n// code-bearing error the tool-handler contract (AGENTS §14) requires, never a `{ error }`\n// return. `AgentToolError` is this package's general TOOL-CALL error — not scoped to agent\n// delegation alone — so `createDescribeTool` (a malformed call / an unknown tool name) reuses it\n// rather than minting a second class for the same `TOOL` misuse semantics.\n\n/**\n * Thrown by {@link import('./factories.js').createAgentTool}'s and\n * {@link import('./factories.js').createDescribeTool}'s handlers on every failure path — a\n * malformed / unresolvable call or an unknown tool name (`TOOL`), a delegation that would\n * exceed the configured depth bound or re-enter an ancestor (`DEPTH`), a prompt cycle\n * (`DEADLOCK`), a prompt that expired before it was answered (`EXPIRE`), or an answer that\n * failed to apply (`ANSWER`) — the last three thrown by\n * {@link import('./factories.js').createPromptTool} / {@link import('./factories.js').createAnswerTool}.\n * The upcoming database / relation tools (SRC-1's later units) will throw it too: a typed\n * `@orkestrel/database` failure re-surfaces as `DATABASE`, a typed `@orkestrel/relation` failure\n * as `RELATION` — each carrying the package's own granular error code in `context`.\n *\n * @remarks\n * Carries a machine-readable `code` (see {@link import('./types.js').AgentToolErrorCode}) and\n * an optional `context` bag for structured diagnostics. The `ToolManagerInterface`\n * (`@orkestrel/agent`) isolates every throw into the canonical tool result's top-level `error`\n * (AGENTS §14) — nothing escapes the run.\n *\n * @example\n * ```ts\n * import { AgentToolError, isAgentToolError } from '@src/core'\n *\n * try {\n * \tthrow new AgentToolError('TOOL', 'task is required')\n * } catch (error) {\n * \tif (isAgentToolError(error)) console.log(error.code) // 'TOOL'\n * }\n * ```\n */\nexport class AgentToolError extends Error {\n\treadonly code: AgentToolErrorCode\n\tdeclare readonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: AgentToolErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'AgentToolError'\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 AgentToolError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link AgentToolError}\n *\n * @example\n * ```ts\n * import { isAgentToolError } from '@src/core'\n *\n * try {\n * \t// ...\n * } catch (error) {\n * \tif (isAgentToolError(error)) console.log(error.code)\n * }\n * ```\n */\nexport function isAgentToolError(value: unknown): value is AgentToolError {\n\treturn value instanceof AgentToolError\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'\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// Tool-package 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` / `workspaceToolShape` are OWNED here now — ported\n// byte-faithfully from `@orkestrel/workflow` / `@orkestrel/agent` ahead of the upstream cleanup\n// that drops the authoring surface from those packages (this package becomes the defining home).\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 (OWNED here now, ported from `@orkestrel/workflow`)\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 has no handler.',\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\tdescription:\n\t\t\t\t'Per-attempt deadline in milliseconds; overrides the phase default. 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 required on the strict form; a 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 (OWNED here now, ported from `@orkestrel/agent`)\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` / `exact` are\n * `optionalShape(booleanShape(...))`. The two REGISTRY arms — `workspaces` (list the workspaces\n * the model can move between) and `switch` (re-point the active one by `id`) — let a model\n * 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\texact: 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\texact: 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 criteria form — conditions, order, and pagination. */\nexport const criteriaShape = 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 12 database operations (`'create'` / `'tables'` /\n * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /\n * `'remove'` / `'migrate'` / `'destroy'`).\n *\n * @remarks\n * Every arm carries `id` (the database id). `'create'` / `'migrate'` carry `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 `criteria` (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\tkeys: optionalShape(\n\t\t\trecordShape(stringShape(), { description: 'Table name to its primary-key column.' }),\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 criteria.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tcriteria: optionalShape(criteriaShape),\n\t}),\n\tobjectShape({\n\t\toperation: literalShape(['count'], { description: 'Count rows matching criteria.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttable: stringShape({ min: 1, description: 'The table name.' }),\n\t\tcriteria: optionalShape(criteriaShape),\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\tcriteria: optionalShape(criteriaShape),\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(['migrate'], { description: 'Replace the table layout in place.' }),\n\t\tid: stringShape({ min: 1, description: 'The database id.' }),\n\t\ttables: tableSpecShape,\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').AgentToolError}. 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, WorkflowStatus } from '@orkestrel/workflow'\nimport type { PromptType } from '@orkestrel/terminal'\nimport type { TablesShape } 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, Connector, Criteria, Direction, TableSchema } from '@orkestrel/database'\nimport type { ColumnSchema } from '@orkestrel/database'\nimport type { ContractShape } from '@orkestrel/contract'\nimport type {\n\tAgentToolErrorCode,\n\tColumnKind,\n\tColumnSpec,\n\tDatabaseDefinition,\n\tTableSpec,\n} from './types.js'\nimport type { PhaseDraft, TaskDraft, WorkflowDraft, WorkflowSteps } from './types.js'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { isDatabaseError, shapeToColumnType } from '@orkestrel/database'\nimport { isRelationError } from '@orkestrel/relation'\nimport { AgentToolError } from './errors.js'\nimport {\n\tbooleanShape,\n\tintegerShape,\n\tisNonEmptyString,\n\tisRecord,\n\tisString,\n\tnumberShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\n\n// Tool-package helpers — OWNED here now, ported byte-faithfully from `@orkestrel/workflow` ahead\n// of the upstream cleanup that drops the authoring surface from that package (this package\n// becomes the defining home for the workflow tool's lenient-authoring pipeline and its ancestry\n// tagging).\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 (a typed `DEPTH` `WorkflowError`, `@orkestrel/workflow`). 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 * 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` and the COUNT of settled task results —\n * enough for a caller / model to react without serializing the whole live tree. (It carries no\n * synthetic `id` / `name`: a tool handler has no call id; the `ToolManagerInterface`\n * (`@orkestrel/agent`) 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 }`\n */\nexport function workflowToolSummary(\n\tresult: WorkflowResult,\n): Readonly<{ status: WorkflowStatus; count: number }> {\n\treturn { status: result.status, count: result.results.length }\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 the workflow's `name`.\n * The result is a complete definition the caller validates against the STRICT contract before\n * 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 ? {} : { 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 AgentToolErrorCode} 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 AgentToolErrorCode}, or `undefined` if `error` is not a `TerminalError`\n */\nexport function terminalToolCode(error: unknown): AgentToolErrorCode | 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// `TablesShape`, 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 TablesShape} 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 `TablesShape` a `@orkestrel/database` `createDatabase` call accepts\n */\nexport function expandTables(spec: TableSpec): TablesShape {\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 }`, and an optional\n * `keys` record of strings. The boundary guard a {@link import('./types.js').DefinitionStoreInterface}\n * applies to an untrusted persisted blob 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 (!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.keys !== undefined) {\n\t\tif (!isRecord(value.keys)) return false\n\t\tfor (const key of Object.values(value.keys)) {\n\t\t\tif (!isString(key)) return false\n\t\t}\n\t}\n\treturn true\n}\n\n/**\n * Map a caught error to the {@link AgentToolErrorCode} 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 AgentToolErrorCode} 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 AgentToolError}.\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 AgentToolError('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 AgentToolError('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 AgentToolError('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 AgentToolError('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 AgentToolError} 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 AgentToolError('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 AgentToolError('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 AgentToolError('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 criteria into a live `@orkestrel/database`\n * {@link Criteria} — 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 criteria - The parsed criteria (or `undefined`)\n * @returns The equivalent live `Criteria`, or `undefined` when `criteria` is `undefined`\n */\nexport function criteriaOf(\n\tcriteria:\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?: Connector\n\t\t\t\t}>[]\n\t\t\t\torder?: readonly Readonly<{ column: string; direction: Direction }>[]\n\t\t\t\tlimit?: number\n\t\t\t\toffset?: number\n\t\t }>\n\t\t| undefined,\n): Criteria | undefined {\n\tif (criteria === undefined) return undefined\n\tconst conditions = criteria.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...(criteria.order === undefined ? {} : { order: criteria.order }),\n\t\t...(criteria.limit === undefined ? {} : { limit: criteria.limit }),\n\t\t...(criteria.offset === undefined ? {} : { offset: criteria.offset }),\n\t}\n}\n\n/**\n * Clamp a `'records'` call's criteria to a row cap, and build the PROBE criteria 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(criteria?.limit ?? cap, cap)`, floored at `0` (so a caller can never\n * exceed the configured cap by supplying a larger `criteria.limit`). The returned probe criteria\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 { clampCriteria } from '@src/core'\n *\n * const { criteria, limit } = clampCriteria(undefined, 100)\n * // limit === 100, criteria.limit === 101 — a probe fetching one extra row\n * const rows = await table.records(criteria)\n * const truncated = rows.length > limit // true when storage had more than `limit` rows\n * ```\n *\n * @param criteria - The live criteria to clamp (or `undefined`)\n * @param cap - The row-count ceiling\n * @returns The PROBE criteria (`limit` bumped by one) and the effective `limit`\n */\nexport function clampCriteria(\n\tcriteria: Criteria | undefined,\n\tcap: number,\n): Readonly<{ criteria: Criteria; limit: number }> {\n\tconst limit = Math.max(0, Math.min(criteria?.limit ?? cap, cap))\n\treturn { criteria: { ...criteria, limit: limit + 1 }, limit }\n}\n\n/** Map a column NAME + its live `@orkestrel/database` `ContractShape` to a {@link ColumnSchema} — the leaf {@link tableSchema} maps over. */\nexport function columnSchema(name: string, shape: ContractShape): ColumnSchema {\n\treturn {\n\t\tname,\n\t\ttype: shapeToColumnType(shape),\n\t\tnullable: shape.type === 'optional' || shape.type === 'nullable',\n\t}\n}\n\n/**\n * Build one {@link TableSchema} from a table NAME and its `@orkestrel/database` `TableExport` —\n * the \"deployed\" schema shape `DatabaseInterface.migrate` diffs against, derived from a LIVE\n * handle's `export()` rather than a re-declared {@link TableSpec}, so it works for ANY handle\n * (config-tracked or caller-supplied).\n *\n * @param name - The table name\n * @param table - The table's `TableExport` (`{ key, columns }`, `@orkestrel/database`)\n * @returns The equivalent {@link TableSchema} (`indexes` empty — this package declares none)\n */\nexport function tableSchema(\n\tname: string,\n\ttable: Readonly<{ key: string; columns: Readonly<Record<string, ContractShape>> }>,\n): TableSchema {\n\treturn {\n\t\tname,\n\t\tprimary: table.key,\n\t\tcolumns: Object.entries(table.columns).map(([column, shape]) => columnSchema(column, shape)),\n\t\tindexes: [],\n\t}\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). 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\treturn Promise.resolve(this.#definitions.get(id))\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, 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 { AgentToolError } 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/tool'\n *\n * const resolver = new DatabaseResolver(handles, drivers, key, 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 #key: KeyFunction\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 key - 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\tkey: KeyFunction,\n\t\tstore?: DefinitionStoreInterface,\n\t) {\n\t\tthis.#handles = new Map(handles)\n\t\tthis.#drivers = drivers\n\t\tthis.#key = key\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 AgentToolError('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\t...(definition.keys === undefined ? {} : { keys: definition.keys }),\n\t\t\t\t\tkey: this.#key,\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 AgentToolError('TOOL', `unknown database '${id}'`, { id })\n\t}\n}\n","import type { ContractInterface } from '@orkestrel/contract'\nimport type {\n\tAgentInterface,\n\tAgentRegistryInterface,\n\tToolInterface,\n\tToolManagerInterface,\n\tWorkspaceManagerInterface,\n} from '@orkestrel/agent'\nimport type {\n\tWorkflowDefinition,\n\tWorkflowFunction,\n\tWorkflowRunnerInterface,\n} from '@orkestrel/workflow'\nimport type {\n\tAgentFunctionOptions,\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 {\n\tcreateTool,\n\tcreateWorkspaceManager,\n\tisText,\n\trangeOf,\n\tWorkspaceError,\n} from '@orkestrel/agent'\nimport {\n\tcreateContract,\n\tisRecord,\n\trawShape,\n\tsamplesToSchema,\n\tschemaToObject,\n\tschemaToParameters,\n\tschemaToShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { isTerminalError } from '@orkestrel/terminal'\nimport { createDatabase, createMemoryDriver, generateUUID } from '@orkestrel/database'\nimport { createWorkflowContract, WorkflowError } 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 { AgentToolError, isAgentToolError } from './errors.js'\nimport {\n\tagentTag,\n\tclampCriteria,\n\tcoerceAnswer,\n\tcompleteDraft,\n\tcriteriaOf,\n\tdatabaseToolCode,\n\texpandInclude,\n\texpandSteps,\n\texpandTables,\n\trelationManagerOf,\n\trelationModelOf,\n\trelationToolCode,\n\ttableSchema,\n\tterminalToolCode,\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` / `createWorkspaceTool` OWN their full\n// handler logic now (ported byte-faithfully from `@orkestrel/workflow` / `@orkestrel/agent` ahead\n// of the upstream cleanup that drops the authoring surface from those packages) and additionally\n// layer a pluggable store slot on top; `createAgentTool` is net-new: sub-agent delegation over an\n// `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/agent` tool BY NAME.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's\n * `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, id-correlated to the task's own id. A\n * `ToolManagerInterface.execute` (`@orkestrel/agent`) NEVER throws (a handler throw is isolated\n * into `result.error`), so a failing tool is surfaced here as a THROWN `Error` carrying the\n * original message as `cause` — the leaf `fail`s, honouring `bail`. An UNREGISTERED tool name is\n * a programmer error (an explicit binding to a name that doesn't exist) — unlike the engine's\n * own silent auto-complete of an unresolved task handler, this THROWS a typed `TOOL`\n * `WorkflowError` (`@orkestrel/workflow`).\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) 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/agent'\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\treturn async (controller) => {\n\t\tconst tool = tools.tool(name)\n\t\tif (tool === undefined) {\n\t\t\tthrow new WorkflowError('TOOL', `tool '${name}' is not registered`, { tool: name })\n\t\t}\n\t\tconst result = await tools.execute({\n\t\t\tid: controller.task.id,\n\t\t\tname,\n\t\t\targuments: controller.input,\n\t\t})\n\t\t// A `tool` result NEVER throws — the manager isolates a handler throw into `result.error`.\n\t\t// Surface that as a task failure (so a failing tool `fail`s the leaf, honouring `bail`).\n\t\t// The manager already flattened the original throw to a string, so the message IS the\n\t\t// richest surviving detail — `cause` carries that same string, nothing deeper exists.\n\t\tif (result.error !== undefined) throw new Error(result.error, { cause: result.error })\n\t\treturn result.value\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, folding\n * a nested workflow-authoring depth / cycle guard into its own closure.\n *\n * @remarks\n * OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's\n * `WorkflowOptions.functions` registry like any other behavior; the pure workflow runner has no\n * knowledge of agents itself. Before running the agent, the depth/cycle guard REJECTS the call\n * (a THROWN typed `DEPTH` `WorkflowError`, which the leaf `fail`s) when running it would push a\n * nested chain past {@link import('./constants.js').MAX_WORKFLOW_DEPTH}, OR when this agent is\n * already an ancestor (a cycle). When {@link import('./types.js').AgentFunctionOptions.runner}\n * is supplied, the adapter BINDS a depth/cycle-aware {@link createWorkflowTool} onto the agent's\n * `context.tools` (the propagation seam) — closed over `depth` and the extended ancestry (the\n * tool itself computes `depth + 1` internally) — so the agent can author + run a NESTED workflow\n * through it; the wrapped default is the CURRENT task's own workflow id (used only on a no-args\n * tool call). The task's cancellation folds into the agent run: an already-aborted\n * `controller.signal` cancels the agent up front; otherwise a one-shot listener fires\n * `agent.abort(reason)` when the task cancels, removed in `finally`. `agent.generate()` resolves\n * a partial `AgentResult` on a cancel (never rejects), returned as the task's completed value.\n *\n * A bound agent is effectively SINGLE-RUN: `context.tools.add` binds one `ToolInterface` under\n * the fixed {@link import('./constants.js').WORKFLOW_TOOL_NAME}, and `agent.generate()` /\n * `agent.abort()` are per-agent state. Two CONCURRENT tasks sharing the SAME `agent` instance\n * race on that one tool binding (last-write-wins) and on generate/abort — give each concurrent\n * task its OWN agent instance.\n *\n * @param agent - The live `AgentInterface` to run\n * @param options - The nested-workflow binding + depth/cycle bookkeeping (see {@link import('./types.js').AgentFunctionOptions})\n * @returns A {@link WorkflowFunction} 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): WorkflowFunction {\n\treturn async (controller) => {\n\t\tconst depth = options?.depth ?? 0\n\t\tconst ancestry = options?.ancestry ?? []\n\t\t// GUARD (before running the agent): running it would let it author + run a NESTED workflow\n\t\t// at `depth + 1`, so reject when that would exceed the bound, OR when this agent is already\n\t\t// an ancestor (a re-entry cycle). The throw becomes the leaf's typed `DEPTH` failure.\n\t\tif (depth + 1 > MAX_WORKFLOW_DEPTH) {\n\t\t\tthrow new WorkflowError('DEPTH', `agent '${agent.id}' exceeds max workflow depth`, {\n\t\t\t\tagent: agent.id,\n\t\t\t\tdepth,\n\t\t\t\tmax: MAX_WORKFLOW_DEPTH,\n\t\t\t})\n\t\t}\n\t\tconst tag = agentTag(agent.id)\n\t\tif (ancestry.includes(tag)) {\n\t\t\tthrow new WorkflowError('DEPTH', `agent '${agent.id}' is already an ancestor (cycle)`, {\n\t\t\t\tagent: agent.id,\n\t\t\t\tancestry: [...ancestry],\n\t\t\t})\n\t\t}\n\t\t// BIND the workflow tool so the agent can fan out into a nested workflow at `depth + 1` with\n\t\t// THIS agent added to the ancestry — the propagation across the agent/tool boundary (closed\n\t\t// over the tool at bind time, since a tool handler receives no ambient context). The current\n\t\t// task's own workflow id is the tool's WRAPPED default, used only on a no-args call.\n\t\tconst runner = options?.runner\n\t\tif (runner !== undefined) {\n\t\t\tconst workflowId = controller.task.phase.workflow.id\n\t\t\tconst wrapped: WorkflowDefinition = { id: workflowId, name: workflowId, phases: [] }\n\t\t\tagent.context.tools.add(\n\t\t\t\tcreateWorkflowTool(wrapped, runner, { depth, ancestry: [...ancestry, tag] }),\n\t\t\t)\n\t\t}\n\t\t// Fold the task's cancellation into the agent run: an already-aborted signal cancels the\n\t\t// agent up front; otherwise a one-shot listener fires `agent.abort(reason)` when the task\n\t\t// cancels. `generate()` RESOLVES a partial on a cancel (never rejects).\n\t\tconst signal = controller.signal\n\t\tconst onAbort = {\n\t\t\thandleEvent(): void {\n\t\t\t\tagent.abort(signal.reason)\n\t\t\t},\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\tagent.abort(signal.reason)\n\t\t} else {\n\t\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\t}\n\t\ttry {\n\t\t\treturn await agent.generate()\n\t\t} finally {\n\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t}\n\t}\n}\n\n/**\n * Compile the LENIENT workflow DRAFT contract — identical to `createWorkflowContract`\n * (`@orkestrel/workflow`) EXCEPT `id` and `name` are OPTIONAL at all three levels (workflow /\n * phase / task), so a small model can omit the six identity strings.\n *\n * @remarks\n * The widened authoring surface {@link createWorkflowTool} parses an authored blob through\n * before {@link import('./helpers.js').completeDraft} fills the missing ids/names. It does NOT\n * relax the canonical contract — `createWorkflowContract` (`@orkestrel/workflow`) stays\n * byte-for-byte unchanged and STRICT, and the completed draft is re-validated against THAT\n * strict gate before running (soundness preserved). A PROVIDED `id` / `name` still carries\n * `minLength: 1`, so an explicitly-empty `id: ''` is REJECTED (parses to `undefined`), never\n * auto-filled — keeping \"garbage\" distinct from \"omitted\". `run` stays optional (a plain name\n * string).\n *\n * @returns The compiled {@link import('./types.js').WorkflowDraft} contract\n *\n * @example\n * ```ts\n * import { createWorkflowDraftContract, completeDraft } from '@src/core'\n *\n * const draft = createWorkflowDraftContract()\n * const parsed = draft.parse({ phases: [{ tasks: [{ run: 'compile' }] }] })\n * const definition = parsed && completeDraft(parsed) // ids/names filled positionally\n * draft.parse({ id: '', phases: [] }) // undefined — an explicit empty id is rejected\n * ```\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, runs it through `runner`, and, when\n * {@link import('./types.js').WorkflowToolOptions.store} is supplied, PERSISTS each executed\n * workflow's final snapshot after the run settles.\n *\n * @remarks\n * A plain `ToolManagerInterface`-compatible tool (`@orkestrel/agent`), reproducing\n * `@orkestrel/workflow`'s former call contract exactly (flat / draft / full authoring forms, the\n * strict soundness gate, the depth/cycle guard). 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` (no ambient context, no signal), the run's\n * depth + ancestry are CLOSED OVER at bind time via {@link import('./types.js').WorkflowToolOptions},\n * and the handler enforces the SAME depth / cycle guard itself before running the nested\n * workflow at `depth + 1` with the extended ancestry.\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 }`) on success, THROWS a typed `WorkflowError` (`@orkestrel/workflow`) on\n * every failure path — malformed authored args (`TOOL`), or an over-deep / cyclic nested run\n * (`DEPTH`). The `ToolManagerInterface` isolates every throw into the canonical tool result's\n * top-level `error`, so nothing escapes the run. `options.depth` / `options.ancestry` are the\n * propagation carrier across a workflow → agent → workflow chain; `options.store` is this\n * package's ADDITION — the persisted snapshot is retrievable via the store afterwards (a caller\n * restores it through `@orkestrel/workflow`'s own `Workflow.restore` / store-backed factories).\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 - Depth/ancestry bookkeeping plus the optional durable store (see {@link import('./types.js').WorkflowToolOptions})\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/agent'\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 are now persisted to `store` on settle\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 depth = options?.depth ?? 0\n\tconst ancestry = options?.ancestry ?? []\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\t// Branch on the authored args' 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(args).length === 0) {\n\t\t\t\ttarget = definition\n\t\t\t} else if (Array.isArray(args.steps)) {\n\t\t\t\tconst flat = steps.parse(args)\n\t\t\t\ttarget = flat === undefined ? undefined : expandSteps(flat)\n\t\t\t} else {\n\t\t\t\tconst parsed = draft.parse(args)\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 WorkflowError('TOOL', 'malformed workflow definition', {\n\t\t\t\t\tworkflow: definition.id,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (depth + 1 > MAX_WORKFLOW_DEPTH) {\n\t\t\t\tthrow new WorkflowError(\n\t\t\t\t\t'DEPTH',\n\t\t\t\t\t`nested workflow exceeds max depth ${MAX_WORKFLOW_DEPTH}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\t\tdepth,\n\t\t\t\t\t\tmax: MAX_WORKFLOW_DEPTH,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst tag = workflowTag(target.id)\n\t\t\tif (ancestry.includes(tag)) {\n\t\t\t\tthrow new WorkflowError('DEPTH', `workflow '${target.id}' is already an ancestor (cycle)`, {\n\t\t\t\t\tworkflow: target.id,\n\t\t\t\t\tancestry: [...ancestry],\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await runner.execute(target)\n\t\t\tif (store !== undefined) await store.set(result.workflow.snapshot())\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 (throwing a typed `WorkspaceError`, `@orkestrel/agent`, on\n * failure). EITHER drives a caller-supplied {@link WorkspaceToolOptions.manager} directly, OR\n * constructs a fresh `WorkspaceManagerInterface` (`@orkestrel/agent`) over\n * {@link import('./types.js').WorkspaceToolOptions.store} (via `@orkestrel/agent`'s\n * `createWorkspaceManager`); neither given constructs a manager backed by `@orkestrel/agent`'s\n * 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` `WorkspaceError` 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/agent`) by `rangeOf` and fed to the workspace's ranged\n * `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/agent'\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 WorkspaceError('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.exact === undefined ? {} : { exact: op.exact }),\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.exact === undefined ? {} : { exact: op.exact }),\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').AgentToolError}; 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').AgentToolError} — 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, createToolManager } from '@orkestrel/agent'\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 AgentToolError('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 AgentToolError('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 AgentToolError(\n\t\t\t\t\t'DEPTH',\n\t\t\t\t\t`delegation exceeds max agent depth ${AGENT_TOOL_DEPTH}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\tdepth,\n\t\t\t\t\t\tmax: AGENT_TOOL_DEPTH,\n\t\t\t\t\t},\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 AgentToolError('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/agent`) 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').AgentToolError} on a malformed call\n * or an unknown tool name.\n *\n * @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) 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/agent'\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 AgentToolError('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 AgentToolError('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').AgentToolError}; 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 { createTerminalManager, createToolManager } 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 AgentToolError('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 AgentToolError('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 AgentToolError(\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 AgentToolError(\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 AgentToolError('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 AgentToolError('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').AgentToolError}),\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` `AgentToolError`; 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` `AgentToolError` (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 { createTerminalManager, createToolManager } 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 AgentToolError('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 AgentToolError('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 AgentToolError(\n\t\t\t\t\t'ANSWER',\n\t\t\t\t\t`failed to answer prompt '${call.id}': ${result.error}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\treason: result.error,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { answered: call.id }\n\t\t},\n\t})\n}\n\n// === Database definition stores (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').AgentToolError}). When a `store` is configured, `'create'`\n * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.\n *\n * `'migrate'` re-declares a LIVE handle's tables via `DatabaseInterface.import` (the SAME driver\n * and storage, a NEW typed view) and calls its `migrate` against the OLD deployed schema —\n * derived from the handle's OWN `export()` (via {@link import('./helpers.js').tableSchema}), so it\n * works for any handle, config-tracked or caller-supplied via\n * {@link import('./types.js').DatabaseToolOptions.databases}. `'records'` clamps its `criteria` to\n * {@link import('./types.js').DatabaseToolOptions.limit} (default\n * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) via\n * {@link import('./helpers.js').clampCriteria}, reporting `truncated` when storage held more rows\n * than the cap. Every operation's `criteria` is normalized via\n * {@link import('./helpers.js').criteriaOf} (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` `AgentToolError` before doing anything. When\n * {@link import('./types.js').DatabaseToolOptions.timeout} is set, every `@orkestrel/database` call\n * this tool makes is given a fresh `AbortSignal.timeout(timeout)`. A typed `@orkestrel/database`\n * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `AgentToolError` carrying the\n * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`\n * ({@link import('./helpers.js').databaseToolCode}); an `AgentToolError` 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\tconst contract = createContract(databaseToolShape)\n\tconst parameters = schemaToParameters(contract.schema)\n\tconst handles = new Map<string, DatabaseInterface>(Object.entries(options.databases ?? {}))\n\tconst definitions = new Map<string, DatabaseDefinition>()\n\tconst drivers = options.drivers ?? { memory: createMemoryDriver }\n\tconst key = options.key ?? generateUUID\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, key)\n\t\t\t: new DatabaseResolver(handles, drivers, key, 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 AgentToolError('TOOL', 'malformed database call', { args })\n\t\t\t}\n\t\t\tif (options.readonly === true && DATABASE_TOOL_MUTATIONS.has(call.operation)) {\n\t\t\t\tthrow new AgentToolError(\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 AgentToolError('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 AgentToolError('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 keys = call.keys\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\t...(keys === undefined ? {} : { keys }),\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tresolver.set(call.id, handle)\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...(keys === undefined ? {} : { keys }),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefinitions.set(call.id, definition)\n\t\t\t\t\t\tif (store !== undefined) await store.set(definition)\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 { criteria: probe, limit } = clampCriteria(criteriaOf(call.criteria), 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(criteriaOf(call.criteria), 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\tcriteriaOf(call.criteria),\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 'migrate': {\n\t\t\t\t\t\tconst handle = await resolver.resolve(call.id)\n\t\t\t\t\t\tconst previous = handle.export()\n\t\t\t\t\t\tconst deployed = Object.entries(previous).map(([name, table]) =>\n\t\t\t\t\t\t\ttableSchema(name, table),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconst tables = call.tables\n\t\t\t\t\t\tconst keys: Record<string, string> = {}\n\t\t\t\t\t\tfor (const name of Object.keys(tables)) {\n\t\t\t\t\t\t\tconst existing = previous[name]\n\t\t\t\t\t\t\tif (existing !== undefined) keys[name] = existing.key\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst declared = expandTables(tables)\n\t\t\t\t\t\tconst migrated = handle.import(\n\t\t\t\t\t\t\tdeclared,\n\t\t\t\t\t\t\tObject.keys(keys).length > 0 ? keys : undefined,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconst migration = await migrated.migrate(deployed, read)\n\t\t\t\t\t\tresolver.set(call.id, migrated)\n\t\t\t\t\t\tconst tracked =\n\t\t\t\t\t\t\tdefinitions.get(call.id) ??\n\t\t\t\t\t\t\t(store === undefined ? undefined : await store.get(call.id))\n\t\t\t\t\t\tif (tracked !== undefined) {\n\t\t\t\t\t\t\tconst updated: DatabaseDefinition = {\n\t\t\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t\t\tdriver: tracked.driver,\n\t\t\t\t\t\t\t\ttables,\n\t\t\t\t\t\t\t\t...(Object.keys(keys).length > 0 ? { keys } : {}),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdefinitions.set(call.id, updated)\n\t\t\t\t\t\t\tif (store !== undefined) await store.set(updated)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { migration }\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\tdefinitions.delete(call.id)\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 (isAgentToolError(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 AgentToolError(\n\t\t\t\t\t'DATABASE',\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t{\n\t\t\t\t\t\tcode,\n\t\t\t\t\t\toperation: call.operation,\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\t...('table' in call ? { table: call.table } : {}),\n\t\t\t\t\t},\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').AgentToolError}\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').clampCriteria}'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 * `AgentToolError` 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` `AgentToolError`, mirroring {@link createDatabaseTool}'s error\n * mapping; an `AgentToolError` 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 AgentToolError('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 (isAgentToolError(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 AgentToolError(\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 AgentToolError(\n\t\t\t\t\t'DATABASE',\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t{ code: database, operation: 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').AgentToolError}.\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').AgentToolError} 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/agent'\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 AgentToolError('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 AgentToolError('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').AgentToolError} 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/agent`) 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/agent'\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 AgentToolError message\n * ```\n */\nexport function createEndpointTool(\n\tdefinition: EndpointDefinition,\n\toptions?: EndpointToolOptions,\n): ToolInterface {\n\tif (definition.samples.length === 0) {\n\t\tthrow new AgentToolError('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 AgentToolError('TOOL', 'malformed endpoint call arguments', {\n\t\t\t\t\tname: definition.name,\n\t\t\t\t\tfaults: contract.explain(args),\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn definition.invoke(parsed)\n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;CACA,MAAM,aAAa,mBAAmB,YAAY;CAElD,IAAI,EADa,SAAS,YAAY,OAErC,OAAO,WAAW;EACjB,MAAM,WAAW;EACjB,aAAa,WAAW;EACxB,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,QAAQ,MAAM;GACb,OAAO,WAAW,OAAO,IAAI;EAC9B;CACD,CAAC;CAEF,MAAM,WAAW,eAAe,cAAc,YAAY,CAAC;CAC3D,OAAO,WAAW;EACjB,MAAM,WAAW;EACjB,aAAa,WAAW;EACxB,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,QAAQ,MAAM;GACb,MAAM,SAAS,SAAS,MAAM,IAAI;GAClC,IAAI,WAAW,KAAA,KAAa,CAAC,SAAS,MAAM,GAC3C,MAAM,IAAI,eAAe,QAAQ,qCAAqC;IACrE,MAAM,WAAW;IACjB,QAAQ,SAAS,QAAQ,IAAI;GAC9B,CAAC;GAEF,OAAO,WAAW,OAAO,MAAM;EAChC;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"index.js","names":["#execute","#tools","#definition","#run"],"sources":["../../../src/core/helpers.ts","../../../src/core/tools/Tool.ts","../../../src/core/tools/ToolManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { ToolCall } from './types.js'\nimport { holds, isRecord, isString } from '@orkestrel/contract'\n\n/**\n * Determine whether an unknown value is structurally a {@link ToolCall}.\n *\n * @remarks\n * This total guard accepts a plain record with string `id` and `name` fields and a\n * plain-record `arguments` field. Adversarial values return `false`.\n *\n * @param value - The value to test\n * @returns `true` when the value has the complete tool-call shape\n *\n * @example\n * ```ts\n * import { isToolCall } from '@orkestrel/tool'\n *\n * isToolCall({ id: '1', name: 'search', arguments: { query: 'birds' } }) // true\n * isToolCall({ id: '1', name: 'search', arguments: [] }) // false\n * ```\n */\nexport function isToolCall(value: unknown): value is ToolCall {\n\treturn holds(\n\t\t() =>\n\t\t\tisRecord(value) && isString(value.id) && isString(value.name) && isRecord(value.arguments),\n\t)\n}\n","import type { ToolInterface, ToolOptions } from '../types.js'\n\n/**\n * An executable tool definition bound to a handler.\n *\n * @remarks\n * Schema fields and arguments are forwarded by reference. Handler failures are not\n * caught here; {@link ToolManager} owns per-call error isolation.\n *\n * @example\n * ```ts\n * import { Tool } from '@orkestrel/tool'\n *\n * const tool = new Tool({\n * \tname: 'add',\n * \tdescription: 'Add two numbers',\n * \tparameters: {\n * \t\ttype: 'object',\n * \t\tproperties: { a: { type: 'number' }, b: { type: 'number' } },\n * \t},\n * \texecute: (args) => Number(args.a) + Number(args.b),\n * })\n * ```\n */\nexport class Tool implements ToolInterface {\n\treadonly name: string\n\treadonly description?: string\n\treadonly summary?: string\n\treadonly parameters?: Readonly<Record<string, unknown>>\n\treadonly #execute: (args: Readonly<Record<string, unknown>>) => Promise<unknown> | unknown\n\n\tconstructor(options: ToolOptions) {\n\t\tthis.name = options.name\n\t\tif (options.description !== undefined) this.description = options.description\n\t\tif (options.summary !== undefined) this.summary = options.summary\n\t\tif (options.parameters !== undefined) this.parameters = options.parameters\n\t\tthis.#execute = options.execute\n\t}\n\n\texecute(args: Readonly<Record<string, unknown>>): Promise<unknown> | unknown {\n\t\treturn this.#execute(args)\n\t}\n}\n","import type {\n\tToolCall,\n\tToolDefinition,\n\tToolInterface,\n\tToolManagerInterface,\n\tToolResult,\n} from '../types.js'\nimport { attempt, isArray } from '@orkestrel/contract'\n\n/**\n * An insertion-ordered tool registry with per-call error isolation.\n *\n * @remarks\n * A repeated name overwrites the registered tool without changing its insertion\n * position. Definitions advertise `summary` in place of `description` when present.\n * Unknown names and handler throws resolve to error results; batch execution preserves\n * input order and never fails as a whole because of an individual call.\n *\n * @example\n * ```ts\n * import { Tool, ToolManager } from '@orkestrel/tool'\n *\n * const tools = new ToolManager()\n * tools.add(new Tool({ name: 'add', execute: (args) => Number(args.x) + Number(args.y) }))\n * const result = await tools.execute({\n * \tid: '1',\n * \tname: 'add',\n * \targuments: { x: 1, y: 2 },\n * })\n * ```\n */\nexport class ToolManager implements ToolManagerInterface {\n\treadonly #tools = new Map<string, ToolInterface>()\n\n\tget count(): number {\n\t\treturn this.#tools.size\n\t}\n\n\tadd(tool: ToolInterface): void\n\tadd(tools: readonly ToolInterface[]): void\n\tadd(tools: ToolInterface | readonly ToolInterface[]): void {\n\t\tif (isArray(tools)) {\n\t\t\tfor (const tool of tools) this.#tools.set(tool.name, tool)\n\t\t\treturn\n\t\t}\n\t\tthis.#tools.set(tools.name, tools)\n\t}\n\n\ttool(name: string): ToolInterface | undefined {\n\t\treturn this.#tools.get(name)\n\t}\n\n\ttools(): readonly ToolInterface[] {\n\t\treturn [...this.#tools.values()]\n\t}\n\n\tdefinitions(): readonly ToolDefinition[] {\n\t\treturn [...this.#tools.values()].map((tool) => this.#definition(tool))\n\t}\n\n\texecute(call: ToolCall): Promise<ToolResult>\n\texecute(calls: readonly ToolCall[]): Promise<readonly ToolResult[]>\n\texecute(call: ToolCall | readonly ToolCall[]): Promise<ToolResult | readonly ToolResult[]> {\n\t\tif (isArray(call)) return Promise.all(call.map((one) => this.#run(one)))\n\t\treturn this.#run(call)\n\t}\n\n\tremove(name: string): boolean\n\tremove(names: readonly string[]): boolean\n\tremove(names: string | readonly string[]): boolean {\n\t\tif (isArray(names)) {\n\t\t\tlet removed = false\n\t\t\tfor (const name of names) {\n\t\t\t\tif (this.#tools.delete(name)) removed = true\n\t\t\t}\n\t\t\treturn removed\n\t\t}\n\t\treturn this.#tools.delete(names)\n\t}\n\n\tclear(): void {\n\t\tthis.#tools.clear()\n\t}\n\n\tasync #run(call: ToolCall): Promise<ToolResult> {\n\t\tconst tool = this.#tools.get(call.name)\n\t\tif (tool === undefined) {\n\t\t\treturn {\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.name,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `tool not found: ${call.name}`,\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst value = await tool.execute(call.arguments)\n\t\t\treturn { id: call.id, name: call.name, success: true, value }\n\t\t} catch (error) {\n\t\t\tconst message = attempt(() =>\n\t\t\t\terror instanceof Error ? String(error.message) : String(error),\n\t\t\t)\n\t\t\treturn {\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.name,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: message.success ? message.value : 'Unknown thrown value',\n\t\t\t}\n\t\t}\n\t}\n\n\t#definition(tool: ToolInterface): ToolDefinition {\n\t\tconst definition: {\n\t\t\tname: string\n\t\t\tdescription?: string\n\t\t\tparameters?: Readonly<Record<string, unknown>>\n\t\t} = {\n\t\t\tname: tool.name,\n\t\t}\n\t\tconst description = tool.summary ?? tool.description\n\t\tif (description !== undefined) definition.description = description\n\t\tif (tool.parameters !== undefined) definition.parameters = tool.parameters\n\t\treturn definition\n\t}\n}\n","import type { ToolInterface, ToolManagerInterface, ToolOptions } from './types.js'\nimport { Tool } from './tools/Tool.js'\nimport { ToolManager } from './tools/ToolManager.js'\n\n/**\n * Create an executable tool.\n *\n * @param options - The advertised definition and execution handler\n * @returns A tool bound to the supplied handler\n *\n * @example\n * ```ts\n * import { createTool } from '@orkestrel/tool'\n *\n * const add = createTool({\n * \tname: 'add',\n * \tdescription: 'Add two numbers',\n * \texecute: (args) => Number(args.a) + Number(args.b),\n * })\n * ```\n */\nexport function createTool(options: ToolOptions): ToolInterface {\n\treturn new Tool(options)\n}\n\n/**\n * Create an empty tool registry.\n *\n * @returns A registry that advertises definitions and executes calls with per-call\n * error isolation\n *\n * @example\n * ```ts\n * import { createTool, createToolManager } from '@orkestrel/tool'\n *\n * const tools = createToolManager()\n * tools.add(createTool({ name: 'echo', execute: (args) => args.value }))\n * const result = await tools.execute({\n * \tid: '1',\n * \tname: 'echo',\n * \targuments: { value: 'hello' },\n * })\n * ```\n */\nexport function createToolManager(): ToolManagerInterface {\n\treturn new ToolManager()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAW,OAAmC;CAC7D,OAAO,YAEL,SA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