@orkestrel/tool 0.0.5 → 0.0.7

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,3266 +1,203 @@
1
- import { arrayShape, booleanShape, createContract, integerShape, isNonEmptyString, isRecord, isString, jsonShape, literalShape, numberShape, objectShape, optionalShape, rawShape, recordShape, samplesToSchema, schemaToObject, schemaToParameters, schemaToShape, stringShape, unionShape } from "@orkestrel/contract";
2
- import { isTerminalError } from "@orkestrel/terminal";
3
- import { createDatabase, createMemoryDriver, generateUUID, isDatabaseError, shapeToColumnType } from "@orkestrel/database";
4
- import { isRelationError } from "@orkestrel/relation";
5
- import { WorkspaceError, createTool, createWorkspaceManager, isText, rangeOf } from "@orkestrel/agent";
6
- import { WorkflowError, createWorkflowContract } from "@orkestrel/workflow";
7
- //#region src/core/constants.ts
8
- /**
9
- * The name {@link import('./factories.js').createAgentTool} advertises by default — the key a
10
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
11
- */
12
- var AGENT_TOOL_NAME = "agent";
13
- /**
14
- * The maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may
15
- * reach — the bound {@link import('./factories.js').createAgentTool}'s depth/cycle guard
16
- * enforces.
17
- *
18
- * @remarks
19
- * Deliberately a SEPARATE constant from {@link MAX_WORKFLOW_DEPTH} (rather than the two guards
20
- * sharing one reference): the two guards bound DIFFERENT chains (workflow nesting vs. agent
21
- * delegation) that happen to share a value today, and keeping this bound decoupled means a
22
- * future change to one never silently shifts the other. Same numeric value by convention, not
23
- * by shared reference.
24
- */
25
- var AGENT_TOOL_DEPTH = 8;
26
- /**
27
- * The DESCRIPTION {@link import('./factories.js').createAgentTool} advertises — a short guide
28
- * that teaches a model how to delegate a task to a sub-agent.
29
- *
30
- * @remarks
31
- * Mirrors {@link WORKFLOW_TOOL_DESCRIPTION} / `WORKSPACE_TOOL_DESCRIPTION`'s teaching style: names
32
- * the required `task` field, and documents the optional per-call `provider` / `tools` /
33
- * `system` overrides.
34
- */
35
- /**
36
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createAgentTool}
37
- * advertises in place of {@link AGENT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
38
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
39
- * for the full teaching description; the full text stays retrievable via
40
- * {@link import('./factories.js').createDescribeTool}.
41
- */
42
- var AGENT_TOOL_SUMMARY = "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.";
43
- var AGENT_TOOL_DESCRIPTION = [
44
- "Delegate a task to a sub-agent and return its result. Every call runs ONE sub-agent turn to completion.",
45
- "",
46
- "Required:",
47
- " task - the instructions the sub-agent should carry out.",
48
- "Optional overrides (default to the values this tool was configured with):",
49
- " provider - the registry key of the model/provider the sub-agent runs against.",
50
- " tools - registry keys of the tools loaded into the sub-agent (replaces the default list, not merged).",
51
- " system - a system prompt seeding the sub-agent's context (replaces the default).",
52
- "Example:",
53
- JSON.stringify({ task: "Summarize the attached notes in three bullet points." })
54
- ].join("\n");
55
- /**
56
- * The maximum nesting depth a workflow → agent → workflow chain may reach — the bound
57
- * {@link import('./factories.js').createAgentFunction} and
58
- * {@link import('./factories.js').createWorkflowTool}'s depth/cycle guards enforce.
59
- *
60
- * @remarks
61
- * OWNED here now (ported from `@orkestrel/workflow`, whose engine no longer uses it — only the
62
- * tool-authoring guards this package now owns consume it). The limit lives in ONE place: an
63
- * agent-function-wrapped agent running at this depth can no longer author + run a NESTED
64
- * workflow through its bound workflow tool (that would be depth `MAX_WORKFLOW_DEPTH + 1`), so
65
- * the over-deep invocation is REJECTED (a typed `DEPTH` `WorkflowError` throw, `@orkestrel/workflow`).
66
- */
67
- var MAX_WORKFLOW_DEPTH = 8;
68
- /**
69
- * The name {@link import('./factories.js').createWorkflowTool} advertises by default — the key a
70
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under, and the name
71
- * {@link import('./factories.js').createAgentFunction} binds the depth/cycle-aware workflow tool
72
- * under onto a wrapped agent's `context.tools`.
73
- *
74
- * @remarks
75
- * OWNED here now (ported from `@orkestrel/workflow`). The propagation seam's well-known key: when
76
- * `createAgentFunction`'s `runner` option is supplied, it adds a `createWorkflowTool`-built tool
77
- * under this name to the agent's `context.tools`, so it can author + run a NESTED workflow
78
- * (bounded by {@link MAX_WORKFLOW_DEPTH}).
79
- */
80
- var WORKFLOW_TOOL_NAME = "workflow";
81
- /**
82
- * A complete FLAT authoring example — the PRIMARY way a small model authors a workflow through
83
- * {@link import('./factories.js').createWorkflowTool}: `{ name, steps: [{ name }] }`.
84
- *
85
- * @remarks
86
- * OWNED here now (ported from `@orkestrel/workflow`). Each step becomes a one-task phase, in
87
- * order; a step's `name` is a REGISTERED behavior name (not a label) — the registry key its
88
- * task's `run` resolves against. The tool expands this
89
- * ({@link import('./helpers.js').expandSteps}) into a valid `WorkflowDefinition`
90
- * (`@orkestrel/workflow`). It is embedded VERBATIM in {@link WORKFLOW_TOOL_DESCRIPTION}.
91
- */
92
- var WORKFLOW_TOOL_FLAT_EXAMPLE = Object.freeze({
93
- name: "release",
94
- steps: Object.freeze([Object.freeze({ name: "compile" }), Object.freeze({ name: "publish" })])
95
- });
96
- /**
97
- * A minimal NESTED authoring example — the ADVANCED escape-hatch form a model may use instead of
98
- * the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).
99
- *
100
- * @remarks
101
- * OWNED here now (ported from `@orkestrel/workflow`). The full four-level form, documented in
102
- * {@link WORKFLOW_TOOL_DESCRIPTION} as the advanced alternative. It is embedded VERBATIM.
103
- */
104
- var WORKFLOW_TOOL_NESTED_EXAMPLE = Object.freeze({
105
- id: "release",
106
- name: "Release",
107
- phases: Object.freeze([Object.freeze({
108
- id: "build",
109
- name: "Build",
110
- tasks: Object.freeze([Object.freeze({
111
- id: "compile",
112
- name: "Compile",
113
- run: "compile"
114
- })])
115
- })])
116
- });
117
- /**
118
- * The DESCRIPTION {@link import('./factories.js').createWorkflowTool} advertises — a multi-line
119
- * guide that teaches a small model how to author a complete workflow tree.
120
- *
121
- * @remarks
122
- * OWNED here now (ported from `@orkestrel/workflow`). Presents the SIMPLE flat shape
123
- * (`{ name, steps: [{ name }] }`) as the PRIMARY way with one complete worked example
124
- * ({@link WORKFLOW_TOOL_FLAT_EXAMPLE}), names that a step's `name` is a REGISTERED name (not a
125
- * human label), and documents the full nested `WorkflowDefinition` as the ADVANCED form with a
126
- * minimal example ({@link WORKFLOW_TOOL_NESTED_EXAMPLE}). The `parameters` the tool advertises
127
- * are the FLAT shape's schema; the nested form is the documented escape-hatch (the tool accepts
128
- * both).
129
- */
130
- /**
131
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkflowTool}
132
- * advertises in place of {@link WORKFLOW_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
133
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
134
- * for the full teaching description; the full text stays retrievable via
135
- * {@link import('./factories.js').createDescribeTool}.
136
- */
137
- var WORKFLOW_TOOL_SUMMARY = "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.";
138
- var WORKFLOW_TOOL_DESCRIPTION = [
139
- "Author and run a workflow (phases run sequentially, the tasks within a phase run concurrently) in one call.",
140
- "",
141
- "SIMPLEST way — a flat list of steps. Each step runs one registered behavior; steps run one after another:",
142
- " { \"name\": \"<workflow name>\", \"steps\": [ { \"name\": \"<registered name>\" }, ... ] }",
143
- "- a step's \"name\" is a REGISTERED behavior name (a registry key), NOT a human label.",
144
- "- the top-level \"name\" (the workflow name) is optional. Ids are filled in for you.",
145
- "Example:",
146
- JSON.stringify(WORKFLOW_TOOL_FLAT_EXAMPLE),
147
- "",
148
- "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):",
149
- JSON.stringify(WORKFLOW_TOOL_NESTED_EXAMPLE),
150
- "In the nested form you may omit any \"id\"/\"name\" and they are filled in positionally; a provided one is kept."
151
- ].join("\n");
152
- /**
153
- * The name {@link import('./factories.js').createWorkspaceTool} advertises by default — the key a
154
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
155
- *
156
- * @remarks
157
- * OWNED here now (ported from `@orkestrel/agent`).
158
- */
159
- var WORKSPACE_TOOL_NAME = "workspace";
160
- /**
161
- * A valid `WorkspaceOperation` (`@orkestrel/agent`) object — the canonical example embedded
162
- * VERBATIM in {@link WORKSPACE_TOOL_DESCRIPTION}.
163
- *
164
- * @remarks
165
- * OWNED here now (ported from `@orkestrel/agent`). A `'write'` op (the most common authoring
166
- * action): create or overwrite `notes.txt` with `hello`. Frozen so it cannot be mutated in
167
- * place.
168
- */
169
- var WORKSPACE_TOOL_EXAMPLE = Object.freeze({
170
- operation: "write",
171
- path: "notes.txt",
172
- content: "hello"
173
- });
174
- /**
175
- * The DESCRIPTION {@link import('./factories.js').createWorkspaceTool} advertises — a multi-line
176
- * guide that teaches a small model how to drive a workspace through the single
177
- * `operation`-keyed tool.
178
- *
179
- * @remarks
180
- * OWNED here now (ported from `@orkestrel/agent`). Mirrors {@link WORKFLOW_TOOL_DESCRIPTION}'s
181
- * teaching style: names the `operation` discriminant field, enumerates all 13 operations with
182
- * their FLAT fields, gives a worked example for the common ones, and embeds
183
- * {@link WORKSPACE_TOOL_EXAMPLE} verbatim.
184
- */
185
- /**
186
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkspaceTool}
187
- * advertises in place of {@link WORKSPACE_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
188
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
189
- * for the full teaching description; the full text stays retrievable via
190
- * {@link import('./factories.js').createDescribeTool}.
191
- */
192
- var WORKSPACE_TOOL_SUMMARY = "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.";
193
- var WORKSPACE_TOOL_DESCRIPTION = [
194
- "Read and edit files in a workspace. Every call is ONE operation, chosen by the \"operation\" field.",
195
- "All file operations act on the ACTIVE workspace; use \"workspaces\" then \"switch\" to move between workspaces.",
196
- "",
197
- "Operations (each takes the fields listed):",
198
- "- read { \"operation\": \"read\", \"path\": \"<file>\" } — return the file's text.",
199
- "- list { \"operation\": \"list\" } — list every file in the active workspace (path, state, size, lines, kind).",
200
- "- has { \"operation\": \"has\", \"path\": \"<file>\" } — whether the file exists.",
201
- "- search { \"operation\": \"search\", \"query\": \"<text>\", \"regex\"?: bool, \"exact\"?: bool, \"limit\"?: int } — find lines matching the query across all files.",
202
- "- replace { \"operation\": \"replace\", \"query\": \"<text>\", \"replacement\": \"<text>\", \"regex\"?: bool, \"exact\"?: bool, \"limit\"?: int } — replace matches across all files.",
203
- "- write { \"operation\": \"write\", \"path\": \"<file>\", \"content\": \"<text>\" } — create or overwrite the whole file.",
204
- "- 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.",
205
- "- prepend { \"operation\": \"prepend\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the start of the file.",
206
- "- append { \"operation\": \"append\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the end of the file.",
207
- "- move { \"operation\": \"move\", \"from\": \"<file>\", \"to\": \"<file>\" } — rename / move a file.",
208
- "- remove { \"operation\": \"remove\", \"path\": \"<file>\" } — delete a file.",
209
- "- workspaces { \"operation\": \"workspaces\" } — list the workspaces you can switch between (each id, file count, active).",
210
- "- switch { \"operation\": \"switch\", \"id\": \"<id>\" } — make the workspace with that id active (ids come from \"workspaces\").",
211
- "",
212
- "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.",
213
- "",
214
- "Example — write a file:",
215
- JSON.stringify(WORKSPACE_TOOL_EXAMPLE)
216
- ].join("\n");
217
- /**
218
- * The name {@link import('./factories.js').createDescribeTool} advertises by default — the key a
219
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
220
- *
221
- * @remarks
222
- * Net-new: pairs with the other three tools' lean {@link AGENT_TOOL_SUMMARY} /
223
- * {@link WORKFLOW_TOOL_SUMMARY} / {@link WORKSPACE_TOOL_SUMMARY} — a model that reads only the
224
- * advertised summary can call `describe` with that tool's registered name to get its full
225
- * teaching description back.
226
- */
227
- var DESCRIBE_TOOL_NAME = "describe";
228
- /**
229
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createDescribeTool}
230
- * advertises — this tool needs no teaching of its own, so its summary and description are both
231
- * short.
232
- */
233
- var DESCRIBE_TOOL_SUMMARY = "Return the full description of a named registered tool.";
234
- /**
235
- * The DESCRIPTION {@link import('./factories.js').createDescribeTool} advertises.
236
- *
237
- * @remarks
238
- * Deliberately short — unlike the workflow / workspace / agent tools, this one has no authoring
239
- * schema or multi-step protocol to teach.
240
- */
241
- var DESCRIBE_TOOL_DESCRIPTION = "Return the full description of a registered tool by its name. Required: name - the registered tool name (see another tool listing for available names).";
242
- /**
243
- * The name {@link import('./factories.js').createPromptTool} advertises by default — the key a
244
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
245
- */
246
- var PROMPT_TOOL_NAME = "ask";
247
- /**
248
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createPromptTool}
249
- * advertises in place of {@link PROMPT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
250
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
251
- * for the full teaching description; the full text stays retrievable via
252
- * {@link import('./factories.js').createDescribeTool}.
253
- */
254
- var PROMPT_TOOL_SUMMARY = "Ask another terminal a question and BLOCK until it answers; the call resolves with the answered value. Call describe('ask') for the required fields.";
255
- var PROMPT_TOOL_DESCRIPTION = [
256
- "Ask another terminal a question and block until it answers. This call does not return until the addressed terminal answers, or the prompt fails.",
257
- "",
258
- "Required:",
259
- " to - the terminal name to ask.",
260
- " form - the prompt kind: one of \"input\", \"password\", \"confirm\", \"select\", \"checkbox\", \"editor\".",
261
- " message - the question shown to the answering terminal.",
262
- "Optional:",
263
- " options - form-specific options (e.g. choices for \"select\"/\"checkbox\").",
264
- "A cycle (two terminals asking each other) or an expired prompt fails the call with a typed error.",
265
- "Example:",
266
- JSON.stringify({
267
- to: "reviewer",
268
- form: "confirm",
269
- message: "Approve the release?"
270
- })
271
- ].join("\n");
272
- /**
273
- * The name {@link import('./factories.js').createAnswerTool} advertises by default — the key a
274
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
275
- */
276
- var ANSWER_TOOL_NAME = "answer";
277
- /**
278
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createAnswerTool}
279
- * advertises in place of {@link ANSWER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
280
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
281
- * for the full teaching description; the full text stays retrievable via
282
- * {@link import('./factories.js').createDescribeTool}.
283
- */
284
- var ANSWER_TOOL_SUMMARY = "List prompts addressed to this terminal, or answer one by id. Call describe('answer') for the required fields.";
285
- var ANSWER_TOOL_DESCRIPTION = [
286
- "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.",
287
- "",
288
- "Operations:",
289
- "- pending { \"operation\": \"pending\" } — list every prompt currently addressed to this terminal (id, form, message, options, time).",
290
- "- 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\").",
291
- "Example — list pending prompts:",
292
- JSON.stringify({ operation: "pending" }),
293
- "Example — answer one:",
294
- JSON.stringify({
295
- operation: "answer",
296
- id: "abc123",
297
- value: true
298
- })
299
- ].join("\n");
300
- /**
301
- * The name the upcoming `createDatabaseTool` factory will advertise by default — the key a model
302
- * calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
303
- *
304
- * @remarks
305
- * SRC-1 of a 3-unit spine: this unit lands the persistence + schema foundation
306
- * ({@link import('./types.js').DatabaseDefinition}, {@link import('./types.js').DefinitionStoreInterface},
307
- * {@link import('./helpers.js').expandTables}); `createDatabaseTool` itself is built in a later unit.
308
- */
309
- var DATABASE_TOOL_NAME = "database";
310
- /**
311
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} the upcoming database tool
312
- * will advertise in place of {@link DATABASE_TOOL_DESCRIPTION}.
313
- */
314
- var DATABASE_TOOL_SUMMARY = "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.";
315
- /**
316
- * The DESCRIPTION the upcoming database tool will advertise — a multi-line guide that teaches a
317
- * small model the operation list, the SERIALIZED criteria form, and the {@link import('./types.js').TableSpec}
318
- * column DSL.
319
- *
320
- * @remarks
321
- * The criteria form is deliberately SERIALIZED (never fluent) — every condition is a flat object
322
- * `{ column, operator, values, connector? }` where `values` is ALWAYS an array, even for a
323
- * single-value operator (`{ column: 'age', operator: 'from', values: [18] }`), so a small model
324
- * never has to chain method calls or guess whether a value is scalar or a list.
325
- */
326
- var DATABASE_TOOL_DESCRIPTION = [
327
- "Create and query a database. Every call is ONE operation, chosen by the \"operation\" field.",
328
- "",
329
- "Operations (each takes the fields listed):",
330
- "- create { \"operation\": \"create\", \"id\": \"<database id>\", \"tables\": { \"<table>\": { \"columns\": { \"<column>\": \"string\" | \"integer\" | \"number\" | \"boolean\" | { \"type\": \"string\", \"optional\": true } } } } } — define a new database.",
331
- "- tables { \"operation\": \"tables\", \"id\": \"<database id>\" } — list a database's table names.",
332
- "- get { \"operation\": \"get\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — fetch one row by its primary key.",
333
- "- records { \"operation\": \"records\", \"id\": \"<database id>\", \"table\": \"<table>\", \"criteria\"?: <Criteria> } — list rows matching criteria.",
334
- "- count { \"operation\": \"count\", \"id\": \"<database id>\", \"table\": \"<table>\", \"criteria\"?: <Criteria> } — count rows matching criteria.",
335
- "- aggregate { \"operation\": \"aggregate\", \"id\": \"<database id>\", \"table\": \"<table>\", \"column\": \"<column>\", \"function\": \"count\" | \"sum\" | \"average\" | \"minimum\" | \"maximum\", \"criteria\"?: <Criteria> } — compute an aggregate.",
336
- "- add { \"operation\": \"add\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — insert a row (fails on a duplicate key).",
337
- "- set { \"operation\": \"set\", \"id\": \"<database id>\", \"table\": \"<table>\", \"row\": { ... } } — upsert a row.",
338
- "- update { \"operation\": \"update\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\", \"row\": { ... } } — patch an existing row.",
339
- "- remove { \"operation\": \"remove\", \"id\": \"<database id>\", \"table\": \"<table>\", \"key\": \"<row key>\" } — delete a row by key.",
340
- "- migrate { \"operation\": \"migrate\", \"id\": \"<database id>\", \"tables\": { ... } } — replace the table layout in place.",
341
- "- destroy { \"operation\": \"destroy\", \"id\": \"<database id>\" } — drop a database entirely.",
342
- "",
343
- "Criteria form — SERIALIZED, never fluent. A condition is a flat object; \"values\" is ALWAYS an array, even for one value:",
344
- " { \"conditions\": [ { \"column\": \"age\", \"operator\": \"from\", \"values\": [18], \"connector\": \"and\" } ], \"order\"?: [...], \"offset\"?: 0, \"limit\"?: 100 }",
345
- " operators: equals, not, above, below, from, to, between, like, glob, starts, ends, any, none, absent, present.",
346
- " \"connector\" joins this condition to the next (\"and\" | \"or\"); omit on the last condition.",
347
- "",
348
- "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.",
349
- "Example — create a database:",
350
- JSON.stringify({
351
- operation: "create",
352
- id: "shop",
353
- tables: { products: { columns: {
354
- name: "string",
355
- price: "number",
356
- notes: {
357
- type: "string",
358
- optional: true
359
- }
360
- } } }
361
- }),
362
- "Example — query with criteria:",
363
- JSON.stringify({
364
- operation: "records",
365
- id: "shop",
366
- table: "products",
367
- criteria: { conditions: [{
368
- column: "price",
369
- operator: "below",
370
- values: [50]
371
- }] }
372
- })
373
- ].join("\n");
374
- /** 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. */
375
- var DATABASE_TOOL_LIMIT = 1e3;
376
- /** The database tool's mutating operations — disabled by `DatabaseToolOptions.readonly`. */
377
- var DATABASE_TOOL_MUTATIONS = /* @__PURE__ */ new Set([
378
- "create",
379
- "add",
380
- "set",
381
- "update",
382
- "remove",
383
- "migrate",
384
- "destroy"
385
- ]);
386
- /**
387
- * The name `createRelationTool` advertises by default — the key a model calls and the
388
- * `ToolManagerInterface` (`@orkestrel/agent`) registers under.
389
- */
390
- var RELATION_TOOL_NAME = "relation";
391
- /**
392
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} the relation tool advertises
393
- * in place of {@link RELATION_TOOL_DESCRIPTION}.
394
- */
395
- var RELATION_TOOL_SUMMARY = "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.";
396
- /**
397
- * The DESCRIPTION the relation tool advertises — a multi-line guide that teaches a small model
398
- * the operation list and the flat dot-path `include` syntax.
399
- *
400
- * @remarks
401
- * An include path is a FLAT dot-separated string (`'contacts.account'`), never a nested object —
402
- * the same small-model ergonomic lever the other tools in this package use for flat args.
403
- */
404
- var RELATION_TOOL_DESCRIPTION = [
405
- "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).",
406
- "",
407
- "Operations (each takes the fields listed):",
408
- "- load { \"operation\": \"load\", \"model\": \"<model>\", \"key\": \"<row key>\", \"include\"?: [\"<path>\", ...] } — fetch one (or, with an array key, several) row(s) with related rows attached.",
409
- "- find { \"operation\": \"find\", \"model\": \"<model>\", \"include\"?: [\"<path>\", ...], \"limit\"?: <n>, \"offset\"?: <n>, \"sort\"?: \"<column>\", \"direction\"?: \"ascending\"|\"descending\" } — list rows, each with related rows attached.",
410
- "- link { \"operation\": \"link\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — connect two rows through a \"through\" relation.",
411
- "- unlink { \"operation\": \"unlink\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\", \"target\": \"<related row key>\" } — disconnect two rows.",
412
- "- links { \"operation\": \"links\", \"model\": \"<model>\", \"key\": \"<row key>\", \"relation\": \"<relation>\" } — list every key linked to a row through a \"through\" relation.",
413
- "",
414
- "\"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.",
415
- "Example — load a row with two levels of relations:",
416
- JSON.stringify({
417
- operation: "load",
418
- model: "orders",
419
- key: "1",
420
- include: ["contacts.account"]
421
- })
422
- ].join("\n");
423
- /** The default cap on rows a `find` / `links` call returns when the caller omits `limit` — the relation tool's default row ceiling. */
424
- var RELATION_TOOL_LIMIT = 1e3;
425
- /** The default cap on how many `include` path segments deep a `load` / `find` call may traverse — the relation tool's default include-depth ceiling. */
426
- var RELATION_TOOL_DEPTH = 3;
427
- /**
428
- * The name {@link import('./factories.js').createInferTool} advertises by default — the key a
429
- * model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
430
- */
431
- var INFER_TOOL_NAME = "infer";
432
- /**
433
- * The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createInferTool}
434
- * advertises in place of {@link INFER_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
435
- * (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
436
- * for the full teaching description; the full text stays retrievable via
437
- * {@link import('./factories.js').createDescribeTool}.
438
- */
439
- var INFER_TOOL_SUMMARY = "Infer a JSON Schema (as advertised tool parameters) from one or more example values. Call describe('infer') for the required fields.";
440
- var INFER_TOOL_DESCRIPTION = [
441
- "Infer a JSON Schema from example values, returned in the same shape a tool advertises its parameters.",
442
- "",
443
- "Required:",
444
- " samples - an array of at least one example value to infer the schema from.",
445
- "Optional:",
446
- " format - infer string formats (date-time, email, ...) from the samples. Defaults to false.",
447
- " enum - infer enum constraints from repeated literal values across the samples. Defaults to false.",
448
- " candidates - values to check against the freshly inferred schema. When present, the result",
449
- " is wrapped as { parameters, checks } instead of the bare parameters record, one",
450
- " check per candidate (same index). Every check has the uniform shape",
451
- " { index, valid, coercible, faults? }. `valid` is a STRICT verdict (no coercion)",
452
- " — e.g. the number 7 is NOT valid against a string slot. `coercible` answers a",
453
- " separate question: would the SAME value be accepted by an endpoint tool call,",
454
- " whose enforcement NORMALIZES args (7 coerces to '7')? So 7 against a string slot",
455
- " yields { valid: false, coercible: true, faults: [] } — a strict mismatch that",
456
- " normalization would silently accept, so faults is EMPTY. `faults` only ever",
457
- " populates for a non-coercible mismatch (a wrong type normalization cannot fix,",
458
- " a missing required key, an out-of-enum value); checks never throw, regardless of",
459
- " candidate shape.",
460
- "Example (no candidates):",
461
- ` in: ${JSON.stringify({ samples: [{
462
- id: 1,
463
- name: "Ada"
464
- }, {
465
- id: 2,
466
- name: "Bob"
467
- }] })}`,
468
- ` out: ${JSON.stringify({
469
- type: "object",
470
- properties: {
471
- id: { type: "integer" },
472
- name: { type: "string" }
473
- },
474
- required: ["id", "name"],
475
- additionalProperties: false
476
- })}`,
477
- "Example (with candidates):",
478
- ` in: ${JSON.stringify({
479
- samples: [{
480
- id: 1,
481
- name: "Ada"
482
- }],
483
- candidates: [
484
- {
485
- id: 3,
486
- name: "Cy"
487
- },
488
- {
489
- id: "x",
490
- name: "Cy"
491
- },
492
- {
493
- id: 1,
494
- name: 7
495
- }
496
- ]
497
- })}`,
498
- ` out: ${JSON.stringify({
499
- parameters: {
500
- type: "object",
501
- properties: {
502
- id: { type: "integer" },
503
- name: { type: "string" }
504
- },
505
- required: ["id", "name"],
506
- additionalProperties: false
507
- },
508
- checks: [
509
- {
510
- index: 0,
511
- valid: true,
512
- coercible: true
513
- },
514
- {
515
- index: 1,
516
- valid: false,
517
- coercible: false,
518
- faults: "<structured faults>"
519
- },
520
- {
521
- index: 2,
522
- valid: false,
523
- coercible: true,
524
- faults: []
525
- }
526
- ]
527
- })}`
528
- ].join("\n");
529
- //#endregion
530
- //#region src/core/errors.ts
531
- /**
532
- * Thrown by {@link import('./factories.js').createAgentTool}'s and
533
- * {@link import('./factories.js').createDescribeTool}'s handlers on every failure path — a
534
- * malformed / unresolvable call or an unknown tool name (`TOOL`), a delegation that would
535
- * exceed the configured depth bound or re-enter an ancestor (`DEPTH`), a prompt cycle
536
- * (`DEADLOCK`), a prompt that expired before it was answered (`EXPIRE`), or an answer that
537
- * failed to apply (`ANSWER`) — the last three thrown by
538
- * {@link import('./factories.js').createPromptTool} / {@link import('./factories.js').createAnswerTool}.
539
- * The upcoming database / relation tools (SRC-1's later units) will throw it too: a typed
540
- * `@orkestrel/database` failure re-surfaces as `DATABASE`, a typed `@orkestrel/relation` failure
541
- * as `RELATION` — each carrying the package's own granular error code in `context`.
542
- *
543
- * @remarks
544
- * Carries a machine-readable `code` (see {@link import('./types.js').AgentToolErrorCode}) and
545
- * an optional `context` bag for structured diagnostics. The `ToolManagerInterface`
546
- * (`@orkestrel/agent`) isolates every throw into the canonical tool result's top-level `error`
547
- * (AGENTS §14) — nothing escapes the run.
548
- *
549
- * @example
550
- * ```ts
551
- * import { AgentToolError, isAgentToolError } from '@src/core'
552
- *
553
- * try {
554
- * throw new AgentToolError('TOOL', 'task is required')
555
- * } catch (error) {
556
- * if (isAgentToolError(error)) console.log(error.code) // 'TOOL'
557
- * }
558
- * ```
559
- */
560
- var AgentToolError = class extends Error {
561
- code;
562
- constructor(code, message, context) {
563
- super(message);
564
- this.name = "AgentToolError";
565
- this.code = code;
566
- if (context !== void 0) this.context = context;
567
- }
568
- };
569
- /**
570
- * Type guard narrowing an unknown caught value to an {@link AgentToolError}.
571
- *
572
- * @param value - The value to test (typically a `catch` binding)
573
- * @returns `true` when `value` is an {@link AgentToolError}
574
- *
575
- * @example
576
- * ```ts
577
- * import { isAgentToolError } from '@src/core'
578
- *
579
- * try {
580
- * // ...
581
- * } catch (error) {
582
- * if (isAgentToolError(error)) console.log(error.code)
583
- * }
584
- * ```
585
- */
586
- function isAgentToolError(value) {
587
- return value instanceof AgentToolError;
588
- }
589
- //#endregion
590
- //#region src/core/shapers.ts
591
- /**
592
- * The shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` (the
593
- * terminal identity to address), `form` (which of the six {@link import('@orkestrel/terminal').PromptType}
594
- * forms to ask), `message`, an optional `timeout` override, and every per-form optional field
595
- * FLATTENED onto one object (mirrors `workspaceToolShape`'s flat-arm style, but a single shared
596
- * shape rather than a discriminated union — `form` alone does not vary the REQUIRED fields, only
597
- * which of the optional ones apply, so a flat shape stays faithful without duplicating `to` /
598
- * `message` / `timeout` across six near-identical arms).
599
- *
600
- * @remarks
601
- * `choices` backs `'select'` / `'checkbox'`; `default` backs `'input'` / `'confirm'` / `'select'`
602
- * (a string for the first two forms' text default, `'true'`/`'false'` string for confirm — the
603
- * contract layer cannot vary a field's type by a sibling field's value, so `default` stays a
604
- * string and the handler coerces per form); `mask` backs `'password'`; `min` / `max` backs
605
- * `'checkbox'`; `validate` (declarative only) backs the four text-shaped forms
606
- * (`'input'` / `'password'` / `'confirm'` / `'editor'`).
607
- */
608
- var promptToolShape = objectShape({
609
- to: stringShape({
610
- min: 1,
611
- description: "The terminal identity to address the prompt to."
612
- }),
613
- form: literalShape([
614
- "input",
615
- "password",
616
- "confirm",
617
- "select",
618
- "checkbox",
619
- "editor"
620
- ], { description: "Which prompt form to ask." }),
621
- message: stringShape({
622
- min: 1,
623
- description: "The prompt's question."
624
- }),
625
- default: optionalShape(stringShape({ description: "The default answer if the responder submits blank — 'input' / 'editor' text, 'confirm' 'true'/'false', or a 'select' choice value." })),
626
- choices: optionalShape(arrayShape(objectShape({
627
- name: stringShape({
628
- min: 1,
629
- description: "The choice label shown to the answering party."
630
- }),
631
- value: stringShape({
632
- min: 1,
633
- description: "The value submitted when this choice is picked."
634
- }),
635
- description: optionalShape(stringShape({ description: "An optional one-line elaboration." }))
636
- }), { description: "The selectable choices for 'select' / 'checkbox'." })),
637
- mask: optionalShape(stringShape({
638
- min: 1,
639
- description: "The mask character 'password' renders in place of input."
640
- })),
641
- min: optionalShape(integerShape({
642
- min: 0,
643
- description: "The minimum number of 'checkbox' selections required."
644
- })),
645
- max: optionalShape(integerShape({
646
- min: 0,
647
- description: "The maximum number of 'checkbox' selections allowed."
648
- })),
649
- validate: optionalShape(objectShape({
650
- required: optionalShape(booleanShape({ description: "Reject an empty (trimmed) input." })),
651
- minimum: optionalShape(integerShape({
652
- min: 0,
653
- description: "Reject an input shorter than this many characters."
654
- })),
655
- maximum: optionalShape(integerShape({
656
- min: 0,
657
- description: "Reject an input longer than this many characters."
658
- })),
659
- pattern: optionalShape(stringShape({ description: "Reject an input that fails this regular-expression source." })),
660
- email: optionalShape(booleanShape({ description: "Require a valid email-address shape." })),
661
- url: optionalShape(booleanShape({ description: "Require a valid URL shape." })),
662
- numeric: optionalShape(booleanShape({ description: "Require a numeric value." })),
663
- integer: optionalShape(booleanShape({ description: "Require an integer value." })),
664
- alphanumeric: optionalShape(booleanShape({ description: "Require letters and digits only." }))
665
- })),
666
- timeout: optionalShape(integerShape({
667
- min: 0,
668
- description: "Milliseconds to wait before the prompt expires."
669
- }))
670
- });
671
- /**
672
- * The shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated
673
- * by `operation`: `'pending'` lists the prompts addressed to this tool's terminal, `'answer'`
674
- * resolves one by `id` with a `value`.
675
- *
676
- * @remarks
677
- * `value`'s type varies by the ORIGINAL prompt's form (`string` for `'input'` / `'password'` /
678
- * `'select'` / `'editor'`, `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`) —
679
- * `unionShape(stringShape(), booleanShape(), arrayShape(stringShape()))` expresses that
680
- * union directly, so `value` is typed as the full `string | boolean | readonly string[]` union
681
- * here (no lossy string-only fallback needed).
682
- */
683
- var answerToolShape = unionShape(objectShape({ operation: literalShape(["pending"], { description: "List the prompts currently addressed to this terminal." }) }), objectShape({
684
- operation: literalShape(["answer"], { description: "Answer one pending prompt by id." }),
685
- id: stringShape({
686
- min: 1,
687
- description: "The id of the pending prompt to answer."
688
- }),
689
- value: unionShape(stringShape({ description: "A text / select / editor answer." }), booleanShape({ description: "A confirm answer." }), arrayShape(stringShape(), { description: "A checkbox answer — the checked values." }))
690
- }));
691
- /**
692
- * The shape of {@link import('./types.js').AgentToolArguments} —
693
- * {@link import('./factories.js').createAgentTool}'s advertised `parameters`.
694
- *
695
- * @remarks
696
- * `task` is the only required field (a non-empty string); `provider` / `tools` / `system`
697
- * are per-call overrides of the tool's own configured defaults.
698
- */
699
- var agentToolShape = objectShape({
700
- task: stringShape({
701
- min: 1,
702
- description: "The instructions the sub-agent should carry out."
703
- }),
704
- provider: optionalShape(stringShape({
705
- min: 1,
706
- description: "Registry key of the provider to run the sub-agent against (overrides the default)."
707
- })),
708
- tools: optionalShape(arrayShape(stringShape({ min: 1 }), { description: "Registry keys of the tools loaded into the sub-agent (replaces the default list)." })),
709
- system: optionalShape(stringShape({ description: "A system prompt seeding the sub-agent's context (overrides the default)." }))
710
- });
711
- /**
712
- * The shape of {@link import('./types.js').DescribeToolArguments} —
713
- * {@link import('./factories.js').createDescribeTool}'s advertised `parameters`.
714
- *
715
- * @remarks
716
- * `name` is the only field (a non-empty string) — the registered tool name to look up.
717
- */
718
- var describeToolShape = objectShape({ name: stringShape({
719
- min: 1,
720
- description: "The registered name of the tool whose full description to return."
721
- }) });
722
- /**
723
- * The shape of a {@link import('./types.js').TaskDraft} — identical to a strict task shape
724
- * EXCEPT `id` and `name` are OPTIONAL.
725
- */
726
- var taskDraftShape = objectShape({
727
- id: optionalShape(stringShape({
728
- min: 1,
729
- description: "Task id; auto-filled when omitted."
730
- })),
731
- name: optionalShape(stringShape({
732
- min: 1,
733
- description: "Task name; defaults to the id when omitted."
734
- })),
735
- description: optionalShape(stringShape({ description: "Optional task description." })),
736
- run: optionalShape(stringShape({
737
- min: 1,
738
- description: "The registered behavior name to invoke (a registry key, not a label); omitted has no handler."
739
- })),
740
- retries: optionalShape(integerShape({
741
- min: 0,
742
- description: "Extra attempts after the first on failure; overrides the phase default. Omitted means none."
743
- })),
744
- timeout: optionalShape(integerShape({
745
- min: 0,
746
- description: "Per-attempt deadline in milliseconds; overrides the phase default. Omitted means no deadline."
747
- }))
748
- });
749
- /**
750
- * The shape of a PHASE in a draft workflow — identical to a strict phase shape EXCEPT `id` and
751
- * `name` are OPTIONAL, and its tasks are {@link taskDraftShape}s.
752
- */
753
- var phaseDraftShape = objectShape({
754
- id: optionalShape(stringShape({
755
- min: 1,
756
- description: "Phase id; auto-filled when omitted."
757
- })),
758
- name: optionalShape(stringShape({
759
- min: 1,
760
- description: "Phase name; defaults to the id when omitted."
761
- })),
762
- description: optionalShape(stringShape({ description: "Optional phase description." })),
763
- tasks: arrayShape(taskDraftShape, { description: "The phase tasks; they run CONCURRENTLY." }),
764
- concurrency: optionalShape(integerShape({
765
- min: 1,
766
- description: "Max tasks in flight at once (a resource throttle); omitted means unbounded."
767
- })),
768
- bail: optionalShape(literalShape([true, false], { description: "Per-phase failure-policy override; omitted inherits the workflow bail." }))
769
- });
770
- /**
771
- * The shape of a DRAFT workflow — identical to a strict workflow shape EXCEPT `id` and `name`
772
- * are OPTIONAL at all three levels (workflow / phase / task), so a small model can omit the six
773
- * identity strings and let the tool synthesize them positionally.
774
- *
775
- * @remarks
776
- * The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.
777
- * `run` stays required on the strict form; a provided `id` / `name` still has `minLength: 1` (so
778
- * an explicitly-empty `id: ''` is REJECTED, not auto-filled). After
779
- * {@link import('./helpers.js').completeDraft} fills the missing ids/names, the result is
780
- * validated against the STRICT `createWorkflowContract` (`@orkestrel/workflow`) gate before
781
- * running.
782
- */
783
- var workflowDraftShape = objectShape({
784
- id: optionalShape(stringShape({
785
- min: 1,
786
- description: "Workflow id; auto-filled when omitted."
787
- })),
788
- name: optionalShape(stringShape({
789
- min: 1,
790
- description: "Workflow name; defaults to the id when omitted."
791
- })),
792
- description: optionalShape(stringShape({ description: "Optional workflow description." })),
793
- phases: arrayShape(phaseDraftShape, { description: "The workflow phases; they run SEQUENTIALLY, in order." }),
794
- bail: optionalShape(literalShape([true, false], { description: "Failure policy: false (default) continues gracefully, true halts on the first failure." }))
795
- });
796
- /**
797
- * The shape of ONE flat step — `{ name }` — the building block of {@link workflowStepsShape}.
798
- *
799
- * @remarks
800
- * `name` is the REGISTERED behavior name the step runs (it becomes the task's `run`). The tool
801
- * expands each step into a one-task phase, in order ({@link import('./helpers.js').expandSteps}).
802
- */
803
- var stepShape = objectShape({ name: stringShape({
804
- min: 1,
805
- description: "The registered behavior name this step runs (becomes the task run)."
806
- }) });
807
- /**
808
- * The FLAT authoring shape {@link import('./factories.js').createWorkflowTool} advertises as its
809
- * `parameters` — the simplest surface a small model can fill: `{ name?, steps: [{ name }] }`.
810
- *
811
- * @remarks
812
- * A deliberately-reduced surface: a flat ordered list of steps, each a `{ name }`. The tool
813
- * EXPANDS it ({@link import('./helpers.js').expandSteps}) into a full
814
- * {@link import('./types.js').WorkflowDefinition} — one one-task phase per step, in order —
815
- * then validates against the STRICT `createWorkflowContract` (`@orkestrel/workflow`) gate. The
816
- * full nested form is STILL accepted by the tool (it branches on the args' shape) and is
817
- * documented as the advanced escape-hatch in the tool's description — but THIS is what
818
- * `parameters` advertises.
819
- */
820
- var workflowStepsShape = objectShape({
821
- name: optionalShape(stringShape({
822
- min: 1,
823
- description: "Optional workflow name."
824
- })),
825
- steps: arrayShape(stepShape, { description: "The ordered steps to run, one after another (each becomes a one-task phase)." })
826
- });
827
- /**
828
- * The shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union
829
- * over the 13 workspace edit / read / navigation operations, discriminated by the `operation`
830
- * literal (never a bare `kind`; AGENTS §4.4). Each variant leads with its `operation`
831
- * discriminant then its FLAT fields, every field via `stringShape` / `optionalShape` /
832
- * `integerShape({ min: 1 })` / `booleanShape`, each carrying a strong field-level `description`.
833
- *
834
- * @remarks
835
- * The union compiles to an `anyOf` JSON Schema + a `unionOf` guard + a first-match parser
836
- * automatically ({@link import('./factories.js').createWorkspaceTool} types the result to the
837
- * hand-written {@link import('./types.js').WorkspaceOperation}). `limit` and the four `'splice'`
838
- * caret components are POSITIVE integers (`integerShape({ min: 1 })`); `regex` / `exact` are
839
- * `optionalShape(booleanShape(...))`. The two REGISTRY arms — `workspaces` (list the workspaces
840
- * the model can move between) and `switch` (re-point the active one by `id`) — let a model
841
- * DISCOVER then CHOOSE which workspace the edit / read arms target.
842
- */
843
- var workspaceToolShape = unionShape(objectShape({
844
- operation: literalShape(["read"], { description: "Read a whole text file's text by path." }),
845
- path: stringShape({ description: "The path of the file to read." })
846
- }), objectShape({ operation: literalShape(["list"], { description: "List every file in the workspace." }) }), objectShape({
847
- operation: literalShape(["has"], { description: "Check whether a file exists at the path." }),
848
- path: stringShape({ description: "The path to check for." })
849
- }), objectShape({
850
- operation: literalShape(["search"], { description: "Search every text file for a query, returning each hit." }),
851
- query: stringShape({ description: "The text (or regular-expression source) to search for." }),
852
- regex: optionalShape(booleanShape({ description: "Treat the query as a regular expression. Defaults to false (a literal substring)." })),
853
- exact: optionalShape(booleanShape({ description: "Match case-sensitively. Defaults to true (set false for case-insensitive)." })),
854
- limit: optionalShape(integerShape({
855
- min: 1,
856
- description: "Stop after this many matches across all files. Omitted means unlimited."
857
- }))
858
- }), objectShape({
859
- operation: literalShape(["replace"], { description: "Replace a query with a replacement across every text file." }),
860
- query: stringShape({ description: "The text (or regular-expression source) to replace." }),
861
- replacement: stringShape({ description: "The text to substitute for each match." }),
862
- regex: optionalShape(booleanShape({ description: "Treat the query as a regular expression. Defaults to false (a literal substring)." })),
863
- exact: optionalShape(booleanShape({ description: "Match case-sensitively. Defaults to true (set false for case-insensitive)." })),
864
- limit: optionalShape(integerShape({
865
- min: 1,
866
- description: "Stop after this many replacements across all files. Omitted means unlimited."
867
- }))
868
- }), objectShape({
869
- operation: literalShape(["write"], { description: "Create or overwrite a whole file with content." }),
870
- path: stringShape({ description: "The path of the file to write." }),
871
- content: stringShape({ description: "The full new contents of the file." })
872
- }), objectShape({
873
- operation: literalShape(["splice"], { description: "Replace a 1-based range of an existing text file (from inclusive, to exclusive) with content." }),
874
- path: stringShape({ description: "The path of the text file to edit." }),
875
- content: stringShape({ description: "The text to splice in place of the range." }),
876
- fromLine: integerShape({
877
- min: 1,
878
- description: "The 1-based start line of the range (inclusive)."
879
- }),
880
- fromColumn: integerShape({
881
- min: 1,
882
- description: "The 1-based start column of the range (inclusive; column 1 is the first character)."
883
- }),
884
- toLine: integerShape({
885
- min: 1,
886
- description: "The 1-based end line of the range (exclusive)."
887
- }),
888
- toColumn: integerShape({
889
- min: 1,
890
- description: "The 1-based end column of the range (exclusive)."
891
- })
892
- }), objectShape({
893
- operation: literalShape(["prepend"], { description: "Add content to the start of a file (creating it when absent)." }),
894
- path: stringShape({ description: "The path of the file to prepend to." }),
895
- content: stringShape({ description: "The text to add at the start of the file." })
896
- }), objectShape({
897
- operation: literalShape(["append"], { description: "Add content to the end of a file (creating it when absent)." }),
898
- path: stringShape({ description: "The path of the file to append to." }),
899
- content: stringShape({ description: "The text to add at the end of the file." })
900
- }), objectShape({
901
- operation: literalShape(["move"], { description: "Rename or move a file (overwriting an occupied target)." }),
902
- from: stringShape({ description: "The current path of the file." }),
903
- to: stringShape({ description: "The new path for the file." })
904
- }), objectShape({
905
- operation: literalShape(["remove"], { description: "Delete a file from the workspace." }),
906
- path: stringShape({ description: "The path of the file to remove." })
907
- }), objectShape({ operation: literalShape(["workspaces"], { description: "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." }) }), objectShape({
908
- operation: literalShape(["switch"], { description: "Switch the active workspace to the one with this id (get ids from the \"workspaces\" operation). Edit and read operations then target it." }),
909
- id: stringShape({ description: "The id of the workspace to make active (from the \"workspaces\" listing)." })
910
- }));
911
- /** A {@link import('./types.js').ColumnKind} literal — the leaf {@link columnSpecShape} wraps. */
912
- var columnKindShape = literalShape([
913
- "string",
914
- "integer",
915
- "number",
916
- "boolean"
917
- ], { description: "A column type: \"string\" | \"integer\" | \"number\" | \"boolean\"." });
918
- /** A {@link import('./types.js').ColumnSpec} — a bare {@link columnKindShape}, or `{ type, optional }`. */
919
- var columnSpecShape = unionShape(columnKindShape, objectShape({
920
- type: columnKindShape,
921
- optional: optionalShape(booleanShape({ description: "Whether the column may be absent from a row." }))
922
- }));
923
- /** A {@link import('./types.js').TableSpec} — table name to `{ columns }`, each column a {@link columnSpecShape}. */
924
- var tableSpecShape = recordShape(objectShape({ columns: recordShape(columnSpecShape, { description: "Column name to its type." }) }), { description: "Table name to its column layout." });
925
- /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
926
- var keyShape = unionShape(arrayShape(unionShape(stringShape(), numberShape()), { description: "Multiple row keys, positional — a miss at an index is undefined there." }), stringShape({ description: "One row key." }), numberShape({ description: "One row key." }));
927
- /** A loose row — a flat object of column name to JSON value; the array form (multiple rows) resolves FIRST per AGENTS §9.2. */
928
- var rowShape = recordShape(jsonShape(), { description: "A row as a flat object of column name to value." });
929
- /** One or many loose rows — the array form resolves FIRST per AGENTS §9.2. */
930
- var rowsShape = unionShape(arrayShape(rowShape, { description: "Multiple rows." }), rowShape);
931
- /** One SERIALIZED WHERE condition — `values` is ALWAYS an array, even for a single-value operator. */
932
- var conditionShape = objectShape({
933
- column: stringShape({ description: "The column this condition applies to." }),
934
- operator: literalShape([
935
- "equals",
936
- "not",
937
- "above",
938
- "below",
939
- "from",
940
- "to",
941
- "between",
942
- "like",
943
- "glob",
944
- "starts",
945
- "ends",
946
- "any",
947
- "none",
948
- "absent",
949
- "present"
950
- ], { description: "The comparison operator." }),
951
- values: arrayShape(jsonShape(), { description: "The operand values the operator needs (always an array, even for one value)." }),
952
- connector: optionalShape(literalShape(["and", "or"], { description: "Joins this condition to the next; omit on the last condition." }))
953
- });
954
- /** One sort term. */
955
- var orderShape = objectShape({
956
- column: stringShape({ description: "The column to sort by." }),
957
- direction: literalShape(["ascending", "descending"], { description: "The sort direction." })
958
- });
959
- /** The SERIALIZED criteria form — conditions, order, and pagination. */
960
- var criteriaShape = objectShape({
961
- conditions: optionalShape(arrayShape(conditionShape, { description: "The WHERE conditions, folded left to right." })),
962
- order: optionalShape(arrayShape(orderShape, { description: "The sort terms, applied in order." })),
963
- limit: optionalShape(integerShape({
964
- min: 0,
965
- description: "Max rows to return."
966
- })),
967
- offset: optionalShape(integerShape({
968
- min: 0,
969
- description: "Rows to skip before returning."
970
- }))
971
- });
972
- /**
973
- * The shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —
974
- * discriminated by `operation` into the 12 database operations (`'create'` / `'tables'` /
975
- * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /
976
- * `'remove'` / `'migrate'` / `'destroy'`).
977
- *
978
- * @remarks
979
- * Every arm carries `id` (the database id). `'create'` / `'migrate'` carry `tables` (the
980
- * {@link import('./types.js').TableSpec} column DSL, compiled via
981
- * {@link import('./helpers.js').expandTables}); `'get'` / `'update'` / `'remove'` carry `key`
982
- * (one key or an array of keys, positional); `'add'` / `'set'` carry `row` (one row or an array of
983
- * rows); `'update'` also carries `changes` (a loose partial row); `'records'` / `'count'` /
984
- * `'aggregate'` carry an optional `criteria` (the SERIALIZED form — `values` is ALWAYS an array,
985
- * even for a single-value operator, so a caller never chains method calls or guesses arity).
986
- */
987
- var databaseToolShape = unionShape(objectShape({
988
- operation: literalShape(["create"], { description: "Define a new database." }),
989
- id: stringShape({
990
- min: 1,
991
- description: "The database id."
992
- }),
993
- tables: tableSpecShape,
994
- driver: optionalShape(stringShape({
995
- min: 1,
996
- description: "The registered driver key. Defaults to \"memory\"."
997
- })),
998
- keys: optionalShape(recordShape(stringShape(), { description: "Table name to its primary-key column." }))
999
- }), objectShape({
1000
- operation: literalShape(["tables"], { description: "List a database's table names." }),
1001
- id: stringShape({
1002
- min: 1,
1003
- description: "The database id."
1004
- })
1005
- }), objectShape({
1006
- operation: literalShape(["get"], { description: "Fetch one or more rows by primary key." }),
1007
- id: stringShape({
1008
- min: 1,
1009
- description: "The database id."
1010
- }),
1011
- table: stringShape({
1012
- min: 1,
1013
- description: "The table name."
1014
- }),
1015
- key: keyShape
1016
- }), objectShape({
1017
- operation: literalShape(["records"], { description: "List rows matching criteria." }),
1018
- id: stringShape({
1019
- min: 1,
1020
- description: "The database id."
1021
- }),
1022
- table: stringShape({
1023
- min: 1,
1024
- description: "The table name."
1025
- }),
1026
- criteria: optionalShape(criteriaShape)
1027
- }), objectShape({
1028
- operation: literalShape(["count"], { description: "Count rows matching criteria." }),
1029
- id: stringShape({
1030
- min: 1,
1031
- description: "The database id."
1032
- }),
1033
- table: stringShape({
1034
- min: 1,
1035
- description: "The table name."
1036
- }),
1037
- criteria: optionalShape(criteriaShape)
1038
- }), objectShape({
1039
- operation: literalShape(["aggregate"], { description: "Compute an aggregate over a column." }),
1040
- id: stringShape({
1041
- min: 1,
1042
- description: "The database id."
1043
- }),
1044
- table: stringShape({
1045
- min: 1,
1046
- description: "The table name."
1047
- }),
1048
- function: literalShape([
1049
- "count",
1050
- "sum",
1051
- "average",
1052
- "minimum",
1053
- "maximum"
1054
- ], { description: "The aggregate function." }),
1055
- column: stringShape({
1056
- min: 1,
1057
- description: "The column to aggregate."
1058
- }),
1059
- criteria: optionalShape(criteriaShape)
1060
- }), objectShape({
1061
- operation: literalShape(["add"], { description: "Insert one or more rows (fails on a duplicate key)." }),
1062
- id: stringShape({
1063
- min: 1,
1064
- description: "The database id."
1065
- }),
1066
- table: stringShape({
1067
- min: 1,
1068
- description: "The table name."
1069
- }),
1070
- row: rowsShape
1071
- }), objectShape({
1072
- operation: literalShape(["set"], { description: "Upsert one or more rows." }),
1073
- id: stringShape({
1074
- min: 1,
1075
- description: "The database id."
1076
- }),
1077
- table: stringShape({
1078
- min: 1,
1079
- description: "The table name."
1080
- }),
1081
- row: rowsShape
1082
- }), objectShape({
1083
- operation: literalShape(["update"], { description: "Patch one or more existing rows." }),
1084
- id: stringShape({
1085
- min: 1,
1086
- description: "The database id."
1087
- }),
1088
- table: stringShape({
1089
- min: 1,
1090
- description: "The table name."
1091
- }),
1092
- key: keyShape,
1093
- changes: rowShape
1094
- }), objectShape({
1095
- operation: literalShape(["remove"], { description: "Delete one or more rows by key." }),
1096
- id: stringShape({
1097
- min: 1,
1098
- description: "The database id."
1099
- }),
1100
- table: stringShape({
1101
- min: 1,
1102
- description: "The table name."
1103
- }),
1104
- key: keyShape
1105
- }), objectShape({
1106
- operation: literalShape(["migrate"], { description: "Replace the table layout in place." }),
1107
- id: stringShape({
1108
- min: 1,
1109
- description: "The database id."
1110
- }),
1111
- tables: tableSpecShape
1112
- }), objectShape({
1113
- operation: literalShape(["destroy"], { description: "Drop a database entirely." }),
1114
- id: stringShape({
1115
- min: 1,
1116
- description: "The database id."
1117
- })
1118
- }));
1119
- /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
1120
- var relationKeyShape = unionShape(arrayShape(unionShape(stringShape(), numberShape()), { description: "Multiple row keys, positional — a miss at an index is undefined there." }), stringShape({ description: "One row key." }), numberShape({ description: "One row key." }));
1121
- /** A single row key (not an array) — used by `'link'` / `'unlink'` / `'links'`, which address exactly one owning row. */
1122
- var singleKeyShape = unionShape(stringShape({ description: "The owning row key." }), numberShape({ description: "The owning row key." }));
1123
- /** Flat dot-path relation include list, expanded via {@link import('./helpers.js').expandInclude}. */
1124
- var includeShape = optionalShape(arrayShape(stringShape({ description: "A dot-separated chain of relation names, e.g. \"contacts.account\"." }), { description: "Which relations to attach, as flat dot-paths." }));
1125
- /** Which registered relation manager to address — omitted resolves to the sole registered manager. */
1126
- var managerShape = optionalShape(stringShape({
1127
- min: 1,
1128
- description: "Which registered relation manager to address."
1129
- }));
1130
- /**
1131
- * The shape of {@link import('./factories.js').createRelationTool}'s call arguments —
1132
- * discriminated by `operation` into the 5 relation operations (`'load'` / `'find'` / `'link'` /
1133
- * `'unlink'` / `'links'`).
1134
- *
1135
- * @remarks
1136
- * `'load'` fetches one or more rows (positional key/array) with `include` attached. `'find'`
1137
- * fetches rows (pagination / sort only) with `include` attached. `'link'` / `'unlink'` write /
1138
- * remove a `through` junction row; `'links'` lists a `through` relation's linked keys.
1139
- */
1140
- var relationToolShape = unionShape(objectShape({
1141
- operation: literalShape(["load"], { description: "Fetch one or more rows by key, with related rows attached." }),
1142
- manager: managerShape,
1143
- model: stringShape({
1144
- min: 1,
1145
- description: "The model (table) name."
1146
- }),
1147
- key: relationKeyShape,
1148
- include: includeShape
1149
- }), objectShape({
1150
- operation: literalShape(["find"], { description: "List rows, with related rows attached." }),
1151
- manager: managerShape,
1152
- model: stringShape({
1153
- min: 1,
1154
- description: "The model (table) name."
1155
- }),
1156
- include: includeShape,
1157
- limit: optionalShape(integerShape({
1158
- min: 0,
1159
- description: "Max rows to return."
1160
- })),
1161
- offset: optionalShape(integerShape({
1162
- min: 0,
1163
- description: "Rows to skip before returning."
1164
- })),
1165
- sort: optionalShape(stringShape({
1166
- min: 1,
1167
- description: "The column to sort by."
1168
- })),
1169
- direction: optionalShape(literalShape(["ascending", "descending"], { description: "The sort direction." }))
1170
- }), objectShape({
1171
- operation: literalShape(["link"], { description: "Connect two rows through a \"through\" relation." }),
1172
- manager: managerShape,
1173
- model: stringShape({
1174
- min: 1,
1175
- description: "The model (table) name."
1176
- }),
1177
- key: singleKeyShape,
1178
- relation: stringShape({
1179
- min: 1,
1180
- description: "The \"through\" relation name."
1181
- }),
1182
- target: singleKeyShape
1183
- }), objectShape({
1184
- operation: literalShape(["unlink"], { description: "Disconnect two rows previously linked through a \"through\" relation." }),
1185
- manager: managerShape,
1186
- model: stringShape({
1187
- min: 1,
1188
- description: "The model (table) name."
1189
- }),
1190
- key: singleKeyShape,
1191
- relation: stringShape({
1192
- min: 1,
1193
- description: "The \"through\" relation name."
1194
- }),
1195
- target: singleKeyShape
1196
- }), objectShape({
1197
- operation: literalShape(["links"], { description: "List every key linked to a row through a \"through\" relation." }),
1198
- manager: managerShape,
1199
- model: stringShape({
1200
- min: 1,
1201
- description: "The model (table) name."
1202
- }),
1203
- key: singleKeyShape,
1204
- relation: stringShape({
1205
- min: 1,
1206
- description: "The \"through\" relation name."
1207
- })
1208
- }));
1209
- /**
1210
- * The shape of {@link import('./factories.js').createInferTool}'s call arguments — one or more
1211
- * example `samples` to infer a JSON Schema from, plus per-call `format` / `enum` toggles and an
1212
- * optional `candidates` array to check against the inferred schema.
1213
- *
1214
- * @remarks
1215
- * `samples` requires at least one element (`min: 1`) — an empty array parses to `undefined`,
1216
- * surfaced by the handler as a typed `TOOL` {@link import('./errors.js').AgentToolError}. When
1217
- * `candidates` is present (any array, including empty), the handler compiles a contract from the
1218
- * freshly inferred schema and checks each candidate against it with a STRICT guard (`.is`, no
1219
- * coercion) — the opposite of {@link import('./factories.js').createEndpointTool}'s NORMALIZING
1220
- * `.parse` enforcement.
1221
- */
1222
- var inferToolShape = objectShape({
1223
- samples: arrayShape(jsonShape(), {
1224
- min: 1,
1225
- description: "The example values to infer a JSON Schema from (at least one)."
1226
- }),
1227
- format: optionalShape(booleanShape({ description: "Infer string formats (date-time, email, ...) from the samples. Defaults to false." })),
1228
- enum: optionalShape(booleanShape({ description: "Infer enum constraints from repeated literal values. Defaults to false." })),
1229
- candidates: optionalShape(arrayShape(jsonShape(), { description: "Optional values to check against the freshly inferred schema. When present, the tool returns a per-candidate verdict (strict — no coercion) alongside the inferred parameters." }))
1230
- });
1231
- //#endregion
1
+ import { attempt, holds, isArray, isRecord, isString } from "@orkestrel/contract";
1232
2
  //#region src/core/helpers.ts
1233
3
  /**
1234
- * The ancestry identifier of a workflow in a run chain — `workflow:<id>`.
1235
- *
1236
- * @remarks
1237
- * Namespacing keeps a workflow id and an {@link agentTag} agent name in ONE set without
1238
- * collision, so re-entering a workflow OR an agent already in the chain is a single `includes`
1239
- * check.
1240
- *
1241
- * @param id - The workflow definition's `id`
1242
- * @returns The namespaced ancestry tag (`workflow:<id>`)
1243
- */
1244
- function workflowTag(id) {
1245
- return `workflow:${id}`;
1246
- }
1247
- /**
1248
- * The ancestry identifier of an agent in a run chain — `agent:<name>`.
1249
- *
1250
- * @remarks
1251
- * The agent counterpart of {@link workflowTag}: {@link import('./factories.js').createAgentFunction}
1252
- * / {@link import('./factories.js').createWorkflowTool} guard against re-entering an agent or
1253
- * workflow already in the chain (a typed `DEPTH` `WorkflowError`, `@orkestrel/workflow`). The
1254
- * `agent:` namespace keeps it distinct from a same-string workflow id.
1255
- *
1256
- * @param name - The agent's identifier / registry name
1257
- * @returns The namespaced ancestry tag (`agent:<name>`)
1258
- */
1259
- function agentTag(name) {
1260
- return `agent:${name}`;
1261
- }
1262
- /**
1263
- * Build the plain success summary {@link import('./factories.js').createWorkflowTool} returns on
1264
- * a completed run — the universal tool-handler contract (AGENTS §14): return a plain value on
1265
- * success, appearing identically over BOTH the agent loop and MCP.
1266
- *
1267
- * @remarks
1268
- * The summary is LEAN: the workflow's terminal `status` and the COUNT of settled task results —
1269
- * enough for a caller / model to react without serializing the whole live tree. (It carries no
1270
- * synthetic `id` / `name`: a tool handler has no call id; the `ToolManagerInterface`
1271
- * (`@orkestrel/agent`) supplies the canonical envelope's identity.)
1272
- *
1273
- * @param result - The terminal `WorkflowResult` (`@orkestrel/workflow`) the run produced
1274
- * @returns The plain success summary — `{ status, count }`
1275
- */
1276
- function workflowToolSummary(result) {
1277
- return {
1278
- status: result.status,
1279
- count: result.results.length
1280
- };
1281
- }
1282
- /**
1283
- * Complete a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesize any
1284
- * MISSING `id` deterministically + positionally, and default any MISSING `name` to its
1285
- * (now-resolved) `id`.
1286
- *
1287
- * @remarks
1288
- * The positional id scheme is stable and human-legible: the workflow is `wf`, phase `i` is
1289
- * `phase-<i>`, and task `j` of that phase is `<phaseId>-task-<j>` (so a provided phase id flows
1290
- * into its tasks' synthesized ids). A PROVIDED `id` / `name` at any level is kept VERBATIM —
1291
- * synthesis touches only the omitted ones. A missing `name` defaults to the resolved `id` (never
1292
- * the other way round), so the result always has both. `run`, `description`, the per-phase
1293
- * `concurrency` / `bail`, the per-task `retries` / `timeout`, and the workflow `bail` carry over
1294
- * unchanged. The result is a complete {@link WorkflowDefinition}; the caller still validates it
1295
- * against the STRICT contract.
1296
- *
1297
- * @param draft - The draft workflow (id/name optional at all three levels)
1298
- * @returns A complete {@link WorkflowDefinition} with every id/name filled
1299
- */
1300
- function completeDraft(draft) {
1301
- const id = draft.id ?? "wf";
1302
- return {
1303
- id,
1304
- name: draft.name ?? id,
1305
- ...draft.description === void 0 ? {} : { description: draft.description },
1306
- phases: draft.phases.map((phase, index) => completePhaseDraft(phase, index)),
1307
- ...draft.bail === void 0 ? {} : { bail: draft.bail }
1308
- };
1309
- }
1310
- /**
1311
- * Complete one {@link PhaseDraft} into a strict phase definition — the per-phase step of
1312
- * {@link completeDraft} (phase `index` → `phase-<index>` when its id is omitted).
1313
- *
1314
- * @param phase - The draft phase
1315
- * @param index - The phase's positional index in the workflow
1316
- * @returns A complete phase definition
1317
- */
1318
- function completePhaseDraft(phase, index) {
1319
- const id = phase.id ?? `phase-${index}`;
1320
- return {
1321
- id,
1322
- name: phase.name ?? id,
1323
- ...phase.description === void 0 ? {} : { description: phase.description },
1324
- tasks: phase.tasks.map((task, taskIndex) => completeTaskDraft(task, id, taskIndex)),
1325
- ...phase.concurrency === void 0 ? {} : { concurrency: phase.concurrency },
1326
- ...phase.bail === void 0 ? {} : { bail: phase.bail }
1327
- };
1328
- }
1329
- /**
1330
- * Complete one {@link TaskDraft} into a strict task definition — the per-task leaf step of
1331
- * {@link completeDraft} (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id
1332
- * is omitted).
1333
- *
1334
- * @param task - The draft task
1335
- * @param phaseId - The (resolved) parent phase id, so the synthesized task id nests under it
1336
- * @param index - The task's positional index within its phase
1337
- * @returns A complete task definition
1338
- */
1339
- function completeTaskDraft(task, phaseId, index) {
1340
- const id = task.id ?? `${phaseId}-task-${index}`;
1341
- return {
1342
- id,
1343
- name: task.name ?? id,
1344
- ...task.description === void 0 ? {} : { description: task.description },
1345
- ...task.run === void 0 ? {} : { run: task.run },
1346
- ...task.retries === void 0 ? {} : { retries: task.retries },
1347
- ...task.timeout === void 0 ? {} : { timeout: task.timeout }
1348
- };
1349
- }
1350
- /**
1351
- * Expand a flat {@link WorkflowSteps} blob into a strict {@link WorkflowDefinition} — each step
1352
- * becomes a one-task phase, IN ORDER.
1353
- *
1354
- * @remarks
1355
- * The expansion of the tool's ADVERTISED surface: the deliberately-reduced flat form. Each
1356
- * {@link import('./types.js').WorkflowStep} maps to a phase holding exactly one task: the step's
1357
- * `name` becomes the task's `run` (the behavior-registry key). Ids/names are auto-filled
1358
- * positionally — it builds an ids-omitted {@link WorkflowDraft} and delegates to
1359
- * {@link completeDraft}, so the two lenient surfaces share ONE synthesis path (step `i` → phase
1360
- * `phase-<i>`, its task `phase-<i>-task-0`). The optional `name` becomes the workflow's `name`.
1361
- * The result is a complete definition the caller validates against the STRICT contract before
1362
- * running.
1363
- *
1364
- * @param flat - The flat steps blob (`{ name?, steps: [{ name }] }`)
1365
- * @returns A complete {@link WorkflowDefinition} (one one-task phase per step)
1366
- */
1367
- function expandSteps(flat) {
1368
- return completeDraft({
1369
- ...flat.name === void 0 ? {} : { name: flat.name },
1370
- phases: flat.steps.map((step) => ({ tasks: [{ run: step.name }] }))
1371
- });
1372
- }
1373
- /**
1374
- * Normalize an LLM-supplied answer `value` to the type {@link PromptType} `form` expects, so a
1375
- * caller that only ever emits strings can still answer a typed prompt.
1376
- *
1377
- * @remarks
1378
- * `'confirm'` coerces to a `boolean` — a `boolean` passes through, and the strings `'true'` /
1379
- * `'false'` (case-insensitively) map to it; any other string is truthy-coerced via
1380
- * `Boolean(value)`. `'checkbox'` coerces to `readonly string[]` — an array passes through
1381
- * (stringifying each entry), a comma-separated string splits + trims into one, and any other
1382
- * single (non-comma) string becomes a one-item array. Every other form (`'input'` / `'password'`
1383
- * / `'select'` / `'editor'`) coerces to a plain `string` — a string passes through verbatim; a
1384
- * non-string, non-object scalar (`number` / `boolean`) stringifies via `String(value)`; an
1385
- * object or array (no lossless string form) falls back to `''` rather than serializing garbage.
1386
- * Pure and total — never throws.
1387
- *
1388
- * @param form - The {@link PromptType} the answer is being coerced FOR
1389
- * @param value - The raw, LLM-supplied answer value
1390
- * @returns The coerced answer — `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`,
1391
- * `string` otherwise
1392
- */
1393
- function coerceAnswer(form, value) {
1394
- if (form === "confirm") {
1395
- if (typeof value === "boolean") return value;
1396
- if (typeof value === "string") {
1397
- const lower = value.trim().toLowerCase();
1398
- if (lower === "true") return true;
1399
- if (lower === "false") return false;
1400
- }
1401
- return Boolean(value);
1402
- }
1403
- if (form === "checkbox") {
1404
- if (Array.isArray(value)) return value.map((entry) => String(entry));
1405
- if (typeof value === "string") {
1406
- if (value.includes(",")) return value.split(",").map((entry) => entry.trim());
1407
- return [value];
1408
- }
1409
- return [String(value)];
1410
- }
1411
- if (typeof value === "string") return value;
1412
- if (typeof value === "object" && value !== null) return "";
1413
- return String(value);
1414
- }
1415
- /**
1416
- * Map a caught error to the {@link AgentToolErrorCode} the terminal-tool factory should throw
1417
- * with — the pure classification step of that factory's error handling.
1418
- *
1419
- * @remarks
1420
- * Narrows `error` with {@link isTerminalError} (`@orkestrel/terminal`) first: a non-`TerminalError`
1421
- * value returns `undefined`, telling the caller this mapper does not apply (rethrow / handle
1422
- * otherwise). For a genuine `TerminalError`, `'DEADLOCK'` maps to `'DEADLOCK'`, `'EXPIRE'` maps
1423
- * to `'EXPIRE'`, and every other {@link import('@orkestrel/terminal').TerminalErrorCode}
1424
- * (`'TARGET'`, `'CANCEL'`, `'DRIVER'`) maps to the generic `'TOOL'` code. The mapper only
1425
- * classifies — the factory performs the actual throw.
1426
- *
1427
- * @param error - The value caught from a terminal-manager operation (`ask` / `answer` / …)
1428
- * @returns The mapped {@link AgentToolErrorCode}, or `undefined` if `error` is not a `TerminalError`
1429
- */
1430
- function terminalToolCode(error) {
1431
- if (!isTerminalError(error)) return void 0;
1432
- if (error.code === "DEADLOCK") return "DEADLOCK";
1433
- if (error.code === "EXPIRE") return "EXPIRE";
1434
- return "TOOL";
1435
- }
1436
- /** Narrow an unknown value to a {@link ColumnSpec} — a valid {@link import('./types.js').ColumnKind} shorthand, or `{ type, optional }` with a valid `type`. */
1437
- function isColumnSpec(value) {
1438
- if (isColumnKind(value)) return true;
1439
- if (!isRecord(value)) return false;
1440
- return isColumnKind(value.type) && (value.optional === void 0 || typeof value.optional === "boolean");
1441
- }
1442
- /** Narrow an unknown value to a {@link import('./types.js').ColumnKind}. */
1443
- function isColumnKind(value) {
1444
- return value === "string" || value === "integer" || value === "number" || value === "boolean";
1445
- }
1446
- /**
1447
- * Compile a {@link TableSpec} into the `@orkestrel/database` {@link TablesShape} it configures —
1448
- * each {@link ColumnSpec} maps to the matching primitive shaper (`'string'` → `stringShape()`,
1449
- * `'integer'` → `integerShape()`, `'number'` → `numberShape()`, `'boolean'` → `booleanShape()`),
1450
- * wrapped in `optionalShape` when the column declares `optional: true`. Total, pure.
1451
- *
1452
- * @param spec - The small-model-facing table layout
1453
- * @returns The compiled `TablesShape` a `@orkestrel/database` `createDatabase` call accepts
1454
- */
1455
- function expandTables(spec) {
1456
- const tables = {};
1457
- for (const [table, definition] of Object.entries(spec)) {
1458
- const columns = {};
1459
- for (const [column, kind] of Object.entries(definition.columns)) columns[column] = columnShape(kind);
1460
- tables[table] = columns;
1461
- }
1462
- return tables;
1463
- }
1464
- /** Compile one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf {@link expandTables} maps over. */
1465
- function columnShape(spec) {
1466
- const kind = isString(spec) ? spec : spec.type;
1467
- const optional = !isString(spec) && spec.optional === true;
1468
- const shape = kindShape(kind);
1469
- return optional ? optionalShape(shape) : shape;
1470
- }
1471
- /** Map one {@link import('./types.js').ColumnKind} to its primitive `@orkestrel/database` shape — the leaf {@link columnShape} wraps. */
1472
- function kindShape(kind) {
1473
- if (kind === "string") return stringShape();
1474
- if (kind === "integer") return integerShape();
1475
- if (kind === "number") return numberShape();
1476
- return booleanShape();
1477
- }
1478
- /**
1479
- * Narrow an unknown value to a {@link DatabaseDefinition} — a non-empty `id` + `driver`, a
1480
- * `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, and an optional
1481
- * `keys` record of strings. The boundary guard a {@link import('./types.js').DefinitionStoreInterface}
1482
- * applies to an untrusted persisted blob before trusting it as a definition (never an `as`).
1483
- */
1484
- function isDatabaseDefinition(value) {
1485
- if (!isRecord(value)) return false;
1486
- if (!isNonEmptyString(value.id) || !isNonEmptyString(value.driver)) return false;
1487
- if (!isRecord(value.tables)) return false;
1488
- for (const table of Object.values(value.tables)) {
1489
- if (!isRecord(table) || !isRecord(table.columns)) return false;
1490
- for (const column of Object.values(table.columns)) if (!isColumnSpec(column)) return false;
1491
- }
1492
- if (value.keys !== void 0) {
1493
- if (!isRecord(value.keys)) return false;
1494
- for (const key of Object.values(value.keys)) if (!isString(key)) return false;
1495
- }
1496
- return true;
1497
- }
1498
- /**
1499
- * Map a caught error to the {@link AgentToolErrorCode} the upcoming database tool should throw
1500
- * with — the pure classification step of that factory's error handling, mirroring
1501
- * {@link terminalToolCode}'s idiom for `@orkestrel/database`.
1502
- *
1503
- * @param error - The value caught from a `@orkestrel/database` table operation
1504
- * @returns The granular {@link DatabaseErrorCode}, or `undefined` if `error` is not a `DatabaseError`
1505
- */
1506
- function databaseToolCode(error) {
1507
- return isDatabaseError(error) ? error.code : void 0;
1508
- }
1509
- /**
1510
- * Map a caught error to the {@link AgentToolErrorCode} the upcoming relation tool should throw
1511
- * with — the pure classification step of that factory's error handling, mirroring
1512
- * {@link terminalToolCode}'s idiom for `@orkestrel/relation`.
1513
- *
1514
- * @param error - The value caught from a `@orkestrel/relation` operation
1515
- * @returns The granular {@link RelationErrorCode}, or `undefined` if `error` is not a `RelationError`
1516
- */
1517
- function relationToolCode(error) {
1518
- return isRelationError(error) ? error.code : void 0;
1519
- }
1520
- /**
1521
- * Expand the relation tool's FLAT dot-path `include` list into a live `@orkestrel/relation`
1522
- * {@link Include} tree — the pure leaf {@link import('./factories.js').createRelationTool} calls
1523
- * before a `'load'` / `'find'` call.
4
+ * Determine whether an unknown value is structurally a {@link ToolCall}.
1524
5
  *
1525
6
  * @remarks
1526
- * Each path splits on `'.'` into a chain of relation names, deep-merged into one nested
1527
- * `Include` object with a leaf `true`. A longer path SUBSUMES a shorter sibling's bare `true` —
1528
- * `'contacts'` followed by `'contacts.account'` yields `{ contacts: { account: true } }`, never
1529
- * overwriting the deeper chain. An EMPTY segment (`''`, from a leading/trailing/doubled `.`) or a
1530
- * path whose segment count exceeds `depth` throws a typed `TOOL` {@link AgentToolError}.
7
+ * This total guard accepts a plain record with string `id` and `name` fields and a
8
+ * plain-record `arguments` field. Adversarial values return `false`.
1531
9
  *
1532
- * @param paths - The flat dot-path `include` list (or `undefined` — yields `{}`)
1533
- * @param depth - The max segment count a single path may reach
1534
- * @returns The equivalent nested {@link Include}
10
+ * @param value - The value to test
11
+ * @returns `true` when the value has the complete tool-call shape
1535
12
  *
1536
13
  * @example
1537
14
  * ```ts
1538
- * import { expandInclude } from '@src/core'
15
+ * import { isToolCall } from '@orkestrel/tool'
1539
16
  *
1540
- * expandInclude(['contacts', 'contacts.account'], 3)
1541
- * // { contacts: { account: true } }
17
+ * isToolCall({ id: '1', name: 'search', arguments: { query: 'birds' } }) // true
18
+ * isToolCall({ id: '1', name: 'search', arguments: [] }) // false
1542
19
  * ```
1543
20
  */
1544
- function expandInclude(paths, depth) {
1545
- let include = {};
1546
- for (const path of paths ?? []) {
1547
- const segments = path.split(".");
1548
- if (segments.length > depth || segments.some((segment) => segment.length === 0)) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1549
- path,
1550
- depth
1551
- });
1552
- const ancestors = [];
1553
- let branch = include;
1554
- const last = segments.length - 1;
1555
- for (let index = 0; index < last; index++) {
1556
- const segment = segments[index];
1557
- if (segment === void 0) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1558
- path,
1559
- depth
1560
- });
1561
- ancestors.push(branch);
1562
- const existing = branch[segment];
1563
- branch = typeof existing === "object" ? existing : {};
1564
- }
1565
- const leaf = segments[last];
1566
- if (leaf === void 0) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1567
- path,
1568
- depth
1569
- });
1570
- const existing = branch[leaf];
1571
- let merged = {
1572
- ...branch,
1573
- [leaf]: existing === void 0 ? true : existing
1574
- };
1575
- for (let index = last - 1; index >= 0; index--) {
1576
- const ancestor = ancestors[index];
1577
- const segment = segments[index];
1578
- if (ancestor === void 0 || segment === void 0) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1579
- path,
1580
- depth
1581
- });
1582
- merged = {
1583
- ...ancestor,
1584
- [segment]: merged
1585
- };
1586
- }
1587
- include = merged;
1588
- }
1589
- return include;
1590
- }
1591
- /**
1592
- * Resolve which registered {@link RelationManagerInterface} a relation-tool call addresses — the
1593
- * pure manager-resolution leaf {@link import('./factories.js').createRelationTool} calls on
1594
- * every operation.
1595
- *
1596
- * @remarks
1597
- * An explicit `name` must match a key of `managers` (a miss throws a typed `TOOL`
1598
- * {@link AgentToolError} naming the registered managers). An OMITTED `name` resolves to the sole
1599
- * registered manager when exactly one is registered, else throws the same typed error.
1600
- *
1601
- * @param managers - The tool's registered `RelationManagerInterface` map
1602
- * @param name - The call's optional `manager` field
1603
- * @returns The resolved {@link RelationManagerInterface}
1604
- */
1605
- function relationManagerOf(managers, name) {
1606
- if (name !== void 0) {
1607
- const manager = managers[name];
1608
- if (manager === void 0) throw new AgentToolError("TOOL", `unknown relation manager '${name}'`, {
1609
- manager: name,
1610
- managers: Object.keys(managers)
1611
- });
1612
- return manager;
1613
- }
1614
- const names = Object.keys(managers);
1615
- const [single] = names;
1616
- if (names.length === 1 && single !== void 0) {
1617
- const manager = managers[single];
1618
- if (manager !== void 0) return manager;
1619
- }
1620
- throw new AgentToolError("TOOL", "no relation manager resolved for the call", { managers: names });
1621
- }
1622
- /**
1623
- * Resolve a `model` name against a live {@link RelationManagerInterface} — the pure model-lookup
1624
- * leaf {@link import('./factories.js').createRelationTool} calls on every operation, mirroring
1625
- * {@link relationManagerOf}'s guard shape.
1626
- *
1627
- * @param manager - The resolved {@link RelationManagerInterface}
1628
- * @param name - The call's `model` field
1629
- * @returns The model's {@link ModelInterface}
1630
- */
1631
- function relationModelOf(manager, name) {
1632
- if (!manager.has(name)) throw new AgentToolError("TOOL", `unknown model '${name}'`, {
1633
- model: name,
1634
- models: manager.models()
1635
- });
1636
- return manager.model(name);
1637
- }
1638
- /**
1639
- * Normalize the database tool's parsed SERIALIZED criteria into a live `@orkestrel/database`
1640
- * {@link Criteria} — default each condition's OMITTED `connector` to `'and'`.
1641
- *
1642
- * @remarks
1643
- * The wire form ({@link import('./shapers.js').databaseToolShape}) lets a caller drop `connector`
1644
- * on the last condition (it has nothing to join FORWARD to); the compiled `Condition` a live
1645
- * `@orkestrel/database` table call accepts always carries one, so this fills the gap. `order` /
1646
- * `limit` / `offset` pass through unchanged. Pure and total.
1647
- *
1648
- * @param criteria - The parsed criteria (or `undefined`)
1649
- * @returns The equivalent live `Criteria`, or `undefined` when `criteria` is `undefined`
1650
- */
1651
- function criteriaOf(criteria) {
1652
- if (criteria === void 0) return void 0;
1653
- const conditions = criteria.conditions?.map((condition) => ({
1654
- ...condition,
1655
- connector: condition.connector ?? "and"
1656
- }));
1657
- return {
1658
- ...conditions === void 0 ? {} : { conditions },
1659
- ...criteria.order === void 0 ? {} : { order: criteria.order },
1660
- ...criteria.limit === void 0 ? {} : { limit: criteria.limit },
1661
- ...criteria.offset === void 0 ? {} : { offset: criteria.offset }
1662
- };
1663
- }
1664
- /**
1665
- * Clamp a `'records'` call's criteria to a row cap, and build the PROBE criteria the caller reads
1666
- * with — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation
1667
- * uses to detect truncation without a separate `count` round trip.
1668
- *
1669
- * @remarks
1670
- * The effective limit is `min(criteria?.limit ?? cap, cap)`, floored at `0` (so a caller can never
1671
- * exceed the configured cap by supplying a larger `criteria.limit`). The returned probe criteria
1672
- * requests ONE MORE row than the effective limit (`limit: effective + 1`) — if storage returns
1673
- * that many, the caller knows the true result was truncated (`rows.length > effective`) and slices
1674
- * back down to `effective` before returning.
1675
- *
1676
- * @example
1677
- * ```ts
1678
- * import { clampCriteria } from '@src/core'
1679
- *
1680
- * const { criteria, limit } = clampCriteria(undefined, 100)
1681
- * // limit === 100, criteria.limit === 101 — a probe fetching one extra row
1682
- * const rows = await table.records(criteria)
1683
- * const truncated = rows.length > limit // true when storage had more than `limit` rows
1684
- * ```
1685
- *
1686
- * @param criteria - The live criteria to clamp (or `undefined`)
1687
- * @param cap - The row-count ceiling
1688
- * @returns The PROBE criteria (`limit` bumped by one) and the effective `limit`
1689
- */
1690
- function clampCriteria(criteria, cap) {
1691
- const limit = Math.max(0, Math.min(criteria?.limit ?? cap, cap));
1692
- return {
1693
- criteria: {
1694
- ...criteria,
1695
- limit: limit + 1
1696
- },
1697
- limit
1698
- };
1699
- }
1700
- /** Map a column NAME + its live `@orkestrel/database` `ContractShape` to a {@link ColumnSchema} — the leaf {@link tableSchema} maps over. */
1701
- function columnSchema(name, shape) {
1702
- return {
1703
- name,
1704
- type: shapeToColumnType(shape),
1705
- nullable: shape.type === "optional" || shape.type === "nullable"
1706
- };
1707
- }
1708
- /**
1709
- * Build one {@link TableSchema} from a table NAME and its `@orkestrel/database` `TableExport` —
1710
- * the "deployed" schema shape `DatabaseInterface.migrate` diffs against, derived from a LIVE
1711
- * handle's `export()` rather than a re-declared {@link TableSpec}, so it works for ANY handle
1712
- * (config-tracked or caller-supplied).
1713
- *
1714
- * @param name - The table name
1715
- * @param table - The table's `TableExport` (`{ key, columns }`, `@orkestrel/database`)
1716
- * @returns The equivalent {@link TableSchema} (`indexes` empty — this package declares none)
1717
- */
1718
- function tableSchema(name, table) {
1719
- return {
1720
- name,
1721
- primary: table.key,
1722
- columns: Object.entries(table.columns).map(([column, shape]) => columnSchema(column, shape)),
1723
- indexes: []
1724
- };
21
+ function isToolCall(value) {
22
+ return holds(() => isRecord(value) && isString(value.id) && isString(value.name) && isRecord(value.arguments));
1725
23
  }
1726
24
  //#endregion
1727
- //#region src/core/stores/MemoryDefinitionStore.ts
25
+ //#region src/core/tools/Tool.ts
1728
26
  /**
1729
- * The in-memory {@link DefinitionStoreInterface} a process-lifetime `Map` of
1730
- * {@link DatabaseDefinition}s keyed by database id, the DEFAULT store
1731
- * {@link import('../factories.js').createMemoryDefinitionStore} builds. The EXACT twin of
1732
- * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}.
27
+ * An executable tool definition bound to a handler.
1733
28
  *
1734
29
  * @remarks
1735
- * A plain `Map<string, DatabaseDefinition>` (AGENTS §21 the definition is already pure,
1736
- * self-contained CONFIG-only JSON, so no encoding is needed for the memory tier). There is NO
1737
- * idle-TTL and NO eviction: a persisted definition lives until an explicit `delete`. A durable
1738
- * backend (JSON / SQLite / IndexedDB) swaps in through the SAME interface without touching a
1739
- * consumer — its driver-pluggable twin is
1740
- * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore} (the definition as one
1741
- * opaque JSON column).
1742
- *
1743
- * - **`get` resolves the persisted definition for an id**, or `undefined` if none is stored.
1744
- * - **`set` inserts / replaces under the definition's OWN `id`** (no separate id param).
1745
- * - **`delete` drops a definition by id**; an absent id is a no-op (no throw).
1746
- *
1747
- * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1748
- * bijection with {@link DefinitionStoreInterface}).
30
+ * Schema fields and arguments are forwarded by reference. Handler failures are not
31
+ * caught here; {@link ToolManager} owns per-call error isolation.
1749
32
  *
1750
33
  * @example
1751
34
  * ```ts
1752
- * import { createMemoryDefinitionStore } from '@src/core'
35
+ * import { Tool } from '@orkestrel/tool'
1753
36
  *
1754
- * const store = createMemoryDefinitionStore()
1755
- * await store.set({ id: 'shop', driver: 'memory', tables: {} })
1756
- * const definition = await store.get('shop')
1757
- * await store.delete('shop')
37
+ * const tool = new Tool({
38
+ * name: 'add',
39
+ * description: 'Add two numbers',
40
+ * parameters: {
41
+ * type: 'object',
42
+ * properties: { a: { type: 'number' }, b: { type: 'number' } },
43
+ * },
44
+ * execute: (args) => Number(args.a) + Number(args.b),
45
+ * })
1758
46
  * ```
1759
47
  */
1760
- var MemoryDefinitionStore = class {
1761
- #definitions = /* @__PURE__ */ new Map();
1762
- get(id) {
1763
- return Promise.resolve(this.#definitions.get(id));
1764
- }
1765
- set(definition) {
1766
- this.#definitions.set(definition.id, definition);
1767
- return Promise.resolve();
48
+ var Tool = class {
49
+ name;
50
+ description;
51
+ summary;
52
+ parameters;
53
+ #execute;
54
+ constructor(options) {
55
+ this.name = options.name;
56
+ if (options.description !== void 0) this.description = options.description;
57
+ if (options.summary !== void 0) this.summary = options.summary;
58
+ if (options.parameters !== void 0) this.parameters = options.parameters;
59
+ this.#execute = options.execute;
1768
60
  }
1769
- delete(id) {
1770
- this.#definitions.delete(id);
1771
- return Promise.resolve();
61
+ execute(args) {
62
+ return this.#execute(args);
1772
63
  }
1773
64
  };
1774
65
  //#endregion
1775
- //#region src/core/stores/DatabaseDefinitionStore.ts
66
+ //#region src/core/tools/ToolManager.ts
1776
67
  /**
1777
- * A {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database` layer — a
1778
- * database's durable CONFIG state IS a row, so persistence reduces to keyed point-access
1779
- * (`get` / `set` / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the
1780
- * plain-`Map` {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}.
68
+ * An insertion-ordered tool registry with per-call error isolation.
1781
69
  *
1782
70
  * @remarks
1783
- * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
1784
- * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /
1785
- * IndexedDB backend swaps in WITHOUT touching a consumer the same seam as
1786
- * {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}. The driver defaults to
1787
- * memory ({@link import('../factories.js').createDatabaseDefinitionStore} passes
1788
- * `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the durable
1789
- * plumbing by passing a JSON / SQLite / IndexedDB driver.
1790
- *
1791
- * The {@link DatabaseDefinition} is stored as ONE OPAQUE JSON COLUMN — the table is a row of
1792
- * `{ id; definition }` ({@link DatabaseDefinitionRow}). The definition is already a COMPLETE,
1793
- * self-contained, pure-JSON CONFIG payload (never a live handle), so storing it whole is lossless
1794
- * AND keeps the row type flat (`definition` reads back as `unknown`).
1795
- *
1796
- * - **`set(definition)` upserts under the definition's OWN `id`** (no separate id param) — it
1797
- * writes the row `{ id: definition.id, definition }`.
1798
- * - **`get(id)` resolves the stored definition for an id**, narrowing the opaque JSON column back
1799
- * to a {@link DatabaseDefinition} ({@link import('../helpers.js').isDatabaseDefinition} — the
1800
- * AGENTS §14 boundary narrow for an untrusted storage read), or `undefined` if none is stored
1801
- * or the stored blob is malformed.
1802
- * - **`delete(id)` drops a definition by id**; an absent id is a no-op (no throw).
1803
- *
1804
- * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1805
- * bijection with {@link DefinitionStoreInterface}).
71
+ * A repeated name overwrites the registered tool without changing its insertion
72
+ * position. Definitions advertise `summary` in place of `description` when present.
73
+ * Unknown names and handler throws resolve to error results; batch execution preserves
74
+ * input order and never fails as a whole because of an individual call.
1806
75
  *
1807
76
  * @example
1808
77
  * ```ts
1809
- * import { createDatabaseDefinitionStore, createMemoryDriver } from '@src/core'
78
+ * import { Tool, ToolManager } from '@orkestrel/tool'
1810
79
  *
1811
- * const store = createDatabaseDefinitionStore(createMemoryDriver()) // a durable driver swaps in here
1812
- * await store.set({ id: 'shop', driver: 'memory', tables: {} }) // persist the config (one JSON column)
1813
- * const definition = await store.get('shop')
1814
- * await store.delete('shop')
80
+ * const tools = new ToolManager()
81
+ * tools.add(new Tool({ name: 'add', execute: (args) => Number(args.x) + Number(args.y) }))
82
+ * const result = await tools.execute({
83
+ * id: '1',
84
+ * name: 'add',
85
+ * arguments: { x: 1, y: 2 },
86
+ * })
1815
87
  * ```
1816
88
  */
1817
- var DatabaseDefinitionStore = class {
1818
- #table;
1819
- /**
1820
- * Wrap a table as a definition store.
1821
- *
1822
- * @param table - The {@link TableInterface} holding the definitions — its row is the
1823
- * {@link DatabaseDefinitionRow} `{ id; definition }` shape (the definition one opaque JSON column)
1824
- */
1825
- constructor(table) {
1826
- this.#table = table;
89
+ var ToolManager = class {
90
+ #tools = /* @__PURE__ */ new Map();
91
+ get count() {
92
+ return this.#tools.size;
1827
93
  }
1828
- /** Resolve the persisted definition for `id`, narrowing the opaque JSON column back to a `DatabaseDefinition`. */
1829
- async get(id) {
1830
- const row = await this.#table.get(id);
1831
- if (row === void 0) return void 0;
1832
- return isDatabaseDefinition(row.definition) ? row.definition : void 0;
1833
- }
1834
- /** Insert or replace under the definition's OWN `id` (no separate id param) — the row is `{ id, definition }`. */
1835
- async set(definition) {
1836
- await this.#table.set({
1837
- id: definition.id,
1838
- definition
1839
- });
94
+ add(tools) {
95
+ if (isArray(tools)) {
96
+ for (const tool of tools) this.#tools.set(tool.name, tool);
97
+ return;
98
+ }
99
+ this.#tools.set(tools.name, tools);
1840
100
  }
1841
- /** Drop a definition by id; an absent id is a no-op (no throw). */
1842
- async delete(id) {
1843
- await this.#table.remove(id);
101
+ tool(name) {
102
+ return this.#tools.get(name);
1844
103
  }
1845
- };
1846
- //#endregion
1847
- //#region src/core/databases/DatabaseResolver.ts
1848
- /**
1849
- * Resolve database definitions into cached live handles for database tools.
1850
- *
1851
- * @example
1852
- * ```ts
1853
- * import { DatabaseResolver } from '@orkestrel/tool'
1854
- *
1855
- * const resolver = new DatabaseResolver(handles, drivers, key, store)
1856
- * const database = await resolver.resolve('shop')
1857
- * ```
1858
- */
1859
- var DatabaseResolver = class {
1860
- #handles;
1861
- #drivers;
1862
- #key;
1863
- #store;
1864
- /**
1865
- * Create a database resolver over the tool's live state and optional definition store.
1866
- *
1867
- * @param handles - Initial live database handles cached by id
1868
- * @param drivers - Driver factories keyed by definition driver name
1869
- * @param key - Key generator supplied to newly created databases
1870
- * @param store - Optional persistent definition store
1871
- */
1872
- constructor(handles, drivers, key, store) {
1873
- this.#handles = new Map(handles);
1874
- this.#drivers = drivers;
1875
- this.#key = key;
1876
- this.#store = store;
104
+ tools() {
105
+ return [...this.#tools.values()];
1877
106
  }
1878
- /**
1879
- * Determine whether a live database is cached by id.
1880
- *
1881
- * @param id - Database id
1882
- * @returns Whether a live handle is cached
1883
- */
1884
- has(id) {
1885
- return this.#handles.has(id);
107
+ definitions() {
108
+ return [...this.#tools.values()].map((tool) => this.#definition(tool));
1886
109
  }
1887
- /**
1888
- * Read a cached database without consulting the definition store.
1889
- *
1890
- * @param id - Database id
1891
- * @returns The cached live database, or `undefined`
1892
- */
1893
- get(id) {
1894
- return this.#handles.get(id);
110
+ execute(call) {
111
+ if (isArray(call)) return Promise.all(call.map((one) => this.#run(one)));
112
+ return this.#run(call);
1895
113
  }
1896
- /**
1897
- * Cache a live database by id.
1898
- *
1899
- * @param id - Database id
1900
- * @param database - Live database handle
1901
- * @returns Nothing
1902
- */
1903
- set(id, database) {
1904
- this.#handles.set(id, database);
114
+ remove(names) {
115
+ if (isArray(names)) {
116
+ let removed = false;
117
+ for (const name of names) if (this.#tools.delete(name)) removed = true;
118
+ return removed;
119
+ }
120
+ return this.#tools.delete(names);
1905
121
  }
1906
- /**
1907
- * Remove a cached live database by id.
1908
- *
1909
- * @param id - Database id
1910
- * @returns Nothing
1911
- */
1912
- delete(id) {
1913
- this.#handles.delete(id);
122
+ clear() {
123
+ this.#tools.clear();
1914
124
  }
1915
- /**
1916
- * Resolve a cached or stored database by id.
1917
- *
1918
- * @param id - Database definition id
1919
- * @returns The cached or newly constructed live database
1920
- */
1921
- async resolve(id) {
1922
- const cached = this.#handles.get(id);
1923
- if (cached !== void 0) return cached;
1924
- if (this.#store !== void 0) {
1925
- const definition = await this.#store.get(id);
1926
- if (definition !== void 0) {
1927
- const factory = this.#drivers[definition.driver];
1928
- if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${definition.driver}'`, {
1929
- id,
1930
- driver: definition.driver
1931
- });
1932
- const handle = createDatabase({
1933
- driver: factory(),
1934
- tables: expandTables(definition.tables),
1935
- ...definition.keys === void 0 ? {} : { keys: definition.keys },
1936
- key: this.#key
1937
- });
1938
- this.set(id, handle);
1939
- return handle;
1940
- }
125
+ async #run(call) {
126
+ const tool = this.#tools.get(call.name);
127
+ if (tool === void 0) return {
128
+ id: call.id,
129
+ name: call.name,
130
+ error: `tool not found: ${call.name}`
131
+ };
132
+ try {
133
+ const value = await tool.execute(call.arguments);
134
+ return {
135
+ id: call.id,
136
+ name: call.name,
137
+ value
138
+ };
139
+ } catch (error) {
140
+ const message = attempt(() => error instanceof Error ? String(error.message) : String(error));
141
+ return {
142
+ id: call.id,
143
+ name: call.name,
144
+ error: message.success ? message.value : "Unknown thrown value"
145
+ };
1941
146
  }
1942
- throw new AgentToolError("TOOL", `unknown database '${id}'`, { id });
147
+ }
148
+ #definition(tool) {
149
+ const definition = { name: tool.name };
150
+ const description = tool.summary ?? tool.description;
151
+ if (description !== void 0) definition.description = description;
152
+ if (tool.parameters !== void 0) definition.parameters = tool.parameters;
153
+ return definition;
1943
154
  }
1944
155
  };
1945
156
  //#endregion
1946
157
  //#region src/core/factories.ts
1947
158
  /**
1948
- * Wrap a registered tool as a {@link WorkflowFunction} (`@orkestrel/workflow`) — the OPT-IN
1949
- * adapter that lets a `function`-form task run a `@orkestrel/agent` tool BY NAME.
1950
- *
1951
- * @remarks
1952
- * OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's
1953
- * `WorkflowOptions.functions` registry like any other behavior
1954
- * (`{ publish: createToolFunction(tools, 'publish') }`); the pure workflow runner has no
1955
- * knowledge of tools itself. The returned function executes `name` against `tools` with the
1956
- * task's `controller.input` as the call arguments, id-correlated to the task's own id. A
1957
- * `ToolManagerInterface.execute` (`@orkestrel/agent`) NEVER throws (a handler throw is isolated
1958
- * into `result.error`), so a failing tool is surfaced here as a THROWN `Error` carrying the
1959
- * original message as `cause` — the leaf `fail`s, honouring `bail`. An UNREGISTERED tool name is
1960
- * a programmer error (an explicit binding to a name that doesn't exist) — unlike the engine's
1961
- * own silent auto-complete of an unresolved task handler, this THROWS a typed `TOOL`
1962
- * `WorkflowError` (`@orkestrel/workflow`).
1963
- *
1964
- * @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) the named tool is registered on
1965
- * @param name - The registered tool's name
1966
- * @returns A {@link WorkflowFunction} that runs the named tool
1967
- *
1968
- * @example
1969
- * ```ts
1970
- * import { createToolFunction } from '@src/core'
1971
- * import { createToolManager } from '@orkestrel/agent'
1972
- * import { createWorkflowRunner } from '@orkestrel/workflow'
1973
- *
1974
- * const tools = createToolManager()
1975
- * tools.add(myPublishTool)
1976
- * const runner = createWorkflowRunner()
1977
- * await runner.execute(definition, { functions: { publish: createToolFunction(tools, 'publish') } })
1978
- * ```
1979
- */
1980
- function createToolFunction(tools, name) {
1981
- return async (controller) => {
1982
- if (tools.tool(name) === void 0) throw new WorkflowError("TOOL", `tool '${name}' is not registered`, { tool: name });
1983
- const result = await tools.execute({
1984
- id: controller.task.id,
1985
- name,
1986
- arguments: controller.input
1987
- });
1988
- if (result.error !== void 0) throw new Error(result.error, { cause: result.error });
1989
- return result.value;
1990
- };
1991
- }
1992
- /**
1993
- * Wrap a live `AgentInterface` (`@orkestrel/agent`) as a {@link WorkflowFunction}
1994
- * (`@orkestrel/workflow`) — the OPT-IN adapter that runs the agent to a settled result, folding
1995
- * a nested workflow-authoring depth / cycle guard into its own closure.
1996
- *
1997
- * @remarks
1998
- * OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's
1999
- * `WorkflowOptions.functions` registry like any other behavior; the pure workflow runner has no
2000
- * knowledge of agents itself. Before running the agent, the depth/cycle guard REJECTS the call
2001
- * (a THROWN typed `DEPTH` `WorkflowError`, which the leaf `fail`s) when running it would push a
2002
- * nested chain past {@link import('./constants.js').MAX_WORKFLOW_DEPTH}, OR when this agent is
2003
- * already an ancestor (a cycle). When {@link import('./types.js').AgentFunctionOptions.runner}
2004
- * is supplied, the adapter BINDS a depth/cycle-aware {@link createWorkflowTool} onto the agent's
2005
- * `context.tools` (the propagation seam) — closed over `depth` and the extended ancestry (the
2006
- * tool itself computes `depth + 1` internally) — so the agent can author + run a NESTED workflow
2007
- * through it; the wrapped default is the CURRENT task's own workflow id (used only on a no-args
2008
- * tool call). The task's cancellation folds into the agent run: an already-aborted
2009
- * `controller.signal` cancels the agent up front; otherwise a one-shot listener fires
2010
- * `agent.abort(reason)` when the task cancels, removed in `finally`. `agent.generate()` resolves
2011
- * a partial `AgentResult` on a cancel (never rejects), returned as the task's completed value.
2012
- *
2013
- * A bound agent is effectively SINGLE-RUN: `context.tools.add` binds one `ToolInterface` under
2014
- * the fixed {@link import('./constants.js').WORKFLOW_TOOL_NAME}, and `agent.generate()` /
2015
- * `agent.abort()` are per-agent state. Two CONCURRENT tasks sharing the SAME `agent` instance
2016
- * race on that one tool binding (last-write-wins) and on generate/abort — give each concurrent
2017
- * task its OWN agent instance.
2018
- *
2019
- * @param agent - The live `AgentInterface` to run
2020
- * @param options - The nested-workflow binding + depth/cycle bookkeeping (see {@link import('./types.js').AgentFunctionOptions})
2021
- * @returns A {@link WorkflowFunction} that runs `agent` to its settled result
2022
- *
2023
- * @example
2024
- * ```ts
2025
- * import { createAgentFunction } from '@src/core'
2026
- * import { createWorkflowRunner } from '@orkestrel/workflow'
2027
- *
2028
- * const runner = createWorkflowRunner()
2029
- * const review = createAgentFunction(myAgent, { runner })
2030
- * await runner.execute(definition, { functions: { review } })
2031
- * ```
2032
- */
2033
- function createAgentFunction(agent, options) {
2034
- return async (controller) => {
2035
- const depth = options?.depth ?? 0;
2036
- const ancestry = options?.ancestry ?? [];
2037
- if (depth + 1 > 8) throw new WorkflowError("DEPTH", `agent '${agent.id}' exceeds max workflow depth`, {
2038
- agent: agent.id,
2039
- depth,
2040
- max: 8
2041
- });
2042
- const tag = agentTag(agent.id);
2043
- if (ancestry.includes(tag)) throw new WorkflowError("DEPTH", `agent '${agent.id}' is already an ancestor (cycle)`, {
2044
- agent: agent.id,
2045
- ancestry: [...ancestry]
2046
- });
2047
- const runner = options?.runner;
2048
- if (runner !== void 0) {
2049
- const workflowId = controller.task.phase.workflow.id;
2050
- const wrapped = {
2051
- id: workflowId,
2052
- name: workflowId,
2053
- phases: []
2054
- };
2055
- agent.context.tools.add(createWorkflowTool(wrapped, runner, {
2056
- depth,
2057
- ancestry: [...ancestry, tag]
2058
- }));
2059
- }
2060
- const signal = controller.signal;
2061
- const onAbort = { handleEvent() {
2062
- agent.abort(signal.reason);
2063
- } };
2064
- if (signal.aborted) agent.abort(signal.reason);
2065
- else signal.addEventListener("abort", onAbort, { once: true });
2066
- try {
2067
- return await agent.generate();
2068
- } finally {
2069
- signal.removeEventListener("abort", onAbort);
2070
- }
2071
- };
2072
- }
2073
- /**
2074
- * Compile the LENIENT workflow DRAFT contract — identical to `createWorkflowContract`
2075
- * (`@orkestrel/workflow`) EXCEPT `id` and `name` are OPTIONAL at all three levels (workflow /
2076
- * phase / task), so a small model can omit the six identity strings.
2077
- *
2078
- * @remarks
2079
- * The widened authoring surface {@link createWorkflowTool} parses an authored blob through
2080
- * before {@link import('./helpers.js').completeDraft} fills the missing ids/names. It does NOT
2081
- * relax the canonical contract — `createWorkflowContract` (`@orkestrel/workflow`) stays
2082
- * byte-for-byte unchanged and STRICT, and the completed draft is re-validated against THAT
2083
- * strict gate before running (soundness preserved). A PROVIDED `id` / `name` still carries
2084
- * `minLength: 1`, so an explicitly-empty `id: ''` is REJECTED (parses to `undefined`), never
2085
- * auto-filled — keeping "garbage" distinct from "omitted". `run` stays optional (a plain name
2086
- * string).
2087
- *
2088
- * @returns The compiled {@link import('./types.js').WorkflowDraft} contract
2089
- *
2090
- * @example
2091
- * ```ts
2092
- * import { createWorkflowDraftContract, completeDraft } from '@src/core'
2093
- *
2094
- * const draft = createWorkflowDraftContract()
2095
- * const parsed = draft.parse({ phases: [{ tasks: [{ run: 'compile' }] }] })
2096
- * const definition = parsed && completeDraft(parsed) // ids/names filled positionally
2097
- * draft.parse({ id: '', phases: [] }) // undefined — an explicit empty id is rejected
2098
- * ```
2099
- */
2100
- function createWorkflowDraftContract() {
2101
- return createContract(workflowDraftShape);
2102
- }
2103
- /**
2104
- * Wrap a {@link WorkflowDefinition} as an LLM-callable tool — it ADVERTISES the SIMPLE flat
2105
- * authoring shape (`{ name?, steps: [{ name }] }`) as its `parameters` so even a small model can
2106
- * author a complete tree, and its handler EXPANDS / COMPLETES the authored blob, validates it
2107
- * against the STRICT contract, runs it through `runner`, and, when
2108
- * {@link import('./types.js').WorkflowToolOptions.store} is supplied, PERSISTS each executed
2109
- * workflow's final snapshot after the run settles.
2110
- *
2111
- * @remarks
2112
- * A plain `ToolManagerInterface`-compatible tool (`@orkestrel/agent`), reproducing
2113
- * `@orkestrel/workflow`'s former call contract exactly (flat / draft / full authoring forms, the
2114
- * strict soundness gate, the depth/cycle guard). It is ALSO the propagation carrier
2115
- * {@link createAgentFunction} binds onto a wrapped agent's `context.tools`: because a tool
2116
- * handler receives ONLY the model-supplied `args` (no ambient context, no signal), the run's
2117
- * depth + ancestry are CLOSED OVER at bind time via {@link import('./types.js').WorkflowToolOptions},
2118
- * and the handler enforces the SAME depth / cycle guard itself before running the nested
2119
- * workflow at `depth + 1` with the extended ancestry.
2120
- *
2121
- * **Widened authoring surface (additive — the canonical contract + runner stay STRICT and
2122
- * unchanged).** A 2B model reliably CALLS the tool but cannot reliably emit the full four-level
2123
- * nested {@link WorkflowDefinition} (six required `id`/`name` strings, an all-or-nothing tree).
2124
- * So the tool ACCEPTS three authoring forms and converges them on the SAME strict
2125
- * `createWorkflowContract` gate before running (soundness preserved):
2126
- * - the FLAT shape `{ name?, steps: [{ name }] }` — the ADVERTISED `parameters` (the simplest
2127
- * form, {@link import('./helpers.js').expandSteps}'d into one one-task phase per step);
2128
- * - a nested DRAFT with any `id`/`name` OMITTED — {@link createWorkflowDraftContract}-parsed then
2129
- * {@link import('./helpers.js').completeDraft}'d (missing ids synthesized positionally);
2130
- * - the full nested {@link WorkflowDefinition} — the advanced escape-hatch, accepted as the draft
2131
- * super-set.
2132
- *
2133
- * The universal tool-handler contract (AGENTS §14): returns the plain run summary
2134
- * (`{ status, count }`) on success, THROWS a typed `WorkflowError` (`@orkestrel/workflow`) on
2135
- * every failure path — malformed authored args (`TOOL`), or an over-deep / cyclic nested run
2136
- * (`DEPTH`). The `ToolManagerInterface` isolates every throw into the canonical tool result's
2137
- * top-level `error`, so nothing escapes the run. `options.depth` / `options.ancestry` are the
2138
- * propagation carrier across a workflow → agent → workflow chain; `options.store` is this
2139
- * package's ADDITION — the persisted snapshot is retrievable via the store afterwards (a caller
2140
- * restores it through `@orkestrel/workflow`'s own `Workflow.restore` / store-backed factories).
2141
- *
2142
- * @param definition - The workflow the tool runs when called with no authored args
2143
- * @param runner - The `WorkflowRunnerInterface` (`@orkestrel/workflow`) that executes the (nested) workflow
2144
- * @param options - Depth/ancestry bookkeeping plus the optional durable store (see {@link import('./types.js').WorkflowToolOptions})
2145
- * @returns A `ToolInterface` (named {@link import('./constants.js').WORKFLOW_TOOL_NAME}) whose
2146
- * `parameters` advertise the flat authoring schema
2147
- *
2148
- * @example
2149
- * ```ts
2150
- * import { createWorkflowTool } from '@src/core'
2151
- * import { createWorkflowRunner, createMemoryWorkflowStore } from '@orkestrel/workflow'
2152
- * import { createToolManager } from '@orkestrel/agent'
2153
- *
2154
- * const runner = createWorkflowRunner()
2155
- * const store = createMemoryWorkflowStore()
2156
- * const tool = createWorkflowTool(definition, runner, { store })
2157
- * const tools = createToolManager()
2158
- * tools.add(tool) // authored runs are now persisted to `store` on settle
2159
- * ```
2160
- */
2161
- function createWorkflowTool(definition, runner, options) {
2162
- const strict = createWorkflowContract();
2163
- const draft = createWorkflowDraftContract();
2164
- const steps = createContract(workflowStepsShape);
2165
- const depth = options?.depth ?? 0;
2166
- const ancestry = options?.ancestry ?? [];
2167
- const store = options?.store;
2168
- const parameters = schemaToParameters(steps.schema);
2169
- return createTool({
2170
- name: WORKFLOW_TOOL_NAME,
2171
- description: WORKFLOW_TOOL_DESCRIPTION,
2172
- summary: WORKFLOW_TOOL_SUMMARY,
2173
- ...parameters === void 0 ? {} : { parameters },
2174
- async execute(args) {
2175
- let target;
2176
- if (Object.keys(args).length === 0) target = definition;
2177
- else if (Array.isArray(args.steps)) {
2178
- const flat = steps.parse(args);
2179
- target = flat === void 0 ? void 0 : expandSteps(flat);
2180
- } else {
2181
- const parsed = draft.parse(args);
2182
- target = parsed === void 0 ? void 0 : completeDraft(parsed);
2183
- }
2184
- if (target === void 0 || !strict.is(target)) throw new WorkflowError("TOOL", "malformed workflow definition", { workflow: definition.id });
2185
- if (depth + 1 > 8) throw new WorkflowError("DEPTH", `nested workflow exceeds max depth 8`, {
2186
- workflow: target.id,
2187
- depth,
2188
- max: 8
2189
- });
2190
- const tag = workflowTag(target.id);
2191
- if (ancestry.includes(tag)) throw new WorkflowError("DEPTH", `workflow '${target.id}' is already an ancestor (cycle)`, {
2192
- workflow: target.id,
2193
- ancestry: [...ancestry]
2194
- });
2195
- const result = await runner.execute(target);
2196
- if (store !== void 0) await store.set(result.workflow.snapshot());
2197
- return workflowToolSummary(result);
2198
- }
2199
- });
2200
- }
2201
- /**
2202
- * Build an LLM-callable workspace-editing tool — it ADVERTISES the `operation`-discriminated
2203
- * 13-op union ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its
2204
- * handler PARSES the model-supplied args against that contract and DISPATCHES the matched
2205
- * operation against the manager's ACTIVE workspace (the registry ops drive the manager itself),
2206
- * returning the plain result (throwing a typed `WorkspaceError`, `@orkestrel/agent`, on
2207
- * failure). EITHER drives a caller-supplied {@link WorkspaceToolOptions.manager} directly, OR
2208
- * constructs a fresh `WorkspaceManagerInterface` (`@orkestrel/agent`) over
2209
- * {@link import('./types.js').WorkspaceToolOptions.store} (via `@orkestrel/agent`'s
2210
- * `createWorkspaceManager`); neither given constructs a manager backed by `@orkestrel/agent`'s
2211
- * in-memory store default.
2212
- *
2213
- * @remarks
2214
- * MANAGER-DRIVEN: every edit / read op (read / list / has / search / replace / write / splice /
2215
- * prepend / append / move / remove) targets `manager.active`, so the model edits whichever
2216
- * workspace is active and a host can re-point it (`WorkspaceManagerInterface.switch`) between
2217
- * turns. Two REGISTRY ops make the model self-sufficient: `workspaces` LISTS the registered
2218
- * workspaces (each `{ id, files, active }`) so it can discover an id, and `switch` re-points the
2219
- * active workspace by id (lenient — an unknown id is a no-op reporting `switched: false`, never a
2220
- * throw).
2221
- *
2222
- * NO-ACTIVE RULE (the ergonomic seam): a WRITING op (write / splice / prepend / append / move /
2223
- * remove / replace) run when `manager.active` is `undefined` AUTO-CREATES + activates a default
2224
- * workspace (`manager.add()`) so the model can just start writing; a pure-READ op (read / list /
2225
- * has / search) against no active workspace returns the EMPTY result (`undefined` / `[]` /
2226
- * `false`), never creating one and never throwing.
2227
- *
2228
- * The handler conforms to the universal tool-handler contract (AGENTS §14): it `contract.parse`s
2229
- * the args, THROWS a `TOOL` `WorkspaceError` when no operation arm matched (a malformed / unknown
2230
- * operation), else `switch`es on `op.operation` and RETURNS the plain result — letting a
2231
- * `WorkspaceError` raised by the live workspace (`MODALITY` / `PATTERN` / `RANGE`) PROPAGATE
2232
- * uncaught. The range edit is the FLAT `'splice'` op: its four flat caret integers are
2233
- * reassembled into a `Range` (`@orkestrel/agent`) by `rangeOf` and fed to the workspace's ranged
2234
- * `write`.
2235
- *
2236
- * @param options - `manager` (drive directly) OR `store` (build a manager over it); neither ⇒
2237
- * an in-memory-backed manager (see {@link import('./types.js').WorkspaceToolOptions})
2238
- * @returns A `ToolInterface` (named {@link import('./constants.js').WORKSPACE_TOOL_NAME} by default)
2239
- *
2240
- * @example
2241
- * ```ts
2242
- * import { createWorkspaceTool } from '@src/core'
2243
- * import { createToolManager } from '@orkestrel/agent'
2244
- *
2245
- * const tool = createWorkspaceTool() // in-memory workspace, no persistence
2246
- * const tools = createToolManager()
2247
- * tools.add(tool)
2248
- * ```
2249
- */
2250
- function createWorkspaceTool(options) {
2251
- const manager = options?.manager ?? createWorkspaceManager(options?.store === void 0 ? void 0 : { store: options.store });
2252
- const contract = createContract(workspaceToolShape);
2253
- const parameters = schemaToParameters(contract.schema);
2254
- return createTool({
2255
- name: options?.name ?? "workspace",
2256
- description: options?.description ?? WORKSPACE_TOOL_DESCRIPTION,
2257
- summary: WORKSPACE_TOOL_SUMMARY,
2258
- ...parameters === void 0 ? {} : { parameters },
2259
- execute(args) {
2260
- const op = contract.parse(args);
2261
- if (op === void 0) throw new WorkspaceError("TOOL", `unknown or malformed operation`, { args });
2262
- if (op.operation === "workspaces") {
2263
- const activeId = manager.active?.id;
2264
- return manager.workspaces().map((workspace) => ({
2265
- id: workspace.id,
2266
- files: workspace.count,
2267
- active: workspace.id === activeId
2268
- }));
2269
- }
2270
- if (op.operation === "switch") {
2271
- const switched = manager.switch(op.id);
2272
- return switched === void 0 ? {
2273
- id: op.id,
2274
- switched: false
2275
- } : {
2276
- id: switched.id,
2277
- switched: true,
2278
- files: switched.count
2279
- };
2280
- }
2281
- const active = manager.active;
2282
- switch (op.operation) {
2283
- case "read": return active?.read(op.path);
2284
- case "list": return (active?.files() ?? []).map((file) => ({
2285
- path: file.path,
2286
- state: file.state,
2287
- size: file.size,
2288
- lines: file.lines,
2289
- kind: isText(file.content) ? "text" : "binary"
2290
- }));
2291
- case "has": return active?.has(op.path) ?? false;
2292
- case "search": return active?.search(op.query, {
2293
- ...op.regex === void 0 ? {} : { regex: op.regex },
2294
- ...op.exact === void 0 ? {} : { exact: op.exact },
2295
- ...op.limit === void 0 ? {} : { limit: op.limit }
2296
- }) ?? [];
2297
- case "replace": return (active ?? manager.add()).replace(op.query, op.replacement, {
2298
- ...op.regex === void 0 ? {} : { regex: op.regex },
2299
- ...op.exact === void 0 ? {} : { exact: op.exact },
2300
- ...op.limit === void 0 ? {} : { limit: op.limit }
2301
- });
2302
- case "write": {
2303
- const workspace = active ?? manager.add();
2304
- workspace.write(op.path, op.content);
2305
- return {
2306
- path: op.path,
2307
- state: workspace.file(op.path)?.state
2308
- };
2309
- }
2310
- case "splice": {
2311
- const workspace = active ?? manager.add();
2312
- workspace.write(op.path, op.content, rangeOf(op.fromLine, op.fromColumn, op.toLine, op.toColumn));
2313
- return {
2314
- path: op.path,
2315
- state: workspace.file(op.path)?.state
2316
- };
2317
- }
2318
- case "prepend": {
2319
- const workspace = active ?? manager.add();
2320
- workspace.prepend(op.path, op.content);
2321
- return {
2322
- path: op.path,
2323
- state: workspace.file(op.path)?.state
2324
- };
2325
- }
2326
- case "append": {
2327
- const workspace = active ?? manager.add();
2328
- workspace.append(op.path, op.content);
2329
- return {
2330
- path: op.path,
2331
- state: workspace.file(op.path)?.state
2332
- };
2333
- }
2334
- case "move": {
2335
- const workspace = active ?? manager.add();
2336
- return {
2337
- from: op.from,
2338
- to: op.to,
2339
- moved: workspace.move(op.from, op.to)
2340
- };
2341
- }
2342
- case "remove": {
2343
- const workspace = active ?? manager.add();
2344
- return {
2345
- path: op.path,
2346
- removed: workspace.remove(op.path)
2347
- };
2348
- }
2349
- }
2350
- }
2351
- });
2352
- }
2353
- /**
2354
- * Build an LLM-callable sub-agent delegation tool — resolves a live, seeded `AgentInterface`
2355
- * from `registry` and runs it to completion for ONE delegated `task`.
2356
- *
2357
- * @remarks
2358
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2359
- * {@link import('./shapers.js').agentToolShape}, assembles an `AgentJobInput` (`task` seeds the
2360
- * sub-agent's conversation as a single `user` message; `provider` / `tools` / `system` fall
2361
- * back to the tool's own {@link import('./types.js').AgentToolOptions} defaults), rehydrates the sub-agent via
2362
- * `registry.build`, runs it with `agent.generate()`, and returns the settled
2363
- * `AgentResult.content` string (the sub-agent's final text). A missing / unresolvable `provider`, or a malformed call, THROWS a typed `TOOL`
2364
- * {@link import('./errors.js').AgentToolError}; a delegation that would exceed
2365
- * {@link import('./constants.js').AGENT_TOOL_DEPTH}, or re-enter an already-delegated agent (a
2366
- * cycle), THROWS a typed `DEPTH` {@link import('./errors.js').AgentToolError} — both isolated
2367
- * by the `ToolManagerInterface` into the canonical tool result's top-level `error`.
2368
- *
2369
- * `AgentInterface` (`@orkestrel/agent`) exposes no teardown method — a bound sub-agent's
2370
- * lifetime is the single `generate()` call this handler awaits; there is nothing to release
2371
- * afterwards (unlike a store-backed resource, its state lives entirely in the resolved
2372
- * `AgentContextInterface`, owned by the caller's registry).
2373
- *
2374
- * @param registry - The `AgentRegistryInterface` a delegated job resolves against (providers,
2375
- * tools, authorities, schedulers, and the `build` rehydration seam)
2376
- * @param options - Delegation defaults, depth/ancestry bookkeeping, and advertised overrides
2377
- * (see {@link import('./types.js').AgentToolOptions})
2378
- * @returns A `ToolInterface` (named {@link import('./constants.js').AGENT_TOOL_NAME} by default)
2379
- *
2380
- * @example
2381
- * ```ts
2382
- * import { createAgentTool } from '@src/core'
2383
- * import { createAgentRegistry, createToolManager } from '@orkestrel/agent'
2384
- *
2385
- * const registry = createAgentRegistry({ providers: { openai: myProvider } })
2386
- * const tool = createAgentTool(registry, { provider: 'openai' })
2387
- * const tools = createToolManager()
2388
- * tools.add(tool) // a model can now delegate a task to a sub-agent
2389
- * ```
2390
- */
2391
- function createAgentTool(registry, options) {
2392
- const contract = createContract(agentToolShape);
2393
- const parameters = schemaToParameters(contract.schema);
2394
- const depth = options?.depth ?? 0;
2395
- const ancestry = options?.ancestry ?? [];
2396
- return createTool({
2397
- name: options?.name ?? "agent",
2398
- description: options?.description ?? AGENT_TOOL_DESCRIPTION,
2399
- summary: AGENT_TOOL_SUMMARY,
2400
- ...parameters === void 0 ? {} : { parameters },
2401
- async execute(args) {
2402
- const call = contract.parse(args);
2403
- if (call === void 0) throw new AgentToolError("TOOL", "malformed agent-delegation call", { args });
2404
- const provider = call.provider ?? options?.provider;
2405
- if (provider === void 0) throw new AgentToolError("TOOL", "no provider resolved for the delegated agent", { task: call.task });
2406
- if (depth + 1 > 8) throw new AgentToolError("DEPTH", `delegation exceeds max agent depth 8`, {
2407
- provider,
2408
- depth,
2409
- max: 8
2410
- });
2411
- const tag = agentTag(provider);
2412
- if (ancestry.includes(tag)) throw new AgentToolError("DEPTH", `agent '${provider}' is already an ancestor (cycle)`, {
2413
- provider,
2414
- ancestry: [...ancestry]
2415
- });
2416
- const tools = call.tools ?? options?.tools;
2417
- const system = call.system ?? options?.system;
2418
- const agent = registry.build({
2419
- provider,
2420
- messages: [{
2421
- role: "user",
2422
- content: call.task
2423
- }],
2424
- ...system === void 0 ? {} : { system },
2425
- ...tools === void 0 ? {} : { tools }
2426
- });
2427
- const result = await agent.generate();
2428
- if (options?.store !== void 0) {
2429
- const active = agent.context.conversations.active;
2430
- if (active !== void 0) await options.store.set(active.snapshot());
2431
- }
2432
- return result.content;
2433
- }
2434
- });
2435
- }
2436
- /**
2437
- * Build an LLM-callable tool that returns the FULL `description` of another registered tool by
2438
- * name — the counterpart to the lean `summary` the other tools in this package advertise
2439
- * (`AGENT_TOOL_SUMMARY` / `WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY`).
2440
- *
2441
- * @remarks
2442
- * `ToolManagerInterface.definitions()` (`@orkestrel/agent`) advertises `tool.summary ??
2443
- * tool.description` — a lean one-sentence summary stands in for a tool's full teaching
2444
- * description when `summary` is set, keeping the advertised tool list compact for a small model.
2445
- * This tool is the on-demand expansion seam: given a registered tool's `name`, it looks the tool
2446
- * up via `tools.tool(name)` and returns its full `description` (falling back to `summary` when a
2447
- * tool has no `description` of its own, then a placeholder when it has neither).
2448
- *
2449
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2450
- * {@link import('./shapers.js').describeToolShape}, RETURNS the plain description string on
2451
- * success, THROWS a typed `TOOL` {@link import('./errors.js').AgentToolError} on a malformed call
2452
- * or an unknown tool name.
2453
- *
2454
- * @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) whose registered tools this
2455
- * tool can describe
2456
- * @returns A `ToolInterface` (named {@link import('./constants.js').DESCRIBE_TOOL_NAME})
2457
- *
2458
- * @example
2459
- * ```ts
2460
- * import { createDescribeTool, createWorkflowTool } from '@src/core'
2461
- * import { createToolManager } from '@orkestrel/agent'
2462
- *
2463
- * const tools = createToolManager()
2464
- * tools.add(createWorkflowTool(definition, runner))
2465
- * tools.add(createDescribeTool(tools))
2466
- * const full = await tools.execute({ id: '1', name: 'describe', arguments: { name: 'workflow' } })
2467
- * full.value // the workflow tool's full teaching description
2468
- * ```
2469
- */
2470
- function createDescribeTool(tools) {
2471
- const contract = createContract(describeToolShape);
2472
- const parameters = schemaToParameters(contract.schema);
2473
- return createTool({
2474
- name: DESCRIBE_TOOL_NAME,
2475
- description: DESCRIBE_TOOL_DESCRIPTION,
2476
- summary: DESCRIBE_TOOL_SUMMARY,
2477
- ...parameters === void 0 ? {} : { parameters },
2478
- async execute(args) {
2479
- const call = contract.parse(args);
2480
- if (call === void 0) throw new AgentToolError("TOOL", "malformed describe call", { args });
2481
- const tool = tools.tool(call.name);
2482
- if (tool === void 0) throw new AgentToolError("TOOL", `unknown tool '${call.name}'`, { name: call.name });
2483
- return tool.description ?? tool.summary ?? "<no description>";
2484
- }
2485
- });
2486
- }
2487
- /**
2488
- * Build an LLM-callable prompt tool — the ASK side of the terminal seam. Asks
2489
- * {@link import('./types.js').PromptToolOptions.to} a question and BLOCKS until it answers,
2490
- * returning the resolved answer value.
2491
- *
2492
- * @remarks
2493
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2494
- * {@link import('./shapers.js').promptToolShape}, dispatches to the matching
2495
- * `TerminalManagerInterface.ask` overload (`@orkestrel/terminal`) for the call's `form`, and
2496
- * RETURNS the resolved answer on success. `from` is FIXED at construction
2497
- * ({@link import('./types.js').PromptToolOptions.from}) — never read from the model-supplied
2498
- * args — so a model cannot spoof which terminal is asking. A prompt CYCLE rejects with
2499
- * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`
2500
- * {@link import('./errors.js').AgentToolError}; an expired prompt re-surfaces as `EXPIRE`; an
2501
- * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal
2502
- * plus the known ones (`manager.terminals()`).
2503
- *
2504
- * @param options - The live manager, the fixed `from` identity, and advertised overrides (see
2505
- * {@link import('./types.js').PromptToolOptions})
2506
- * @returns A `ToolInterface` (named {@link import('./constants.js').PROMPT_TOOL_NAME} by default)
2507
- *
2508
- * @example
2509
- * ```ts
2510
- * import { createPromptTool } from '@src/core'
2511
- * import { createTerminalManager, createToolManager } from '@orkestrel/terminal'
2512
- *
2513
- * const manager = createTerminalManager()
2514
- * manager.add('agent')
2515
- * manager.add('reviewer')
2516
- * const tool = createPromptTool({ manager, from: 'agent' })
2517
- * const tools = createToolManager()
2518
- * tools.add(tool) // the agent can now ask 'reviewer' and block for the answer
2519
- * ```
2520
- */
2521
- function createPromptTool(options) {
2522
- const contract = createContract(promptToolShape);
2523
- const parameters = schemaToParameters(contract.schema);
2524
- return createTool({
2525
- name: options.name ?? "ask",
2526
- description: options.description ?? PROMPT_TOOL_DESCRIPTION,
2527
- summary: PROMPT_TOOL_SUMMARY,
2528
- ...parameters === void 0 ? {} : { parameters },
2529
- async execute(args) {
2530
- const call = contract.parse(args);
2531
- if (call === void 0) throw new AgentToolError("TOOL", "malformed ask call", { args });
2532
- if ((call.form === "select" || call.form === "checkbox") && (call.choices ?? []).length === 0) throw new AgentToolError("TOOL", "select/checkbox requires at least one choice", {
2533
- to: call.to,
2534
- form: call.form
2535
- });
2536
- try {
2537
- switch (call.form) {
2538
- case "input": return await options.manager.ask(options.from, call.to, call.form, {
2539
- message: call.message,
2540
- ...call.default === void 0 ? {} : { default: call.default },
2541
- ...call.validate === void 0 ? {} : { validate: call.validate }
2542
- });
2543
- case "editor": return await options.manager.ask(options.from, call.to, call.form, {
2544
- message: call.message,
2545
- ...call.default === void 0 ? {} : { default: call.default },
2546
- ...call.validate === void 0 ? {} : { validate: call.validate }
2547
- });
2548
- case "password": return await options.manager.ask(options.from, call.to, call.form, {
2549
- message: call.message,
2550
- ...call.mask === void 0 ? {} : { mask: call.mask },
2551
- ...call.validate === void 0 ? {} : { validate: call.validate }
2552
- });
2553
- case "confirm": return await options.manager.ask(options.from, call.to, call.form, {
2554
- message: call.message,
2555
- ...call.default === void 0 ? {} : { default: call.default === "true" }
2556
- });
2557
- case "select": return await options.manager.ask(options.from, call.to, call.form, {
2558
- message: call.message,
2559
- choices: call.choices ?? [],
2560
- ...call.default === void 0 ? {} : { default: call.default }
2561
- });
2562
- case "checkbox": return await options.manager.ask(options.from, call.to, call.form, {
2563
- message: call.message,
2564
- choices: call.choices ?? [],
2565
- ...call.min === void 0 ? {} : { min: call.min },
2566
- ...call.max === void 0 ? {} : { max: call.max }
2567
- });
2568
- }
2569
- } catch (error) {
2570
- const code = terminalToolCode(error);
2571
- if (code === void 0) throw error;
2572
- if (code === "DEADLOCK") throw new AgentToolError("DEADLOCK", `asking '${call.to}' would form a prompt cycle`, isTerminalError(error) ? error.context : {
2573
- from: options.from,
2574
- to: call.to
2575
- });
2576
- if (code === "EXPIRE") throw new AgentToolError("EXPIRE", `prompt to '${call.to}' expired before it was answered`, { to: call.to });
2577
- if (isTerminalError(error) && error.code === "TARGET") throw new AgentToolError("TOOL", `unknown terminal '${call.to}'`, {
2578
- to: call.to,
2579
- known: options.manager.terminals()
2580
- });
2581
- throw new AgentToolError("TOOL", `asking '${call.to}' failed`, { to: call.to });
2582
- }
2583
- }
2584
- });
2585
- }
2586
- /**
2587
- * Build an LLM-callable answer tool — the ANSWER side of the terminal seam. Lists the prompts
2588
- * currently addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of
2589
- * them by id.
2590
- *
2591
- * @remarks
2592
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2593
- * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`
2594
- * returns a compact list (`{ id, from, form, message }`) of every prompt currently addressed to
2595
- * `to` (`TerminalManagerInterface.pending`, `@orkestrel/terminal`). `'answer'` looks the prompt
2596
- * up by `id` (an unknown id throws a typed `ANSWER` {@link import('./errors.js').AgentToolError}),
2597
- * normalizes the model-supplied `value` to the prompt's own form
2598
- * ({@link import('./helpers.js').coerceAnswer}), and applies it via
2599
- * `TerminalManagerInterface.answer` — a rejected / unknown / unresolvable outcome
2600
- * (`TerminalAnswerResult.error`) re-surfaces as a typed `ANSWER` `AgentToolError`; success returns
2601
- * `{ answered: id }`. `to` is FIXED at construction
2602
- * ({@link import('./types.js').AnswerToolOptions.to}) — never read from the model-supplied args —
2603
- * so a model cannot spoof which terminal it is answering for. Concurrent answerers racing on one
2604
- * endpoint are FIRST-WRITE-WINS — a late answer to an already-settled prompt returns a typed
2605
- * `ANSWER` `AgentToolError` (surfaced as a 422 over HTTP).
2606
- *
2607
- * @param options - The live manager, the fixed `to` identity, and advertised overrides (see
2608
- * {@link import('./types.js').AnswerToolOptions})
2609
- * @returns A `ToolInterface` (named {@link import('./constants.js').ANSWER_TOOL_NAME} by default)
2610
- *
2611
- * @example
2612
- * ```ts
2613
- * import { createAnswerTool } from '@src/core'
2614
- * import { createTerminalManager, createToolManager } from '@orkestrel/terminal'
2615
- *
2616
- * const manager = createTerminalManager()
2617
- * manager.add('reviewer')
2618
- * const tool = createAnswerTool({ manager, to: 'reviewer' })
2619
- * const tools = createToolManager()
2620
- * tools.add(tool) // the reviewer terminal can now list/answer prompts addressed to it
2621
- * ```
2622
- */
2623
- function createAnswerTool(options) {
2624
- const contract = createContract(answerToolShape);
2625
- const parameters = schemaToParameters(contract.schema);
2626
- return createTool({
2627
- name: options.name ?? "answer",
2628
- description: options.description ?? ANSWER_TOOL_DESCRIPTION,
2629
- summary: ANSWER_TOOL_SUMMARY,
2630
- ...parameters === void 0 ? {} : { parameters },
2631
- async execute(args) {
2632
- const call = contract.parse(args);
2633
- if (call === void 0) throw new AgentToolError("TOOL", "malformed answer call", { args });
2634
- if (call.operation === "pending") return options.manager.pending(options.to).map((prompt) => ({
2635
- id: prompt.id,
2636
- from: prompt.from,
2637
- form: prompt.form,
2638
- message: prompt.message
2639
- }));
2640
- const prompt = options.manager.pending(options.to).find((entry) => entry.id === call.id);
2641
- if (prompt === void 0) throw new AgentToolError("ANSWER", `unknown prompt '${call.id}'`, {
2642
- id: call.id,
2643
- reason: "unknown"
2644
- });
2645
- const coerced = coerceAnswer(prompt.form, call.value);
2646
- const result = options.manager.answer(options.to, call.id, coerced);
2647
- if (!result.success) throw new AgentToolError("ANSWER", `failed to answer prompt '${call.id}': ${result.error}`, {
2648
- id: call.id,
2649
- reason: result.error
2650
- });
2651
- return { answered: call.id };
2652
- }
2653
- });
2654
- }
2655
- /**
2656
- * Create the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database
2657
- * definitions, the DEFAULT store the upcoming database / relation tools will persist their
2658
- * `DatabaseDefinition` configs through.
2659
- *
2660
- * @returns A {@link DefinitionStoreInterface}
2661
- *
2662
- * @example
2663
- * ```ts
2664
- * import { createMemoryDefinitionStore } from '@src/core'
2665
- *
2666
- * const store = createMemoryDefinitionStore()
2667
- * ```
2668
- */
2669
- function createMemoryDefinitionStore() {
2670
- return new MemoryDefinitionStore();
2671
- }
2672
- /**
2673
- * Create a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database`
2674
- * layer — the driver-pluggable twin of {@link createMemoryDefinitionStore}, storing each
2675
- * database's definition as one opaque JSON column.
2676
- *
2677
- * @param driver - The {@link DriverInterface} backing the table (default an in-memory driver)
2678
- * @returns A {@link DefinitionStoreInterface}
2679
- *
2680
- * @example
2681
- * ```ts
2682
- * import { createDatabaseDefinitionStore } from '@src/core'
2683
- *
2684
- * const store = createDatabaseDefinitionStore() // in-memory by default
2685
- * ```
2686
- */
2687
- function createDatabaseDefinitionStore(driver = createMemoryDriver()) {
2688
- return new DatabaseDefinitionStore(createDatabase({
2689
- driver,
2690
- tables: { definitions: {
2691
- id: stringShape(),
2692
- definition: rawShape({})
2693
- } }
2694
- }).table("definitions"));
2695
- }
2696
- /**
2697
- * Build an LLM-callable database tool — create, query, and mutate `@orkestrel/database`
2698
- * databases through one `operation`-discriminated call (AGENTS §14, matching
2699
- * {@link createWorkspaceTool}'s single-tool-many-operations shape).
2700
- *
2701
- * @remarks
2702
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2703
- * {@link import('./shapers.js').databaseToolShape}, dispatches to the matching operation, and
2704
- * RETURNS a plain result on success. A database is resolved lazily and cached for the tool's
2705
- * lifetime — `'create'` mints one from `tables` ({@link import('./helpers.js').expandTables}) and
2706
- * a registered `driver` key ({@link import('./types.js').DatabaseToolOptions.drivers}, default
2707
- * `{ memory: () => createMemoryDriver() }`); any other operation addressing an uncached id falls
2708
- * back to {@link import('./types.js').DatabaseToolOptions.store} (an unknown id throws a typed
2709
- * `TOOL` {@link import('./errors.js').AgentToolError}). When a `store` is configured, `'create'`
2710
- * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.
2711
- *
2712
- * `'migrate'` re-declares a LIVE handle's tables via `DatabaseInterface.import` (the SAME driver
2713
- * and storage, a NEW typed view) and calls its `migrate` against the OLD deployed schema —
2714
- * derived from the handle's OWN `export()` (via {@link import('./helpers.js').tableSchema}), so it
2715
- * works for any handle, config-tracked or caller-supplied via
2716
- * {@link import('./types.js').DatabaseToolOptions.databases}. `'records'` clamps its `criteria` to
2717
- * {@link import('./types.js').DatabaseToolOptions.limit} (default
2718
- * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) via
2719
- * {@link import('./helpers.js').clampCriteria}, reporting `truncated` when storage held more rows
2720
- * than the cap. Every operation's `criteria` is normalized via
2721
- * {@link import('./helpers.js').criteriaOf} (defaults an omitted condition `connector` to `'and'`).
2722
- * When {@link import('./types.js').DatabaseToolOptions.readonly} is `true`, every mutating
2723
- * operation throws a typed `TOOL` `AgentToolError` before doing anything. When
2724
- * {@link import('./types.js').DatabaseToolOptions.timeout} is set, every `@orkestrel/database` call
2725
- * this tool makes is given a fresh `AbortSignal.timeout(timeout)`. A typed `@orkestrel/database`
2726
- * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `AgentToolError` carrying the
2727
- * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`
2728
- * ({@link import('./helpers.js').databaseToolCode}); an `AgentToolError` thrown by this tool's own
2729
- * guards passes through unwrapped.
2730
- *
2731
- * A lazily re-minted database over the DEFAULT in-memory driver yields an EMPTY database — only
2732
- * the {@link import('./types.js').DatabaseDefinition} schema persists in `store`, never rows;
2733
- * durable rows need a persistent driver factory registered in
2734
- * {@link import('./types.js').DatabaseToolOptions.drivers}. `'destroy'` closes whatever handle is
2735
- * cached for the id, including an embedder-supplied
2736
- * {@link import('./types.js').DatabaseToolOptions.databases} handle — the embedder relinquishes
2737
- * that handle's lifecycle to this tool for any id it wires in. This tool assumes the
2738
- * single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent calls
2739
- * against one id are NOT serialized by this tool. `'get'` is uncapped by
2740
- * {@link import('./types.js').DatabaseToolOptions.limit} (bounded only by the caller's `key` array
2741
- * size), unlike `'records'` / `'find'` / `'links'`.
2742
- *
2743
- * @param options - The tool's configuration (see {@link import('./types.js').DatabaseToolOptions})
2744
- * @returns A `ToolInterface` (named {@link import('./constants.js').DATABASE_TOOL_NAME} by default)
2745
- *
2746
- * @example
2747
- * ```ts
2748
- * import { createDatabaseTool } from '@src/core'
2749
- *
2750
- * const tool = createDatabaseTool()
2751
- * await tool.execute({
2752
- * operation: 'create',
2753
- * id: 'shop',
2754
- * tables: { products: { columns: { name: 'string', price: 'number' } } },
2755
- * })
2756
- * ```
2757
- */
2758
- function createDatabaseTool(options = {}) {
2759
- const contract = createContract(databaseToolShape);
2760
- const parameters = schemaToParameters(contract.schema);
2761
- const handles = new Map(Object.entries(options.databases ?? {}));
2762
- const definitions = /* @__PURE__ */ new Map();
2763
- const drivers = options.drivers ?? { memory: createMemoryDriver };
2764
- const key = options.key ?? generateUUID;
2765
- const cap = options.limit ?? 1e3;
2766
- const store = options.store;
2767
- const resolver = store === void 0 ? new DatabaseResolver(handles, drivers, key) : new DatabaseResolver(handles, drivers, key, store);
2768
- return createTool({
2769
- name: options.name ?? "database",
2770
- description: options.description ?? DATABASE_TOOL_DESCRIPTION,
2771
- summary: DATABASE_TOOL_SUMMARY,
2772
- ...parameters === void 0 ? {} : { parameters },
2773
- async execute(args) {
2774
- const call = contract.parse(args);
2775
- if (call === void 0) throw new AgentToolError("TOOL", "malformed database call", { args });
2776
- if (options.readonly === true && DATABASE_TOOL_MUTATIONS.has(call.operation)) throw new AgentToolError("TOOL", `operation '${call.operation}' is disabled in readonly mode`, { operation: call.operation });
2777
- const read = options.timeout === void 0 ? void 0 : { signal: AbortSignal.timeout(options.timeout) };
2778
- try {
2779
- switch (call.operation) {
2780
- case "create": {
2781
- if (resolver.has(call.id) || store !== void 0 && await store.get(call.id) !== void 0) throw new AgentToolError("TOOL", `database '${call.id}' already exists`, { id: call.id });
2782
- const name = call.driver ?? "memory";
2783
- const factory = drivers[name];
2784
- if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${name}'`, {
2785
- id: call.id,
2786
- driver: name
2787
- });
2788
- const tables = call.tables;
2789
- const keys = call.keys;
2790
- const handle = createDatabase({
2791
- driver: factory(),
2792
- tables: expandTables(tables),
2793
- ...keys === void 0 ? {} : { keys },
2794
- key
2795
- });
2796
- resolver.set(call.id, handle);
2797
- const definition = {
2798
- id: call.id,
2799
- driver: name,
2800
- tables,
2801
- ...keys === void 0 ? {} : { keys }
2802
- };
2803
- definitions.set(call.id, definition);
2804
- if (store !== void 0) await store.set(definition);
2805
- return {
2806
- id: call.id,
2807
- tables: Object.keys(tables)
2808
- };
2809
- }
2810
- case "tables": {
2811
- const handle = await resolver.resolve(call.id);
2812
- return { tables: Object.keys(handle.export()).map((name) => {
2813
- const table = handle.table(name);
2814
- return {
2815
- name,
2816
- primary: table.primary,
2817
- columns: table.contract.schema
2818
- };
2819
- }) };
2820
- }
2821
- case "get": {
2822
- const table = (await resolver.resolve(call.id)).table(call.table);
2823
- const many = Array.isArray(call.key);
2824
- const keys = Array.isArray(call.key) ? call.key : [call.key];
2825
- const rows = await table.get(keys);
2826
- return many ? { rows } : { row: rows[0] };
2827
- }
2828
- case "records": {
2829
- const table = (await resolver.resolve(call.id)).table(call.table);
2830
- const { criteria: probe, limit } = clampCriteria(criteriaOf(call.criteria), cap);
2831
- const rows = await table.records(probe, read);
2832
- const truncated = rows.length > limit;
2833
- const sliced = rows.slice(0, limit);
2834
- return {
2835
- rows: sliced,
2836
- count: sliced.length,
2837
- truncated,
2838
- limit
2839
- };
2840
- }
2841
- case "count": return { count: await (await resolver.resolve(call.id)).table(call.table).count(criteriaOf(call.criteria), read) };
2842
- case "aggregate": return { value: await (await resolver.resolve(call.id)).table(call.table).aggregate(call.function, call.column, criteriaOf(call.criteria), read) };
2843
- case "add": {
2844
- const table = (await resolver.resolve(call.id)).table(call.table);
2845
- const many = Array.isArray(call.row);
2846
- const rows = Array.isArray(call.row) ? call.row : [call.row];
2847
- const keys = await table.add(rows, read);
2848
- return many ? { keys } : { key: keys[0] };
2849
- }
2850
- case "set": {
2851
- const table = (await resolver.resolve(call.id)).table(call.table);
2852
- const many = Array.isArray(call.row);
2853
- const rows = Array.isArray(call.row) ? call.row : [call.row];
2854
- const keys = await table.set(rows, read);
2855
- return many ? { keys } : { key: keys[0] };
2856
- }
2857
- case "update": {
2858
- const table = (await resolver.resolve(call.id)).table(call.table);
2859
- const changes = call.changes;
2860
- const many = Array.isArray(call.key);
2861
- const keys = Array.isArray(call.key) ? call.key : [call.key];
2862
- const updated = await table.update(keys, changes, read);
2863
- return many ? { updated } : { updated: updated[0] };
2864
- }
2865
- case "remove": {
2866
- const table = (await resolver.resolve(call.id)).table(call.table);
2867
- const many = Array.isArray(call.key);
2868
- const keys = Array.isArray(call.key) ? call.key : [call.key];
2869
- const removed = await table.remove(keys, read);
2870
- return many ? { removed } : { removed: removed[0] };
2871
- }
2872
- case "migrate": {
2873
- const handle = await resolver.resolve(call.id);
2874
- const previous = handle.export();
2875
- const deployed = Object.entries(previous).map(([name, table]) => tableSchema(name, table));
2876
- const tables = call.tables;
2877
- const keys = {};
2878
- for (const name of Object.keys(tables)) {
2879
- const existing = previous[name];
2880
- if (existing !== void 0) keys[name] = existing.key;
2881
- }
2882
- const declared = expandTables(tables);
2883
- const migrated = handle.import(declared, Object.keys(keys).length > 0 ? keys : void 0);
2884
- const migration = await migrated.migrate(deployed, read);
2885
- resolver.set(call.id, migrated);
2886
- const tracked = definitions.get(call.id) ?? (store === void 0 ? void 0 : await store.get(call.id));
2887
- if (tracked !== void 0) {
2888
- const updated = {
2889
- id: call.id,
2890
- driver: tracked.driver,
2891
- tables,
2892
- ...Object.keys(keys).length > 0 ? { keys } : {}
2893
- };
2894
- definitions.set(call.id, updated);
2895
- if (store !== void 0) await store.set(updated);
2896
- }
2897
- return { migration };
2898
- }
2899
- case "destroy": {
2900
- const cached = resolver.get(call.id);
2901
- const persisted = store !== void 0 && cached === void 0 ? await store.get(call.id) !== void 0 : false;
2902
- if (cached !== void 0) {
2903
- await cached.close();
2904
- resolver.delete(call.id);
2905
- }
2906
- definitions.delete(call.id);
2907
- if (store !== void 0) await store.delete(call.id);
2908
- return {
2909
- id: call.id,
2910
- destroyed: cached !== void 0 || persisted
2911
- };
2912
- }
2913
- }
2914
- } catch (error) {
2915
- if (isAgentToolError(error)) throw error;
2916
- const code = databaseToolCode(error);
2917
- if (code === void 0) throw error;
2918
- throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
2919
- code,
2920
- operation: call.operation,
2921
- id: call.id,
2922
- ..."table" in call ? { table: call.table } : {}
2923
- });
2924
- }
2925
- }
2926
- });
2927
- }
2928
- /**
2929
- * Build an LLM-callable relation tool — traverse and edit `@orkestrel/relation` relationships
2930
- * through one `operation`-discriminated call (AGENTS §14, matching {@link createDatabaseTool}'s
2931
- * single-tool-many-operations shape).
2932
- *
2933
- * @remarks
2934
- * The universal tool-handler contract (AGENTS §14): validates the call args against
2935
- * {@link import('./shapers.js').relationToolShape}, resolves the addressed
2936
- * {@link import('@orkestrel/relation').RelationManagerInterface} — an explicit `manager` field
2937
- * must match a key of {@link import('./types.js').RelationToolOptions.managers}, an OMITTED one
2938
- * resolves to the SOLE registered manager, either miss throwing a typed `TOOL`
2939
- * {@link import('./errors.js').AgentToolError}
2940
- * ({@link import('./helpers.js').relationManagerOf}) — then resolves `model` against it
2941
- * ({@link import('./helpers.js').relationModelOf}, same typed-`TOOL`-on-miss shape), and
2942
- * dispatches to the matched operation, RETURNING a plain result on success.
2943
- *
2944
- * `'load'` / `'find'` expand the call's FLAT dot-path `include` list into a live
2945
- * `@orkestrel/relation` `Include` tree via {@link import('./helpers.js').expandInclude}, capped
2946
- * at {@link import('./types.js').RelationToolOptions.depth} (default
2947
- * {@link import('./constants.js').RELATION_TOOL_DEPTH}) — a path exceeding the cap, or carrying an
2948
- * empty segment, throws a typed `TOOL` error. `'load'` dispatches on whether `key` is an array
2949
- * (positional many-key form, AGENTS §9.2) or a single key. `'find'` and `'links'` clamp their
2950
- * result to {@link import('./types.js').RelationToolOptions.limit} (default
2951
- * {@link import('./constants.js').RELATION_TOOL_LIMIT}) — `'find'` probes one row past the
2952
- * effective limit (mirroring {@link import('./helpers.js').clampCriteria}'s idiom) to report
2953
- * `truncated`; `'links'` (which has no upstream pagination) fetches the FULL linked-key list and
2954
- * slices/truncates it the same way. `'link'` / `'unlink'` write / remove one `through` junction
2955
- * row.
2956
- *
2957
- * A typed `@orkestrel/relation` failure (`RelationError`) re-surfaces as a typed `RELATION`
2958
- * `AgentToolError` carrying the original {@link import('@orkestrel/relation').RelationErrorCode}
2959
- * in `context.code`; a typed `@orkestrel/database` failure underneath it (`DatabaseError`)
2960
- * re-surfaces as a typed `DATABASE` `AgentToolError`, mirroring {@link createDatabaseTool}'s error
2961
- * mapping; an `AgentToolError` thrown by this tool's own guards (malformed args, an unknown
2962
- * manager/model) passes through unwrapped.
2963
- *
2964
- * @param options - The tool's configuration (see {@link import('./types.js').RelationToolOptions})
2965
- * @returns A `ToolInterface` (named {@link import('./constants.js').RELATION_TOOL_NAME} by default)
2966
- *
2967
- * @example
2968
- * ```ts
2969
- * import { createRelationTool } from '@src/core'
2970
- *
2971
- * const tool = createRelationTool({ managers: { shop: manager } })
2972
- * await tool.execute({ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] })
2973
- * ```
2974
- */
2975
- function createRelationTool(options) {
2976
- const contract = createContract(relationToolShape);
2977
- const parameters = schemaToParameters(contract.schema);
2978
- const depth = options.depth ?? 3;
2979
- const cap = options.limit ?? 1e3;
2980
- return createTool({
2981
- name: options.name ?? "relation",
2982
- description: options.description ?? RELATION_TOOL_DESCRIPTION,
2983
- summary: RELATION_TOOL_SUMMARY,
2984
- ...parameters === void 0 ? {} : { parameters },
2985
- async execute(args) {
2986
- const call = contract.parse(args);
2987
- if (call === void 0) throw new AgentToolError("TOOL", "malformed relation call", { args });
2988
- try {
2989
- const model = relationModelOf(relationManagerOf(options.managers, call.manager), call.model);
2990
- switch (call.operation) {
2991
- case "load": {
2992
- const include = expandInclude(call.include, depth);
2993
- if (typeof call.key === "string" || typeof call.key === "number") return { row: await model.load(call.key, include) };
2994
- return { rows: await model.load(call.key, include) };
2995
- }
2996
- case "find": {
2997
- const include = expandInclude(call.include, depth);
2998
- const effective = Math.min(call.limit ?? cap, cap);
2999
- const rows = await model.find(include, {
3000
- limit: effective + 1,
3001
- ...call.offset === void 0 ? {} : { offset: call.offset },
3002
- ...call.sort === void 0 ? {} : { sort: call.sort },
3003
- ...call.direction === void 0 ? {} : { direction: call.direction }
3004
- });
3005
- const truncated = rows.length > effective;
3006
- const sliced = rows.slice(0, effective);
3007
- return {
3008
- rows: sliced,
3009
- count: sliced.length,
3010
- truncated,
3011
- limit: effective
3012
- };
3013
- }
3014
- case "link":
3015
- await model.link(call.key, call.relation, call.target);
3016
- return { linked: true };
3017
- case "unlink":
3018
- await model.unlink(call.key, call.relation, call.target);
3019
- return { unlinked: true };
3020
- case "links": {
3021
- const keys = await model.links(call.key, call.relation);
3022
- const truncated = keys.length > cap;
3023
- const sliced = keys.slice(0, cap);
3024
- return {
3025
- keys: sliced,
3026
- count: sliced.length,
3027
- truncated,
3028
- limit: cap
3029
- };
3030
- }
3031
- }
3032
- } catch (error) {
3033
- if (isAgentToolError(error)) throw error;
3034
- const relation = relationToolCode(error);
3035
- if (relation !== void 0) throw new AgentToolError("RELATION", error instanceof Error ? error.message : String(error), {
3036
- code: relation,
3037
- operation: call.operation,
3038
- model: call.model,
3039
- ..."relation" in call ? { relation: call.relation } : {}
3040
- });
3041
- const database = databaseToolCode(error);
3042
- if (database === void 0) throw error;
3043
- throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
3044
- code: database,
3045
- operation: call.operation
3046
- });
3047
- }
3048
- }
3049
- });
3050
- }
3051
- /**
3052
- * Build a standalone LLM-callable tool that infers a JSON Schema from example values — the
3053
- * utility half of the "existing API/DB → MCP tool" bridge (the other half,
3054
- * {@link createEndpointTool}, wraps one CONCRETE endpoint).
3055
- *
3056
- * @remarks
3057
- * The universal tool-handler contract (AGENTS §14): validates the call args against
3058
- * {@link import('./shapers.js').inferToolShape} (`samples` non-empty, `format` / `enum` optional
3059
- * booleans, `candidates` an optional array), infers a schema via `@orkestrel/contract`'s
3060
- * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` via `schemaToObject` (mirrors
3061
- * the tool-parameters convention every other `create*Tool` factory advertises), and RETURNS the
3062
- * resulting parameters record. An empty `samples` array fails `inferToolShape`'s `min: 1` bound —
3063
- * `contract.parse` returns `undefined` and the handler throws a typed `TOOL`
3064
- * {@link import('./errors.js').AgentToolError}.
3065
- *
3066
- * When `candidates` is ABSENT, the return is the bare parameters record — unchanged from before
3067
- * this array existed. When `candidates` is PRESENT (any array, including empty), the handler
3068
- * compiles a SEPARATE per-call contract from the RAW inferred schema (via `@orkestrel/contract`'s
3069
- * `schemaToShape`, NOT the `schemaToObject`-wrapped parameters — a bare-value sample checks a
3070
- * bare-value candidate) and returns `{ parameters, checks }`, one check per candidate at the same
3071
- * index. Every entry has a UNIFORM shape — `{ index, valid, coercible }`, with `faults` added ONLY
3072
- * when `valid` is `false`: `valid` is the STRICT guard verdict (`checker.is(candidate)`), the
3073
- * OPPOSITE of {@link createEndpointTool}'s enforcement, which coerces (`7` becomes `'7'` for a
3074
- * string slot) — here a conformance report answers "does this value conform AS-IS": `7` against a
3075
- * string slot is `valid: false`, full stop. `coercible` answers a SEPARATE question — "would the
3076
- * NORMALIZING parse accept this value", i.e. would {@link createEndpointTool}'s default enforcement
3077
- * admit it (`checker.parse(candidate) !== undefined`) — computed for every candidate regardless of
3078
- * `valid`; by the house parse/guard round-trip guarantee (AGENTS §14), a `valid: true` entry is
3079
- * ALWAYS also `coercible: true`. `@orkestrel/contract` 0.0.7's `explain` mirrors the normalizing
3080
- * `parse`'s leniency, not `is`'s strictness — so a strictly-invalid but coercible candidate (`7`
3081
- * against a string slot) yields `{ valid: false, coercible: true, faults: [] }`: EMPTY faults, since
3082
- * the mismatch the normalizing parse would silently fix is not one `explain` reports. `faults`
3083
- * therefore only ever populates for a NON-coercible mismatch — a wrong type the parse can't coerce
3084
- * (a boolean in a string slot), a missing required key, or an out-of-enum value — where
3085
- * `coercible: false`. `checker.is` / `.parse` / `.explain` are all total over JSON-safe input — a
3086
- * JSON-safe hostile candidate (a `__proto__`-carrying object, deeply nested data) reaches all three
3087
- * and yields a bounded, non-throwing per-candidate verdict; a NON-JSON-safe candidate (e.g. a
3088
- * throwing-getter `Proxy`) never reaches the checker at all — it fails the OUTER `args` parse
3089
- * against {@link import('./shapers.js').inferToolShape} and rejects the WHOLE call with the same
3090
- * `TOOL` {@link import('./errors.js').AgentToolError} a malformed `samples`/`format`/`enum` throws,
3091
- * with no per-candidate verdict produced.
159
+ * Create an executable tool.
3092
160
  *
3093
- * @param options - Advertised `name` / `description` overrides (see
3094
- * {@link import('./types.js').InferToolOptions})
3095
- * @returns A `ToolInterface` (named {@link import('./constants.js').INFER_TOOL_NAME} by default)
161
+ * @param options - The advertised definition and execution handler
162
+ * @returns A tool bound to the supplied handler
3096
163
  *
3097
164
  * @example
3098
165
  * ```ts
3099
- * import { createInferTool } from '@src/core'
3100
- * import { createToolManager } from '@orkestrel/agent'
3101
- *
3102
- * const tool = createInferTool()
3103
- * const tools = createToolManager()
3104
- * tools.add(tool)
166
+ * import { createTool } from '@orkestrel/tool'
3105
167
  *
3106
- * const result = await tools.execute({
3107
- * id: 'call-1',
3108
- * name: 'infer',
3109
- * arguments: { samples: [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bob' }] },
3110
- * })
3111
- * // result.value -> { type: 'object', properties: { id: {...}, name: {...} }, ... }
3112
- *
3113
- * // with candidates, the result is wrapped with per-candidate verdicts
3114
- * const checked = await tools.execute({
3115
- * id: 'call-2',
3116
- * name: 'infer',
3117
- * arguments: {
3118
- * samples: [{ id: 1, name: 'Ada' }],
3119
- * candidates: [{ id: 2, name: 'Bob' }, { id: 'x', name: 'Cy' }],
3120
- * },
168
+ * const add = createTool({
169
+ * name: 'add',
170
+ * description: 'Add two numbers',
171
+ * execute: (args) => Number(args.a) + Number(args.b),
3121
172
  * })
3122
- * // checked.value -> { parameters: {...}, checks: [
3123
- * // { index: 0, valid: true, coercible: true },
3124
- * // { index: 1, valid: false, coercible: false, faults: [...] },
3125
- * // ] }
3126
173
  * ```
3127
174
  */
3128
- function createInferTool(options) {
3129
- const contract = createContract(inferToolShape);
3130
- const parameters = schemaToParameters(contract.schema);
3131
- return createTool({
3132
- name: options?.name ?? "infer",
3133
- description: options?.description ?? INFER_TOOL_DESCRIPTION,
3134
- summary: INFER_TOOL_SUMMARY,
3135
- ...parameters === void 0 ? {} : { parameters },
3136
- async execute(args) {
3137
- const parsed = contract.parse(args);
3138
- if (parsed === void 0) throw new AgentToolError("TOOL", "malformed infer arguments", { args });
3139
- const schema = samplesToSchema(parsed.samples, {
3140
- format: parsed.format ?? false,
3141
- enum: parsed.enum ?? false
3142
- });
3143
- const result = schemaToParameters(schemaToObject(schema));
3144
- if (result === void 0) throw new AgentToolError("TOOL", "could not infer a schema", { args });
3145
- if (parsed.candidates === void 0) return result;
3146
- const checker = createContract(schemaToShape(schema));
3147
- return {
3148
- parameters: result,
3149
- checks: parsed.candidates.map((candidate, index) => {
3150
- const valid = checker.is(candidate);
3151
- const coercible = checker.parse(candidate) !== void 0;
3152
- return valid ? {
3153
- index,
3154
- valid,
3155
- coercible
3156
- } : {
3157
- index,
3158
- valid,
3159
- coercible,
3160
- faults: checker.explain(candidate)
3161
- };
3162
- })
3163
- };
3164
- }
3165
- });
175
+ function createTool(options) {
176
+ return new Tool(options);
3166
177
  }
3167
178
  /**
3168
- * Wrap one CONCRETE endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable
3169
- * `ToolInterface` — the endpoint half of the "existing API/DB → MCP tool" bridge (the other half,
3170
- * {@link createInferTool}, is a standalone inference utility).
179
+ * Create an empty tool registry.
3171
180
  *
3172
- * @remarks
3173
- * `parameters` is inferred ONCE at construction from `definition.samples` via
3174
- * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s
3175
- * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` via `schemaToObject` —
3176
- * the SAME object-rooted schema is both the ADVERTISED `parameters` and, by default
3177
- * ({@link import('./types.js').EndpointToolOptions.validate} `true`), the ENFORCED contract:
3178
- * `@orkestrel/contract` 0.0.7's `schemaToShape` compiles it ONCE (via `createContract`) into a
3179
- * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.invoke` — a
3180
- * NORMALIZING parse, not a strict type check: a scalar is COERCED to its inferred type where the
3181
- * house parsers coerce (a number to/from a numeric string, a boolean from `'1'`/`'0'`/`'true'`/
3182
- * `'false'`/`1`/`0`), so `definition.invoke` receives the COERCED value (e.g. `7` sent for a
3183
- * string slot arrives as `'7'`), not the raw call value. A call whose `args` fails to parse into
3184
- * a record — a required key missing, or a value not coercible to its slot's type — THROWS a
3185
- * typed `TOOL` {@link import('./errors.js').AgentToolError} carrying the compiled contract's
3186
- * structured `explain` faults, and `definition.invoke` is never called. `format` annotations are
3187
- * NEVER asserted, and a key outside the closed inferred schema is SILENTLY DROPPED rather than
3188
- * rejected (see {@link import('./types.js').EndpointToolOptions.validate}). With
3189
- * `validate: false`, `execute` PASSES THROUGH the model-supplied `args` to `definition.invoke`
3190
- * WITHOUT re-validation — the pre-0.0.7 behavior, preserved as an explicit opt-out. Either way,
3191
- * `invoke`'s return flows back as the tool call's plain result; a throw PROPAGATES uncaught,
3192
- * isolated by the `ToolManagerInterface` (`@orkestrel/agent`) into the canonical error envelope
3193
- * (AGENTS §14) — never caught or re-wrapped here.
3194
- *
3195
- * @param definition - The endpoint's identity, non-empty samples, and local handler (see
3196
- * {@link import('./types.js').EndpointDefinition})
3197
- * @param options - Construction-time inference tuning + the validate opt-out (see
3198
- * {@link import('./types.js').EndpointToolOptions})
3199
- * @returns A `ToolInterface` named `definition.name`
181
+ * @returns A registry that advertises definitions and executes calls with per-call
182
+ * error isolation
3200
183
  *
3201
184
  * @example
3202
185
  * ```ts
3203
- * import { createEndpointTool } from '@src/core'
3204
- * import { createToolManager } from '@orkestrel/agent'
186
+ * import { createTool, createToolManager } from '@orkestrel/tool'
3205
187
  *
3206
- * const tool = createEndpointTool({
3207
- * name: 'lookupUser',
3208
- * description: 'Look up a user by id.',
3209
- * samples: [{ id: '1', name: 'Ada' }, { id: '2', name: 'Bob' }],
3210
- * invoke: (args) => ({ id: args.id, name: 'Ada' }),
3211
- * })
3212
188
  * const tools = createToolManager()
3213
- * tools.add(tool)
3214
- *
3215
- * // conforming args (all required keys present) parse and reach `invoke`
189
+ * tools.add(createTool({ name: 'echo', execute: (args) => args.value }))
3216
190
  * const result = await tools.execute({
3217
- * id: 'call-1',
3218
- * name: 'lookupUser',
3219
- * arguments: { id: '1', name: 'Ada' },
191
+ * id: '1',
192
+ * name: 'echo',
193
+ * arguments: { value: 'hello' },
3220
194
  * })
3221
- * // result.value -> { id: '1', name: 'Ada' }
3222
- *
3223
- * // a nonconforming call (id is not coercible to the required string) is rejected before
3224
- * // `invoke` runs
3225
- * const rejected = await tools.execute({
3226
- * id: 'call-2',
3227
- * name: 'lookupUser',
3228
- * arguments: { id: true, name: 'Ada' },
3229
- * })
3230
- * // rejected.error -> the TOOL AgentToolError message
3231
195
  * ```
3232
196
  */
3233
- function createEndpointTool(definition, options) {
3234
- if (definition.samples.length === 0) throw new AgentToolError("TOOL", "endpoint requires at least one sample", { name: definition.name });
3235
- const objectSchema = schemaToObject(samplesToSchema(definition.samples, {
3236
- format: options?.format ?? false,
3237
- enum: options?.enum ?? false
3238
- }));
3239
- const parameters = schemaToParameters(objectSchema);
3240
- if (!(options?.validate ?? true)) return createTool({
3241
- name: definition.name,
3242
- description: definition.description,
3243
- ...parameters === void 0 ? {} : { parameters },
3244
- execute(args) {
3245
- return definition.invoke(args);
3246
- }
3247
- });
3248
- const contract = createContract(schemaToShape(objectSchema));
3249
- return createTool({
3250
- name: definition.name,
3251
- description: definition.description,
3252
- ...parameters === void 0 ? {} : { parameters },
3253
- execute(args) {
3254
- const parsed = contract.parse(args);
3255
- if (parsed === void 0 || !isRecord(parsed)) throw new AgentToolError("TOOL", "malformed endpoint call arguments", {
3256
- name: definition.name,
3257
- faults: contract.explain(args)
3258
- });
3259
- return definition.invoke(parsed);
3260
- }
3261
- });
197
+ function createToolManager() {
198
+ return new ToolManager();
3262
199
  }
3263
200
  //#endregion
3264
- export { AGENT_TOOL_DEPTH, AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME, AGENT_TOOL_SUMMARY, ANSWER_TOOL_DESCRIPTION, ANSWER_TOOL_NAME, ANSWER_TOOL_SUMMARY, AgentToolError, DATABASE_TOOL_DESCRIPTION, DATABASE_TOOL_LIMIT, DATABASE_TOOL_MUTATIONS, DATABASE_TOOL_NAME, DATABASE_TOOL_SUMMARY, DESCRIBE_TOOL_DESCRIPTION, DESCRIBE_TOOL_NAME, DESCRIBE_TOOL_SUMMARY, DatabaseDefinitionStore, DatabaseResolver, INFER_TOOL_DESCRIPTION, INFER_TOOL_NAME, INFER_TOOL_SUMMARY, MAX_WORKFLOW_DEPTH, MemoryDefinitionStore, PROMPT_TOOL_DESCRIPTION, PROMPT_TOOL_NAME, PROMPT_TOOL_SUMMARY, RELATION_TOOL_DEPTH, RELATION_TOOL_DESCRIPTION, RELATION_TOOL_LIMIT, RELATION_TOOL_NAME, RELATION_TOOL_SUMMARY, WORKFLOW_TOOL_DESCRIPTION, WORKFLOW_TOOL_FLAT_EXAMPLE, WORKFLOW_TOOL_NAME, WORKFLOW_TOOL_NESTED_EXAMPLE, WORKFLOW_TOOL_SUMMARY, WORKSPACE_TOOL_DESCRIPTION, WORKSPACE_TOOL_EXAMPLE, WORKSPACE_TOOL_NAME, WORKSPACE_TOOL_SUMMARY, agentTag, agentToolShape, answerToolShape, clampCriteria, coerceAnswer, columnKindShape, columnSchema, columnShape, columnSpecShape, completeDraft, completePhaseDraft, completeTaskDraft, conditionShape, createAgentFunction, createAgentTool, createAnswerTool, createDatabaseDefinitionStore, createDatabaseTool, createDescribeTool, createEndpointTool, createInferTool, createMemoryDefinitionStore, createPromptTool, createRelationTool, createToolFunction, createWorkflowDraftContract, createWorkflowTool, createWorkspaceTool, criteriaOf, criteriaShape, databaseToolCode, databaseToolShape, describeToolShape, expandInclude, expandSteps, expandTables, includeShape, inferToolShape, isAgentToolError, isColumnKind, isColumnSpec, isDatabaseDefinition, keyShape, kindShape, managerShape, orderShape, phaseDraftShape, promptToolShape, relationKeyShape, relationManagerOf, relationModelOf, relationToolCode, relationToolShape, rowShape, rowsShape, singleKeyShape, stepShape, tableSchema, tableSpecShape, taskDraftShape, terminalToolCode, workflowDraftShape, workflowStepsShape, workflowTag, workflowToolSummary, workspaceToolShape };
201
+ export { Tool, ToolManager, createTool, createToolManager, isToolCall };
3265
202
 
3266
203
  //# sourceMappingURL=index.js.map