@orkestrel/tool 0.0.1 → 0.0.3

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,4 +1,7 @@
1
- import { arrayShape, booleanShape, createContract, integerShape, literalShape, objectShape, optionalShape, schemaToParameters, stringShape, unionShape } from "@orkestrel/contract";
1
+ import { arrayShape, booleanShape, createContract, integerShape, isNonEmptyString, isRecord, isString, jsonShape, literalShape, numberShape, objectShape, optionalShape, rawShape, recordShape, schemaToParameters, 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";
2
5
  import { WorkspaceError, createTool, createWorkspaceManager, isText, rangeOf } from "@orkestrel/agent";
3
6
  import { WorkflowError, createWorkflowContract } from "@orkestrel/workflow";
4
7
  //#region src/core/constants.ts
@@ -236,13 +239,204 @@ var DESCRIBE_TOOL_SUMMARY = "Return the full description of a named registered t
236
239
  * schema or multi-step protocol to teach.
237
240
  */
238
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;
239
427
  //#endregion
240
428
  //#region src/core/errors.ts
241
429
  /**
242
430
  * Thrown by {@link import('./factories.js').createAgentTool}'s and
243
431
  * {@link import('./factories.js').createDescribeTool}'s handlers on every failure path — a
244
- * malformed / unresolvable call or an unknown tool name (`TOOL`), or a delegation that would
245
- * exceed the configured depth bound or re-enter an ancestor (`DEPTH`).
432
+ * malformed / unresolvable call or an unknown tool name (`TOOL`), a delegation that would
433
+ * exceed the configured depth bound or re-enter an ancestor (`DEPTH`), a prompt cycle
434
+ * (`DEADLOCK`), a prompt that expired before it was answered (`EXPIRE`), or an answer that
435
+ * failed to apply (`ANSWER`) — the last three thrown by
436
+ * {@link import('./factories.js').createPromptTool} / {@link import('./factories.js').createAnswerTool}.
437
+ * The upcoming database / relation tools (SRC-1's later units) will throw it too: a typed
438
+ * `@orkestrel/database` failure re-surfaces as `DATABASE`, a typed `@orkestrel/relation` failure
439
+ * as `RELATION` — each carrying the package's own granular error code in `context`.
246
440
  *
247
441
  * @remarks
248
442
  * Carries a machine-readable `code` (see {@link import('./types.js').AgentToolErrorCode}) and
@@ -294,6 +488,106 @@ function isAgentToolError(value) {
294
488
  //#endregion
295
489
  //#region src/core/shapers.ts
296
490
  /**
491
+ * The shape of {@link import('./factories.js').createPromptTool}'s call arguments — `to` (the
492
+ * terminal identity to address), `form` (which of the six {@link import('@orkestrel/terminal').PromptType}
493
+ * forms to ask), `message`, an optional `timeout` override, and every per-form optional field
494
+ * FLATTENED onto one object (mirrors `workspaceToolShape`'s flat-arm style, but a single shared
495
+ * shape rather than a discriminated union — `form` alone does not vary the REQUIRED fields, only
496
+ * which of the optional ones apply, so a flat shape stays faithful without duplicating `to` /
497
+ * `message` / `timeout` across six near-identical arms).
498
+ *
499
+ * @remarks
500
+ * `choices` backs `'select'` / `'checkbox'`; `default` backs `'input'` / `'confirm'` / `'select'`
501
+ * (a string for the first two forms' text default, `'true'`/`'false'` string for confirm — the
502
+ * contract layer cannot vary a field's type by a sibling field's value, so `default` stays a
503
+ * string and the handler coerces per form); `mask` backs `'password'`; `min` / `max` backs
504
+ * `'checkbox'`; `validate` (declarative only) backs the four text-shaped forms
505
+ * (`'input'` / `'password'` / `'confirm'` / `'editor'`).
506
+ */
507
+ var promptToolShape = objectShape({
508
+ to: stringShape({
509
+ min: 1,
510
+ description: "The terminal identity to address the prompt to."
511
+ }),
512
+ form: literalShape([
513
+ "input",
514
+ "password",
515
+ "confirm",
516
+ "select",
517
+ "checkbox",
518
+ "editor"
519
+ ], { description: "Which prompt form to ask." }),
520
+ message: stringShape({
521
+ min: 1,
522
+ description: "The prompt's question."
523
+ }),
524
+ default: optionalShape(stringShape({ description: "The default answer if the responder submits blank — 'input' / 'editor' text, 'confirm' 'true'/'false', or a 'select' choice value." })),
525
+ choices: optionalShape(arrayShape(objectShape({
526
+ name: stringShape({
527
+ min: 1,
528
+ description: "The choice label shown to the answering party."
529
+ }),
530
+ value: stringShape({
531
+ min: 1,
532
+ description: "The value submitted when this choice is picked."
533
+ }),
534
+ description: optionalShape(stringShape({ description: "An optional one-line elaboration." }))
535
+ }), { description: "The selectable choices for 'select' / 'checkbox'." })),
536
+ mask: optionalShape(stringShape({
537
+ min: 1,
538
+ description: "The mask character 'password' renders in place of input."
539
+ })),
540
+ min: optionalShape(integerShape({
541
+ min: 0,
542
+ description: "The minimum number of 'checkbox' selections required."
543
+ })),
544
+ max: optionalShape(integerShape({
545
+ min: 0,
546
+ description: "The maximum number of 'checkbox' selections allowed."
547
+ })),
548
+ validate: optionalShape(objectShape({
549
+ required: optionalShape(booleanShape({ description: "Reject an empty (trimmed) input." })),
550
+ minimum: optionalShape(integerShape({
551
+ min: 0,
552
+ description: "Reject an input shorter than this many characters."
553
+ })),
554
+ maximum: optionalShape(integerShape({
555
+ min: 0,
556
+ description: "Reject an input longer than this many characters."
557
+ })),
558
+ pattern: optionalShape(stringShape({ description: "Reject an input that fails this regular-expression source." })),
559
+ email: optionalShape(booleanShape({ description: "Require a valid email-address shape." })),
560
+ url: optionalShape(booleanShape({ description: "Require a valid URL shape." })),
561
+ numeric: optionalShape(booleanShape({ description: "Require a numeric value." })),
562
+ integer: optionalShape(booleanShape({ description: "Require an integer value." })),
563
+ alphanumeric: optionalShape(booleanShape({ description: "Require letters and digits only." }))
564
+ })),
565
+ timeout: optionalShape(integerShape({
566
+ min: 0,
567
+ description: "Milliseconds to wait before the prompt expires."
568
+ }))
569
+ });
570
+ /**
571
+ * The shape of {@link import('./factories.js').createAnswerTool}'s call arguments — discriminated
572
+ * by `operation`: `'pending'` lists the prompts addressed to this tool's terminal, `'answer'`
573
+ * resolves one by `id` with a `value`.
574
+ *
575
+ * @remarks
576
+ * `value`'s type varies by the ORIGINAL prompt's form (`string` for `'input'` / `'password'` /
577
+ * `'select'` / `'editor'`, `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`) —
578
+ * `unionShape(stringShape(), booleanShape(), arrayShape(stringShape()))` expresses that
579
+ * union directly, so `value` is typed as the full `string | boolean | readonly string[]` union
580
+ * here (no lossy string-only fallback needed).
581
+ */
582
+ var answerToolShape = unionShape(objectShape({ operation: literalShape(["pending"], { description: "List the prompts currently addressed to this terminal." }) }), objectShape({
583
+ operation: literalShape(["answer"], { description: "Answer one pending prompt by id." }),
584
+ id: stringShape({
585
+ min: 1,
586
+ description: "The id of the pending prompt to answer."
587
+ }),
588
+ value: unionShape(stringShape({ description: "A text / select / editor answer." }), booleanShape({ description: "A confirm answer." }), arrayShape(stringShape(), { description: "A checkbox answer — the checked values." }))
589
+ }));
590
+ /**
297
591
  * The shape of {@link import('./types.js').AgentToolArguments} —
298
592
  * {@link import('./factories.js').createAgentTool}'s advertised `parameters`.
299
593
  *
@@ -513,6 +807,304 @@ var workspaceToolShape = unionShape(objectShape({
513
807
  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." }),
514
808
  id: stringShape({ description: "The id of the workspace to make active (from the \"workspaces\" listing)." })
515
809
  }));
810
+ /** A {@link import('./types.js').ColumnKind} literal — the leaf {@link columnSpecShape} wraps. */
811
+ var columnKindShape = literalShape([
812
+ "string",
813
+ "integer",
814
+ "number",
815
+ "boolean"
816
+ ], { description: "A column type: \"string\" | \"integer\" | \"number\" | \"boolean\"." });
817
+ /** A {@link import('./types.js').ColumnSpec} — a bare {@link columnKindShape}, or `{ type, optional }`. */
818
+ var columnSpecShape = unionShape(columnKindShape, objectShape({
819
+ type: columnKindShape,
820
+ optional: optionalShape(booleanShape({ description: "Whether the column may be absent from a row." }))
821
+ }));
822
+ /** A {@link import('./types.js').TableSpec} — table name to `{ columns }`, each column a {@link columnSpecShape}. */
823
+ var tableSpecShape = recordShape(objectShape({ columns: recordShape(columnSpecShape, { description: "Column name to its type." }) }), { description: "Table name to its column layout." });
824
+ /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
825
+ 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." }));
826
+ /** A loose row — a flat object of column name to JSON value; the array form (multiple rows) resolves FIRST per AGENTS §9.2. */
827
+ var rowShape = recordShape(jsonShape(), { description: "A row as a flat object of column name to value." });
828
+ /** One or many loose rows — the array form resolves FIRST per AGENTS §9.2. */
829
+ var rowsShape = unionShape(arrayShape(rowShape, { description: "Multiple rows." }), rowShape);
830
+ /** One SERIALIZED WHERE condition — `values` is ALWAYS an array, even for a single-value operator. */
831
+ var conditionShape = objectShape({
832
+ column: stringShape({ description: "The column this condition applies to." }),
833
+ operator: literalShape([
834
+ "equals",
835
+ "not",
836
+ "above",
837
+ "below",
838
+ "from",
839
+ "to",
840
+ "between",
841
+ "like",
842
+ "glob",
843
+ "starts",
844
+ "ends",
845
+ "any",
846
+ "none",
847
+ "absent",
848
+ "present"
849
+ ], { description: "The comparison operator." }),
850
+ values: arrayShape(jsonShape(), { description: "The operand values the operator needs (always an array, even for one value)." }),
851
+ connector: optionalShape(literalShape(["and", "or"], { description: "Joins this condition to the next; omit on the last condition." }))
852
+ });
853
+ /** One sort term. */
854
+ var orderShape = objectShape({
855
+ column: stringShape({ description: "The column to sort by." }),
856
+ direction: literalShape(["ascending", "descending"], { description: "The sort direction." })
857
+ });
858
+ /** The SERIALIZED criteria form — conditions, order, and pagination. */
859
+ var criteriaShape = objectShape({
860
+ conditions: optionalShape(arrayShape(conditionShape, { description: "The WHERE conditions, folded left to right." })),
861
+ order: optionalShape(arrayShape(orderShape, { description: "The sort terms, applied in order." })),
862
+ limit: optionalShape(integerShape({
863
+ min: 0,
864
+ description: "Max rows to return."
865
+ })),
866
+ offset: optionalShape(integerShape({
867
+ min: 0,
868
+ description: "Rows to skip before returning."
869
+ }))
870
+ });
871
+ /**
872
+ * The shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —
873
+ * discriminated by `operation` into the 12 database operations (`'create'` / `'tables'` /
874
+ * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /
875
+ * `'remove'` / `'migrate'` / `'destroy'`).
876
+ *
877
+ * @remarks
878
+ * Every arm carries `id` (the database id). `'create'` / `'migrate'` carry `tables` (the
879
+ * {@link import('./types.js').TableSpec} column DSL, compiled via
880
+ * {@link import('./helpers.js').expandTables}); `'get'` / `'update'` / `'remove'` carry `key`
881
+ * (one key or an array of keys, positional); `'add'` / `'set'` carry `row` (one row or an array of
882
+ * rows); `'update'` also carries `changes` (a loose partial row); `'records'` / `'count'` /
883
+ * `'aggregate'` carry an optional `criteria` (the SERIALIZED form — `values` is ALWAYS an array,
884
+ * even for a single-value operator, so a caller never chains method calls or guesses arity).
885
+ */
886
+ var databaseToolShape = unionShape(objectShape({
887
+ operation: literalShape(["create"], { description: "Define a new database." }),
888
+ id: stringShape({
889
+ min: 1,
890
+ description: "The database id."
891
+ }),
892
+ tables: tableSpecShape,
893
+ driver: optionalShape(stringShape({
894
+ min: 1,
895
+ description: "The registered driver key. Defaults to \"memory\"."
896
+ })),
897
+ keys: optionalShape(recordShape(stringShape(), { description: "Table name to its primary-key column." }))
898
+ }), objectShape({
899
+ operation: literalShape(["tables"], { description: "List a database's table names." }),
900
+ id: stringShape({
901
+ min: 1,
902
+ description: "The database id."
903
+ })
904
+ }), objectShape({
905
+ operation: literalShape(["get"], { description: "Fetch one or more rows by primary key." }),
906
+ id: stringShape({
907
+ min: 1,
908
+ description: "The database id."
909
+ }),
910
+ table: stringShape({
911
+ min: 1,
912
+ description: "The table name."
913
+ }),
914
+ key: keyShape
915
+ }), objectShape({
916
+ operation: literalShape(["records"], { description: "List rows matching criteria." }),
917
+ id: stringShape({
918
+ min: 1,
919
+ description: "The database id."
920
+ }),
921
+ table: stringShape({
922
+ min: 1,
923
+ description: "The table name."
924
+ }),
925
+ criteria: optionalShape(criteriaShape)
926
+ }), objectShape({
927
+ operation: literalShape(["count"], { description: "Count rows matching criteria." }),
928
+ id: stringShape({
929
+ min: 1,
930
+ description: "The database id."
931
+ }),
932
+ table: stringShape({
933
+ min: 1,
934
+ description: "The table name."
935
+ }),
936
+ criteria: optionalShape(criteriaShape)
937
+ }), objectShape({
938
+ operation: literalShape(["aggregate"], { description: "Compute an aggregate over a column." }),
939
+ id: stringShape({
940
+ min: 1,
941
+ description: "The database id."
942
+ }),
943
+ table: stringShape({
944
+ min: 1,
945
+ description: "The table name."
946
+ }),
947
+ function: literalShape([
948
+ "count",
949
+ "sum",
950
+ "average",
951
+ "minimum",
952
+ "maximum"
953
+ ], { description: "The aggregate function." }),
954
+ column: stringShape({
955
+ min: 1,
956
+ description: "The column to aggregate."
957
+ }),
958
+ criteria: optionalShape(criteriaShape)
959
+ }), objectShape({
960
+ operation: literalShape(["add"], { description: "Insert one or more rows (fails on a duplicate key)." }),
961
+ id: stringShape({
962
+ min: 1,
963
+ description: "The database id."
964
+ }),
965
+ table: stringShape({
966
+ min: 1,
967
+ description: "The table name."
968
+ }),
969
+ row: rowsShape
970
+ }), objectShape({
971
+ operation: literalShape(["set"], { description: "Upsert one or more rows." }),
972
+ id: stringShape({
973
+ min: 1,
974
+ description: "The database id."
975
+ }),
976
+ table: stringShape({
977
+ min: 1,
978
+ description: "The table name."
979
+ }),
980
+ row: rowsShape
981
+ }), objectShape({
982
+ operation: literalShape(["update"], { description: "Patch one or more existing rows." }),
983
+ id: stringShape({
984
+ min: 1,
985
+ description: "The database id."
986
+ }),
987
+ table: stringShape({
988
+ min: 1,
989
+ description: "The table name."
990
+ }),
991
+ key: keyShape,
992
+ changes: rowShape
993
+ }), objectShape({
994
+ operation: literalShape(["remove"], { description: "Delete one or more rows by key." }),
995
+ id: stringShape({
996
+ min: 1,
997
+ description: "The database id."
998
+ }),
999
+ table: stringShape({
1000
+ min: 1,
1001
+ description: "The table name."
1002
+ }),
1003
+ key: keyShape
1004
+ }), objectShape({
1005
+ operation: literalShape(["migrate"], { description: "Replace the table layout in place." }),
1006
+ id: stringShape({
1007
+ min: 1,
1008
+ description: "The database id."
1009
+ }),
1010
+ tables: tableSpecShape
1011
+ }), objectShape({
1012
+ operation: literalShape(["destroy"], { description: "Drop a database entirely." }),
1013
+ id: stringShape({
1014
+ min: 1,
1015
+ description: "The database id."
1016
+ })
1017
+ }));
1018
+ /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
1019
+ 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." }));
1020
+ /** A single row key (not an array) — used by `'link'` / `'unlink'` / `'links'`, which address exactly one owning row. */
1021
+ var singleKeyShape = unionShape(stringShape({ description: "The owning row key." }), numberShape({ description: "The owning row key." }));
1022
+ /** Flat dot-path relation include list, expanded via {@link import('./helpers.js').expandInclude}. */
1023
+ 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." }));
1024
+ /** Which registered relation manager to address — omitted resolves to the sole registered manager. */
1025
+ var managerShape = optionalShape(stringShape({
1026
+ min: 1,
1027
+ description: "Which registered relation manager to address."
1028
+ }));
1029
+ /**
1030
+ * The shape of {@link import('./factories.js').createRelationTool}'s call arguments —
1031
+ * discriminated by `operation` into the 5 relation operations (`'load'` / `'find'` / `'link'` /
1032
+ * `'unlink'` / `'links'`).
1033
+ *
1034
+ * @remarks
1035
+ * `'load'` fetches one or more rows (positional key/array) with `include` attached. `'find'`
1036
+ * fetches rows (pagination / sort only) with `include` attached. `'link'` / `'unlink'` write /
1037
+ * remove a `through` junction row; `'links'` lists a `through` relation's linked keys.
1038
+ */
1039
+ var relationToolShape = unionShape(objectShape({
1040
+ operation: literalShape(["load"], { description: "Fetch one or more rows by key, with related rows attached." }),
1041
+ manager: managerShape,
1042
+ model: stringShape({
1043
+ min: 1,
1044
+ description: "The model (table) name."
1045
+ }),
1046
+ key: relationKeyShape,
1047
+ include: includeShape
1048
+ }), objectShape({
1049
+ operation: literalShape(["find"], { description: "List rows, with related rows attached." }),
1050
+ manager: managerShape,
1051
+ model: stringShape({
1052
+ min: 1,
1053
+ description: "The model (table) name."
1054
+ }),
1055
+ include: includeShape,
1056
+ limit: optionalShape(integerShape({
1057
+ min: 0,
1058
+ description: "Max rows to return."
1059
+ })),
1060
+ offset: optionalShape(integerShape({
1061
+ min: 0,
1062
+ description: "Rows to skip before returning."
1063
+ })),
1064
+ sort: optionalShape(stringShape({
1065
+ min: 1,
1066
+ description: "The column to sort by."
1067
+ })),
1068
+ direction: optionalShape(literalShape(["ascending", "descending"], { description: "The sort direction." }))
1069
+ }), objectShape({
1070
+ operation: literalShape(["link"], { description: "Connect two rows through a \"through\" relation." }),
1071
+ manager: managerShape,
1072
+ model: stringShape({
1073
+ min: 1,
1074
+ description: "The model (table) name."
1075
+ }),
1076
+ key: singleKeyShape,
1077
+ relation: stringShape({
1078
+ min: 1,
1079
+ description: "The \"through\" relation name."
1080
+ }),
1081
+ target: singleKeyShape
1082
+ }), objectShape({
1083
+ operation: literalShape(["unlink"], { description: "Disconnect two rows previously linked through a \"through\" relation." }),
1084
+ manager: managerShape,
1085
+ model: stringShape({
1086
+ min: 1,
1087
+ description: "The model (table) name."
1088
+ }),
1089
+ key: singleKeyShape,
1090
+ relation: stringShape({
1091
+ min: 1,
1092
+ description: "The \"through\" relation name."
1093
+ }),
1094
+ target: singleKeyShape
1095
+ }), objectShape({
1096
+ operation: literalShape(["links"], { description: "List every key linked to a row through a \"through\" relation." }),
1097
+ manager: managerShape,
1098
+ model: stringShape({
1099
+ min: 1,
1100
+ description: "The model (table) name."
1101
+ }),
1102
+ key: singleKeyShape,
1103
+ relation: stringShape({
1104
+ min: 1,
1105
+ description: "The \"through\" relation name."
1106
+ })
1107
+ }));
516
1108
  //#endregion
517
1109
  //#region src/core/helpers.ts
518
1110
  /**
@@ -655,6 +1247,453 @@ function expandSteps(flat) {
655
1247
  phases: flat.steps.map((step) => ({ tasks: [{ run: step.name }] }))
656
1248
  });
657
1249
  }
1250
+ /**
1251
+ * Normalize an LLM-supplied answer `value` to the type {@link PromptType} `form` expects, so a
1252
+ * caller that only ever emits strings can still answer a typed prompt.
1253
+ *
1254
+ * @remarks
1255
+ * `'confirm'` coerces to a `boolean` — a `boolean` passes through, and the strings `'true'` /
1256
+ * `'false'` (case-insensitively) map to it; any other string is truthy-coerced via
1257
+ * `Boolean(value)`. `'checkbox'` coerces to `readonly string[]` — an array passes through
1258
+ * (stringifying each entry), a comma-separated string splits + trims into one, and any other
1259
+ * single (non-comma) string becomes a one-item array. Every other form (`'input'` / `'password'`
1260
+ * / `'select'` / `'editor'`) coerces to a plain `string` — a string passes through verbatim; a
1261
+ * non-string, non-object scalar (`number` / `boolean`) stringifies via `String(value)`; an
1262
+ * object or array (no lossless string form) falls back to `''` rather than serializing garbage.
1263
+ * Pure and total — never throws.
1264
+ *
1265
+ * @param form - The {@link PromptType} the answer is being coerced FOR
1266
+ * @param value - The raw, LLM-supplied answer value
1267
+ * @returns The coerced answer — `boolean` for `'confirm'`, `readonly string[]` for `'checkbox'`,
1268
+ * `string` otherwise
1269
+ */
1270
+ function coerceAnswer(form, value) {
1271
+ if (form === "confirm") {
1272
+ if (typeof value === "boolean") return value;
1273
+ if (typeof value === "string") {
1274
+ const lower = value.trim().toLowerCase();
1275
+ if (lower === "true") return true;
1276
+ if (lower === "false") return false;
1277
+ }
1278
+ return Boolean(value);
1279
+ }
1280
+ if (form === "checkbox") {
1281
+ if (Array.isArray(value)) return value.map((entry) => String(entry));
1282
+ if (typeof value === "string") {
1283
+ if (value.includes(",")) return value.split(",").map((entry) => entry.trim());
1284
+ return [value];
1285
+ }
1286
+ return [String(value)];
1287
+ }
1288
+ if (typeof value === "string") return value;
1289
+ if (typeof value === "object" && value !== null) return "";
1290
+ return String(value);
1291
+ }
1292
+ /**
1293
+ * Map a caught error to the {@link AgentToolErrorCode} the terminal-tool factory should throw
1294
+ * with — the pure classification step of that factory's error handling.
1295
+ *
1296
+ * @remarks
1297
+ * Narrows `error` with {@link isTerminalError} (`@orkestrel/terminal`) first: a non-`TerminalError`
1298
+ * value returns `undefined`, telling the caller this mapper does not apply (rethrow / handle
1299
+ * otherwise). For a genuine `TerminalError`, `'DEADLOCK'` maps to `'DEADLOCK'`, `'EXPIRE'` maps
1300
+ * to `'EXPIRE'`, and every other {@link import('@orkestrel/terminal').TerminalErrorCode}
1301
+ * (`'TARGET'`, `'CANCEL'`, `'DRIVER'`) maps to the generic `'TOOL'` code. The mapper only
1302
+ * classifies — the factory performs the actual throw.
1303
+ *
1304
+ * @param error - The value caught from a terminal-manager operation (`ask` / `answer` / …)
1305
+ * @returns The mapped {@link AgentToolErrorCode}, or `undefined` if `error` is not a `TerminalError`
1306
+ */
1307
+ function terminalToolCode(error) {
1308
+ if (!isTerminalError(error)) return void 0;
1309
+ if (error.code === "DEADLOCK") return "DEADLOCK";
1310
+ if (error.code === "EXPIRE") return "EXPIRE";
1311
+ return "TOOL";
1312
+ }
1313
+ /** Narrow an unknown value to a {@link ColumnSpec} — a valid {@link import('./types.js').ColumnKind} shorthand, or `{ type, optional }` with a valid `type`. */
1314
+ function isColumnSpec(value) {
1315
+ if (isColumnKind(value)) return true;
1316
+ if (!isRecord(value)) return false;
1317
+ return isColumnKind(value.type) && (value.optional === void 0 || typeof value.optional === "boolean");
1318
+ }
1319
+ /** Narrow an unknown value to a {@link import('./types.js').ColumnKind}. */
1320
+ function isColumnKind(value) {
1321
+ return value === "string" || value === "integer" || value === "number" || value === "boolean";
1322
+ }
1323
+ /**
1324
+ * Compile a {@link TableSpec} into the `@orkestrel/database` {@link TablesShape} it configures —
1325
+ * each {@link ColumnSpec} maps to the matching primitive shaper (`'string'` → `stringShape()`,
1326
+ * `'integer'` → `integerShape()`, `'number'` → `numberShape()`, `'boolean'` → `booleanShape()`),
1327
+ * wrapped in `optionalShape` when the column declares `optional: true`. Total, pure.
1328
+ *
1329
+ * @param spec - The small-model-facing table layout
1330
+ * @returns The compiled `TablesShape` a `@orkestrel/database` `createDatabase` call accepts
1331
+ */
1332
+ function expandTables(spec) {
1333
+ const tables = {};
1334
+ for (const [table, definition] of Object.entries(spec)) {
1335
+ const columns = {};
1336
+ for (const [column, kind] of Object.entries(definition.columns)) columns[column] = columnShape(kind);
1337
+ tables[table] = columns;
1338
+ }
1339
+ return tables;
1340
+ }
1341
+ /** Compile one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf {@link expandTables} maps over. */
1342
+ function columnShape(spec) {
1343
+ const kind = isString(spec) ? spec : spec.type;
1344
+ const optional = !isString(spec) && spec.optional === true;
1345
+ const shape = kindShape(kind);
1346
+ return optional ? optionalShape(shape) : shape;
1347
+ }
1348
+ /** Map one {@link import('./types.js').ColumnKind} to its primitive `@orkestrel/database` shape — the leaf {@link columnShape} wraps. */
1349
+ function kindShape(kind) {
1350
+ if (kind === "string") return stringShape();
1351
+ if (kind === "integer") return integerShape();
1352
+ if (kind === "number") return numberShape();
1353
+ return booleanShape();
1354
+ }
1355
+ /**
1356
+ * Narrow an unknown value to a {@link DatabaseDefinition} — a non-empty `id` + `driver`, a
1357
+ * `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, and an optional
1358
+ * `keys` record of strings. The boundary guard a {@link import('./types.js').DefinitionStoreInterface}
1359
+ * applies to an untrusted persisted blob before trusting it as a definition (never an `as`).
1360
+ */
1361
+ function isDatabaseDefinition(value) {
1362
+ if (!isRecord(value)) return false;
1363
+ if (!isNonEmptyString(value.id) || !isNonEmptyString(value.driver)) return false;
1364
+ if (!isRecord(value.tables)) return false;
1365
+ for (const table of Object.values(value.tables)) {
1366
+ if (!isRecord(table) || !isRecord(table.columns)) return false;
1367
+ for (const column of Object.values(table.columns)) if (!isColumnSpec(column)) return false;
1368
+ }
1369
+ if (value.keys !== void 0) {
1370
+ if (!isRecord(value.keys)) return false;
1371
+ for (const key of Object.values(value.keys)) if (!isString(key)) return false;
1372
+ }
1373
+ return true;
1374
+ }
1375
+ /**
1376
+ * Map a caught error to the {@link AgentToolErrorCode} the upcoming database tool should throw
1377
+ * with — the pure classification step of that factory's error handling, mirroring
1378
+ * {@link terminalToolCode}'s idiom for `@orkestrel/database`.
1379
+ *
1380
+ * @param error - The value caught from a `@orkestrel/database` table operation
1381
+ * @returns The granular {@link DatabaseErrorCode}, or `undefined` if `error` is not a `DatabaseError`
1382
+ */
1383
+ function databaseToolCode(error) {
1384
+ return isDatabaseError(error) ? error.code : void 0;
1385
+ }
1386
+ /**
1387
+ * Map a caught error to the {@link AgentToolErrorCode} the upcoming relation tool should throw
1388
+ * with — the pure classification step of that factory's error handling, mirroring
1389
+ * {@link terminalToolCode}'s idiom for `@orkestrel/relation`.
1390
+ *
1391
+ * @param error - The value caught from a `@orkestrel/relation` operation
1392
+ * @returns The granular {@link RelationErrorCode}, or `undefined` if `error` is not a `RelationError`
1393
+ */
1394
+ function relationToolCode(error) {
1395
+ return isRelationError(error) ? error.code : void 0;
1396
+ }
1397
+ /**
1398
+ * Expand the relation tool's FLAT dot-path `include` list into a live `@orkestrel/relation`
1399
+ * {@link Include} tree — the pure leaf {@link import('./factories.js').createRelationTool} calls
1400
+ * before a `'load'` / `'find'` call.
1401
+ *
1402
+ * @remarks
1403
+ * Each path splits on `'.'` into a chain of relation names, deep-merged into one nested
1404
+ * `Include` object with a leaf `true`. A longer path SUBSUMES a shorter sibling's bare `true` —
1405
+ * `'contacts'` followed by `'contacts.account'` yields `{ contacts: { account: true } }`, never
1406
+ * overwriting the deeper chain. An EMPTY segment (`''`, from a leading/trailing/doubled `.`) or a
1407
+ * path whose segment count exceeds `depth` throws a typed `TOOL` {@link AgentToolError}.
1408
+ *
1409
+ * @param paths - The flat dot-path `include` list (or `undefined` — yields `{}`)
1410
+ * @param depth - The max segment count a single path may reach
1411
+ * @returns The equivalent nested {@link Include}
1412
+ *
1413
+ * @example
1414
+ * ```ts
1415
+ * import { expandInclude } from '@src/core'
1416
+ *
1417
+ * expandInclude(['contacts', 'contacts.account'], 3)
1418
+ * // { contacts: { account: true } }
1419
+ * ```
1420
+ */
1421
+ function expandInclude(paths, depth) {
1422
+ function merge(base, segments) {
1423
+ const [head, ...rest] = segments;
1424
+ const existing = base[head];
1425
+ if (rest.length === 0) return {
1426
+ ...base,
1427
+ [head]: existing === void 0 ? true : existing
1428
+ };
1429
+ const nextBase = typeof existing === "object" ? existing : {};
1430
+ return {
1431
+ ...base,
1432
+ [head]: merge(nextBase, rest)
1433
+ };
1434
+ }
1435
+ let include = {};
1436
+ for (const path of paths ?? []) {
1437
+ const segments = path.split(".");
1438
+ if (segments.length > depth || segments.some((segment) => segment.length === 0)) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1439
+ path,
1440
+ depth
1441
+ });
1442
+ include = merge(include, segments);
1443
+ }
1444
+ return include;
1445
+ }
1446
+ /**
1447
+ * Resolve which registered {@link RelationManagerInterface} a relation-tool call addresses — the
1448
+ * pure manager-resolution leaf {@link import('./factories.js').createRelationTool} calls on
1449
+ * every operation.
1450
+ *
1451
+ * @remarks
1452
+ * An explicit `name` must match a key of `managers` (a miss throws a typed `TOOL`
1453
+ * {@link AgentToolError} naming the registered managers). An OMITTED `name` resolves to the sole
1454
+ * registered manager when exactly one is registered, else throws the same typed error.
1455
+ *
1456
+ * @param managers - The tool's registered `RelationManagerInterface` map
1457
+ * @param name - The call's optional `manager` field
1458
+ * @returns The resolved {@link RelationManagerInterface}
1459
+ */
1460
+ function relationManagerOf(managers, name) {
1461
+ if (name !== void 0) {
1462
+ const manager = managers[name];
1463
+ if (manager === void 0) throw new AgentToolError("TOOL", `unknown relation manager '${name}'`, {
1464
+ manager: name,
1465
+ managers: Object.keys(managers)
1466
+ });
1467
+ return manager;
1468
+ }
1469
+ const names = Object.keys(managers);
1470
+ if (names.length === 1) return managers[names[0]];
1471
+ throw new AgentToolError("TOOL", "no relation manager resolved for the call", { managers: names });
1472
+ }
1473
+ /**
1474
+ * Resolve a `model` name against a live {@link RelationManagerInterface} — the pure model-lookup
1475
+ * leaf {@link import('./factories.js').createRelationTool} calls on every operation, mirroring
1476
+ * {@link relationManagerOf}'s guard shape.
1477
+ *
1478
+ * @param manager - The resolved {@link RelationManagerInterface}
1479
+ * @param name - The call's `model` field
1480
+ * @returns The model's {@link ModelInterface}
1481
+ */
1482
+ function relationModelOf(manager, name) {
1483
+ if (!manager.has(name)) throw new AgentToolError("TOOL", `unknown model '${name}'`, {
1484
+ model: name,
1485
+ models: manager.models()
1486
+ });
1487
+ return manager.model(name);
1488
+ }
1489
+ /**
1490
+ * Normalize the database tool's parsed SERIALIZED criteria into a live `@orkestrel/database`
1491
+ * {@link Criteria} — default each condition's OMITTED `connector` to `'and'`.
1492
+ *
1493
+ * @remarks
1494
+ * The wire form ({@link import('./shapers.js').databaseToolShape}) lets a caller drop `connector`
1495
+ * on the last condition (it has nothing to join FORWARD to); the compiled `Condition` a live
1496
+ * `@orkestrel/database` table call accepts always carries one, so this fills the gap. `order` /
1497
+ * `limit` / `offset` pass through unchanged. Pure and total.
1498
+ *
1499
+ * @param criteria - The parsed criteria (or `undefined`)
1500
+ * @returns The equivalent live `Criteria`, or `undefined` when `criteria` is `undefined`
1501
+ */
1502
+ function criteriaOf(criteria) {
1503
+ if (criteria === void 0) return void 0;
1504
+ const conditions = criteria.conditions?.map((condition) => ({
1505
+ ...condition,
1506
+ connector: condition.connector ?? "and"
1507
+ }));
1508
+ return {
1509
+ ...conditions === void 0 ? {} : { conditions },
1510
+ ...criteria.order === void 0 ? {} : { order: criteria.order },
1511
+ ...criteria.limit === void 0 ? {} : { limit: criteria.limit },
1512
+ ...criteria.offset === void 0 ? {} : { offset: criteria.offset }
1513
+ };
1514
+ }
1515
+ /**
1516
+ * Clamp a `'records'` call's criteria to a row cap, and build the PROBE criteria the caller reads
1517
+ * with — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation
1518
+ * uses to detect truncation without a separate `count` round trip.
1519
+ *
1520
+ * @remarks
1521
+ * The effective limit is `min(criteria?.limit ?? cap, cap)`, floored at `0` (so a caller can never
1522
+ * exceed the configured cap by supplying a larger `criteria.limit`). The returned probe criteria
1523
+ * requests ONE MORE row than the effective limit (`limit: effective + 1`) — if storage returns
1524
+ * that many, the caller knows the true result was truncated (`rows.length > effective`) and slices
1525
+ * back down to `effective` before returning.
1526
+ *
1527
+ * @example
1528
+ * ```ts
1529
+ * import { clampCriteria } from '@src/core'
1530
+ *
1531
+ * const { criteria, limit } = clampCriteria(undefined, 100)
1532
+ * // limit === 100, criteria.limit === 101 — a probe fetching one extra row
1533
+ * const rows = await table.records(criteria)
1534
+ * const truncated = rows.length > limit // true when storage had more than `limit` rows
1535
+ * ```
1536
+ *
1537
+ * @param criteria - The live criteria to clamp (or `undefined`)
1538
+ * @param cap - The row-count ceiling
1539
+ * @returns The PROBE criteria (`limit` bumped by one) and the effective `limit`
1540
+ */
1541
+ function clampCriteria(criteria, cap) {
1542
+ const limit = Math.max(0, Math.min(criteria?.limit ?? cap, cap));
1543
+ return {
1544
+ criteria: {
1545
+ ...criteria,
1546
+ limit: limit + 1
1547
+ },
1548
+ limit
1549
+ };
1550
+ }
1551
+ /** Map a column NAME + its live `@orkestrel/database` `ContractShape` to a {@link ColumnSchema} — the leaf {@link tableSchema} maps over. */
1552
+ function columnSchema(name, shape) {
1553
+ return {
1554
+ name,
1555
+ type: shapeToColumnType(shape),
1556
+ nullable: shape.type === "optional" || shape.type === "nullable"
1557
+ };
1558
+ }
1559
+ /**
1560
+ * Build one {@link TableSchema} from a table NAME and its `@orkestrel/database` `TableExport` —
1561
+ * the "deployed" schema shape `DatabaseInterface.migrate` diffs against, derived from a LIVE
1562
+ * handle's `export()` rather than a re-declared {@link TableSpec}, so it works for ANY handle
1563
+ * (config-tracked or caller-supplied).
1564
+ *
1565
+ * @param name - The table name
1566
+ * @param table - The table's `TableExport` (`{ key, columns }`, `@orkestrel/database`)
1567
+ * @returns The equivalent {@link TableSchema} (`indexes` empty — this package declares none)
1568
+ */
1569
+ function tableSchema(name, table) {
1570
+ return {
1571
+ name,
1572
+ primary: table.key,
1573
+ columns: Object.entries(table.columns).map(([column, shape]) => columnSchema(column, shape)),
1574
+ indexes: []
1575
+ };
1576
+ }
1577
+ //#endregion
1578
+ //#region src/core/stores/MemoryDefinitionStore.ts
1579
+ /**
1580
+ * The in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of
1581
+ * {@link DatabaseDefinition}s keyed by database id, the DEFAULT store
1582
+ * {@link import('../factories.js').createMemoryDefinitionStore} builds. The EXACT twin of
1583
+ * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}.
1584
+ *
1585
+ * @remarks
1586
+ * A plain `Map<string, DatabaseDefinition>` (AGENTS §21 — the definition is already pure,
1587
+ * self-contained CONFIG-only JSON, so no encoding is needed for the memory tier). There is NO
1588
+ * idle-TTL and NO eviction: a persisted definition lives until an explicit `delete`. A durable
1589
+ * backend (JSON / SQLite / IndexedDB) swaps in through the SAME interface without touching a
1590
+ * consumer — its driver-pluggable twin is
1591
+ * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore} (the definition as one
1592
+ * opaque JSON column).
1593
+ *
1594
+ * - **`get` resolves the persisted definition for an id**, or `undefined` if none is stored.
1595
+ * - **`set` inserts / replaces under the definition's OWN `id`** (no separate id param).
1596
+ * - **`delete` drops a definition by id**; an absent id is a no-op (no throw).
1597
+ *
1598
+ * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1599
+ * bijection with {@link DefinitionStoreInterface}).
1600
+ *
1601
+ * @example
1602
+ * ```ts
1603
+ * import { createMemoryDefinitionStore } from '@src/core'
1604
+ *
1605
+ * const store = createMemoryDefinitionStore()
1606
+ * await store.set({ id: 'shop', driver: 'memory', tables: {} })
1607
+ * const definition = await store.get('shop')
1608
+ * await store.delete('shop')
1609
+ * ```
1610
+ */
1611
+ var MemoryDefinitionStore = class {
1612
+ #definitions = /* @__PURE__ */ new Map();
1613
+ get(id) {
1614
+ return Promise.resolve(this.#definitions.get(id));
1615
+ }
1616
+ set(definition) {
1617
+ this.#definitions.set(definition.id, definition);
1618
+ return Promise.resolve();
1619
+ }
1620
+ delete(id) {
1621
+ this.#definitions.delete(id);
1622
+ return Promise.resolve();
1623
+ }
1624
+ };
1625
+ //#endregion
1626
+ //#region src/core/stores/DatabaseDefinitionStore.ts
1627
+ /**
1628
+ * A {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database` layer — a
1629
+ * database's durable CONFIG state IS a row, so persistence reduces to keyed point-access
1630
+ * (`get` / `set` / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the
1631
+ * plain-`Map` {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}.
1632
+ *
1633
+ * @remarks
1634
+ * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
1635
+ * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /
1636
+ * IndexedDB backend swaps in WITHOUT touching a consumer — the same seam as
1637
+ * {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}. The driver defaults to
1638
+ * memory ({@link import('../factories.js').createDatabaseDefinitionStore} passes
1639
+ * `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the durable
1640
+ * plumbing by passing a JSON / SQLite / IndexedDB driver.
1641
+ *
1642
+ * The {@link DatabaseDefinition} is stored as ONE OPAQUE JSON COLUMN — the table is a row of
1643
+ * `{ id; definition }` ({@link DatabaseDefinitionRow}). The definition is already a COMPLETE,
1644
+ * self-contained, pure-JSON CONFIG payload (never a live handle), so storing it whole is lossless
1645
+ * AND keeps the row type flat (`definition` reads back as `unknown`).
1646
+ *
1647
+ * - **`set(definition)` upserts under the definition's OWN `id`** (no separate id param) — it
1648
+ * writes the row `{ id: definition.id, definition }`.
1649
+ * - **`get(id)` resolves the stored definition for an id**, narrowing the opaque JSON column back
1650
+ * to a {@link DatabaseDefinition} ({@link import('../helpers.js').isDatabaseDefinition} — the
1651
+ * AGENTS §14 boundary narrow for an untrusted storage read), or `undefined` if none is stored
1652
+ * or the stored blob is malformed.
1653
+ * - **`delete(id)` drops a definition by id**; an absent id is a no-op (no throw).
1654
+ *
1655
+ * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1656
+ * bijection with {@link DefinitionStoreInterface}).
1657
+ *
1658
+ * @example
1659
+ * ```ts
1660
+ * import { createDatabaseDefinitionStore, createMemoryDriver } from '@src/core'
1661
+ *
1662
+ * const store = createDatabaseDefinitionStore(createMemoryDriver()) // a durable driver swaps in here
1663
+ * await store.set({ id: 'shop', driver: 'memory', tables: {} }) // persist the config (one JSON column)
1664
+ * const definition = await store.get('shop')
1665
+ * await store.delete('shop')
1666
+ * ```
1667
+ */
1668
+ var DatabaseDefinitionStore = class {
1669
+ #table;
1670
+ /**
1671
+ * Wrap a table as a definition store.
1672
+ *
1673
+ * @param table - The {@link TableInterface} holding the definitions — its row is the
1674
+ * {@link DatabaseDefinitionRow} `{ id; definition }` shape (the definition one opaque JSON column)
1675
+ */
1676
+ constructor(table) {
1677
+ this.#table = table;
1678
+ }
1679
+ /** Resolve the persisted definition for `id`, narrowing the opaque JSON column back to a `DatabaseDefinition`. */
1680
+ async get(id) {
1681
+ const row = await this.#table.get(id);
1682
+ if (row === void 0) return void 0;
1683
+ return isDatabaseDefinition(row.definition) ? row.definition : void 0;
1684
+ }
1685
+ /** Insert or replace under the definition's OWN `id` (no separate id param) — the row is `{ id, definition }`. */
1686
+ async set(definition) {
1687
+ await this.#table.set({
1688
+ id: definition.id,
1689
+ definition
1690
+ });
1691
+ }
1692
+ /** Drop a definition by id; an absent id is a no-op (no throw). */
1693
+ async delete(id) {
1694
+ await this.#table.remove(id);
1695
+ }
1696
+ };
658
1697
  //#endregion
659
1698
  //#region src/core/factories.ts
660
1699
  /**
@@ -1193,7 +2232,594 @@ function createDescribeTool(tools) {
1193
2232
  }
1194
2233
  });
1195
2234
  }
2235
+ /**
2236
+ * Build an LLM-callable prompt tool — the ASK side of the terminal seam. Asks
2237
+ * {@link import('./types.js').PromptToolOptions.to} a question and BLOCKS until it answers,
2238
+ * returning the resolved answer value.
2239
+ *
2240
+ * @remarks
2241
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2242
+ * {@link import('./shapers.js').promptToolShape}, dispatches to the matching
2243
+ * `TerminalManagerInterface.ask` overload (`@orkestrel/terminal`) for the call's `form`, and
2244
+ * RETURNS the resolved answer on success. `from` is FIXED at construction
2245
+ * ({@link import('./types.js').PromptToolOptions.from}) — never read from the model-supplied
2246
+ * args — so a model cannot spoof which terminal is asking. A prompt CYCLE rejects with
2247
+ * `TerminalError('DEADLOCK')`, re-surfaced as a typed `DEADLOCK`
2248
+ * {@link import('./errors.js').AgentToolError}; an expired prompt re-surfaces as `EXPIRE`; an
2249
+ * unknown `to` (or any other `TerminalError`) re-surfaces as `TOOL`, naming the unknown terminal
2250
+ * plus the known ones (`manager.terminals()`).
2251
+ *
2252
+ * @param options - The live manager, the fixed `from` identity, and advertised overrides (see
2253
+ * {@link import('./types.js').PromptToolOptions})
2254
+ * @returns A `ToolInterface` (named {@link import('./constants.js').PROMPT_TOOL_NAME} by default)
2255
+ *
2256
+ * @example
2257
+ * ```ts
2258
+ * import { createPromptTool } from '@src/core'
2259
+ * import { createTerminalManager, createToolManager } from '@orkestrel/terminal'
2260
+ *
2261
+ * const manager = createTerminalManager()
2262
+ * manager.add('agent')
2263
+ * manager.add('reviewer')
2264
+ * const tool = createPromptTool({ manager, from: 'agent' })
2265
+ * const tools = createToolManager()
2266
+ * tools.add(tool) // the agent can now ask 'reviewer' and block for the answer
2267
+ * ```
2268
+ */
2269
+ function createPromptTool(options) {
2270
+ const contract = createContract(promptToolShape);
2271
+ const parameters = schemaToParameters(contract.schema);
2272
+ return createTool({
2273
+ name: options.name ?? "ask",
2274
+ description: options.description ?? PROMPT_TOOL_DESCRIPTION,
2275
+ summary: PROMPT_TOOL_SUMMARY,
2276
+ parameters,
2277
+ execute: async (args) => {
2278
+ const call = contract.parse(args);
2279
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed ask call", { args });
2280
+ if ((call.form === "select" || call.form === "checkbox") && (call.choices ?? []).length === 0) throw new AgentToolError("TOOL", "select/checkbox requires at least one choice", {
2281
+ to: call.to,
2282
+ form: call.form
2283
+ });
2284
+ try {
2285
+ switch (call.form) {
2286
+ case "input": return await options.manager.ask(options.from, call.to, call.form, {
2287
+ message: call.message,
2288
+ ...call.default === void 0 ? {} : { default: call.default },
2289
+ ...call.validate === void 0 ? {} : { validate: call.validate }
2290
+ });
2291
+ case "editor": return await options.manager.ask(options.from, call.to, call.form, {
2292
+ message: call.message,
2293
+ ...call.default === void 0 ? {} : { default: call.default },
2294
+ ...call.validate === void 0 ? {} : { validate: call.validate }
2295
+ });
2296
+ case "password": return await options.manager.ask(options.from, call.to, call.form, {
2297
+ message: call.message,
2298
+ ...call.mask === void 0 ? {} : { mask: call.mask },
2299
+ ...call.validate === void 0 ? {} : { validate: call.validate }
2300
+ });
2301
+ case "confirm": return await options.manager.ask(options.from, call.to, call.form, {
2302
+ message: call.message,
2303
+ ...call.default === void 0 ? {} : { default: call.default === "true" }
2304
+ });
2305
+ case "select": return await options.manager.ask(options.from, call.to, call.form, {
2306
+ message: call.message,
2307
+ choices: call.choices ?? [],
2308
+ ...call.default === void 0 ? {} : { default: call.default }
2309
+ });
2310
+ case "checkbox": return await options.manager.ask(options.from, call.to, call.form, {
2311
+ message: call.message,
2312
+ choices: call.choices ?? [],
2313
+ ...call.min === void 0 ? {} : { min: call.min },
2314
+ ...call.max === void 0 ? {} : { max: call.max }
2315
+ });
2316
+ }
2317
+ } catch (error) {
2318
+ const code = terminalToolCode(error);
2319
+ if (code === void 0) throw error;
2320
+ if (code === "DEADLOCK") throw new AgentToolError("DEADLOCK", `asking '${call.to}' would form a prompt cycle`, isTerminalError(error) ? error.context : {
2321
+ from: options.from,
2322
+ to: call.to
2323
+ });
2324
+ if (code === "EXPIRE") throw new AgentToolError("EXPIRE", `prompt to '${call.to}' expired before it was answered`, { to: call.to });
2325
+ if (isTerminalError(error) && error.code === "TARGET") throw new AgentToolError("TOOL", `unknown terminal '${call.to}'`, {
2326
+ to: call.to,
2327
+ known: options.manager.terminals()
2328
+ });
2329
+ throw new AgentToolError("TOOL", `asking '${call.to}' failed`, { to: call.to });
2330
+ }
2331
+ }
2332
+ });
2333
+ }
2334
+ /**
2335
+ * Build an LLM-callable answer tool — the ANSWER side of the terminal seam. Lists the prompts
2336
+ * currently addressed to {@link import('./types.js').AnswerToolOptions.to}, or answers one of
2337
+ * them by id.
2338
+ *
2339
+ * @remarks
2340
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2341
+ * {@link import('./shapers.js').answerToolShape} (discriminated by `operation`). `'pending'`
2342
+ * returns a compact list (`{ id, from, form, message }`) of every prompt currently addressed to
2343
+ * `to` (`TerminalManagerInterface.pending`, `@orkestrel/terminal`). `'answer'` looks the prompt
2344
+ * up by `id` (an unknown id throws a typed `ANSWER` {@link import('./errors.js').AgentToolError}),
2345
+ * normalizes the model-supplied `value` to the prompt's own form
2346
+ * ({@link import('./helpers.js').coerceAnswer}), and applies it via
2347
+ * `TerminalManagerInterface.answer` — a rejected / unknown / unresolvable outcome
2348
+ * (`TerminalAnswerResult.error`) re-surfaces as a typed `ANSWER` `AgentToolError`; success returns
2349
+ * `{ answered: id }`. `to` is FIXED at construction
2350
+ * ({@link import('./types.js').AnswerToolOptions.to}) — never read from the model-supplied args —
2351
+ * so a model cannot spoof which terminal it is answering for. Concurrent answerers racing on one
2352
+ * endpoint are FIRST-WRITE-WINS — a late answer to an already-settled prompt returns a typed
2353
+ * `ANSWER` `AgentToolError` (surfaced as a 422 over HTTP).
2354
+ *
2355
+ * @param options - The live manager, the fixed `to` identity, and advertised overrides (see
2356
+ * {@link import('./types.js').AnswerToolOptions})
2357
+ * @returns A `ToolInterface` (named {@link import('./constants.js').ANSWER_TOOL_NAME} by default)
2358
+ *
2359
+ * @example
2360
+ * ```ts
2361
+ * import { createAnswerTool } from '@src/core'
2362
+ * import { createTerminalManager, createToolManager } from '@orkestrel/terminal'
2363
+ *
2364
+ * const manager = createTerminalManager()
2365
+ * manager.add('reviewer')
2366
+ * const tool = createAnswerTool({ manager, to: 'reviewer' })
2367
+ * const tools = createToolManager()
2368
+ * tools.add(tool) // the reviewer terminal can now list/answer prompts addressed to it
2369
+ * ```
2370
+ */
2371
+ function createAnswerTool(options) {
2372
+ const contract = createContract(answerToolShape);
2373
+ const parameters = schemaToParameters(contract.schema);
2374
+ return createTool({
2375
+ name: options.name ?? "answer",
2376
+ description: options.description ?? ANSWER_TOOL_DESCRIPTION,
2377
+ summary: ANSWER_TOOL_SUMMARY,
2378
+ parameters,
2379
+ execute: async (args) => {
2380
+ const call = contract.parse(args);
2381
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed answer call", { args });
2382
+ if (call.operation === "pending") return options.manager.pending(options.to).map((prompt) => ({
2383
+ id: prompt.id,
2384
+ from: prompt.from,
2385
+ form: prompt.form,
2386
+ message: prompt.message
2387
+ }));
2388
+ const prompt = options.manager.pending(options.to).find((entry) => entry.id === call.id);
2389
+ if (prompt === void 0) throw new AgentToolError("ANSWER", `unknown prompt '${call.id}'`, {
2390
+ id: call.id,
2391
+ reason: "unknown"
2392
+ });
2393
+ const coerced = coerceAnswer(prompt.form, call.value);
2394
+ const result = options.manager.answer(options.to, call.id, coerced);
2395
+ if (!result.success) throw new AgentToolError("ANSWER", `failed to answer prompt '${call.id}': ${result.error}`, {
2396
+ id: call.id,
2397
+ reason: result.error
2398
+ });
2399
+ return { answered: call.id };
2400
+ }
2401
+ });
2402
+ }
2403
+ /**
2404
+ * Create the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database
2405
+ * definitions, the DEFAULT store the upcoming database / relation tools will persist their
2406
+ * `DatabaseDefinition` configs through.
2407
+ *
2408
+ * @returns A {@link DefinitionStoreInterface}
2409
+ *
2410
+ * @example
2411
+ * ```ts
2412
+ * import { createMemoryDefinitionStore } from '@src/core'
2413
+ *
2414
+ * const store = createMemoryDefinitionStore()
2415
+ * ```
2416
+ */
2417
+ function createMemoryDefinitionStore() {
2418
+ return new MemoryDefinitionStore();
2419
+ }
2420
+ /**
2421
+ * Create a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database`
2422
+ * layer — the driver-pluggable twin of {@link createMemoryDefinitionStore}, storing each
2423
+ * database's definition as one opaque JSON column.
2424
+ *
2425
+ * @param driver - The {@link DriverInterface} backing the table (default an in-memory driver)
2426
+ * @returns A {@link DefinitionStoreInterface}
2427
+ *
2428
+ * @example
2429
+ * ```ts
2430
+ * import { createDatabaseDefinitionStore } from '@src/core'
2431
+ *
2432
+ * const store = createDatabaseDefinitionStore() // in-memory by default
2433
+ * ```
2434
+ */
2435
+ function createDatabaseDefinitionStore(driver = createMemoryDriver()) {
2436
+ return new DatabaseDefinitionStore(createDatabase({
2437
+ driver,
2438
+ tables: { definitions: {
2439
+ id: stringShape(),
2440
+ definition: rawShape({})
2441
+ } }
2442
+ }).table("definitions"));
2443
+ }
2444
+ /**
2445
+ * Build an LLM-callable database tool — create, query, and mutate `@orkestrel/database`
2446
+ * databases through one `operation`-discriminated call (AGENTS §14, matching
2447
+ * {@link createWorkspaceTool}'s single-tool-many-operations shape).
2448
+ *
2449
+ * @remarks
2450
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2451
+ * {@link import('./shapers.js').databaseToolShape}, dispatches to the matching operation, and
2452
+ * RETURNS a plain result on success. A database is resolved lazily and cached for the tool's
2453
+ * lifetime — `'create'` mints one from `tables` ({@link import('./helpers.js').expandTables}) and
2454
+ * a registered `driver` key ({@link import('./types.js').DatabaseToolOptions.drivers}, default
2455
+ * `{ memory: () => createMemoryDriver() }`); any other operation addressing an uncached id falls
2456
+ * back to {@link import('./types.js').DatabaseToolOptions.store} (an unknown id throws a typed
2457
+ * `TOOL` {@link import('./errors.js').AgentToolError}). When a `store` is configured, `'create'`
2458
+ * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.
2459
+ *
2460
+ * `'migrate'` re-declares a LIVE handle's tables via `DatabaseInterface.import` (the SAME driver
2461
+ * and storage, a NEW typed view) and calls its `migrate` against the OLD deployed schema —
2462
+ * derived from the handle's OWN `export()` (via {@link import('./helpers.js').tableSchema}), so it
2463
+ * works for any handle, config-tracked or caller-supplied via
2464
+ * {@link import('./types.js').DatabaseToolOptions.databases}. `'records'` clamps its `criteria` to
2465
+ * {@link import('./types.js').DatabaseToolOptions.limit} (default
2466
+ * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) via
2467
+ * {@link import('./helpers.js').clampCriteria}, reporting `truncated` when storage held more rows
2468
+ * than the cap. Every operation's `criteria` is normalized via
2469
+ * {@link import('./helpers.js').criteriaOf} (defaults an omitted condition `connector` to `'and'`).
2470
+ * When {@link import('./types.js').DatabaseToolOptions.readonly} is `true`, every mutating
2471
+ * operation throws a typed `TOOL` `AgentToolError` before doing anything. When
2472
+ * {@link import('./types.js').DatabaseToolOptions.timeout} is set, every `@orkestrel/database` call
2473
+ * this tool makes is given a fresh `AbortSignal.timeout(timeout)`. A typed `@orkestrel/database`
2474
+ * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `AgentToolError` carrying the
2475
+ * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`
2476
+ * ({@link import('./helpers.js').databaseToolCode}); an `AgentToolError` thrown by this tool's own
2477
+ * guards passes through unwrapped.
2478
+ *
2479
+ * A lazily re-minted database over the DEFAULT in-memory driver yields an EMPTY database — only
2480
+ * the {@link import('./types.js').DatabaseDefinition} schema persists in `store`, never rows;
2481
+ * durable rows need a persistent driver factory registered in
2482
+ * {@link import('./types.js').DatabaseToolOptions.drivers}. `'destroy'` closes whatever handle is
2483
+ * cached for the id, including an embedder-supplied
2484
+ * {@link import('./types.js').DatabaseToolOptions.databases} handle — the embedder relinquishes
2485
+ * that handle's lifecycle to this tool for any id it wires in. This tool assumes the
2486
+ * single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent calls
2487
+ * against one id are NOT serialized by this tool. `'get'` is uncapped by
2488
+ * {@link import('./types.js').DatabaseToolOptions.limit} (bounded only by the caller's `key` array
2489
+ * size), unlike `'records'` / `'find'` / `'links'`.
2490
+ *
2491
+ * @param options - The tool's configuration (see {@link import('./types.js').DatabaseToolOptions})
2492
+ * @returns A `ToolInterface` (named {@link import('./constants.js').DATABASE_TOOL_NAME} by default)
2493
+ *
2494
+ * @example
2495
+ * ```ts
2496
+ * import { createDatabaseTool } from '@src/core'
2497
+ *
2498
+ * const tool = createDatabaseTool()
2499
+ * await tool.execute({
2500
+ * operation: 'create',
2501
+ * id: 'shop',
2502
+ * tables: { products: { columns: { name: 'string', price: 'number' } } },
2503
+ * })
2504
+ * ```
2505
+ */
2506
+ function createDatabaseTool(options = {}) {
2507
+ const contract = createContract(databaseToolShape);
2508
+ const parameters = schemaToParameters(contract.schema);
2509
+ const handles = new Map(Object.entries(options.databases ?? {}));
2510
+ const definitions = /* @__PURE__ */ new Map();
2511
+ const drivers = options.drivers ?? { memory: () => createMemoryDriver() };
2512
+ const key = options.key ?? generateUUID;
2513
+ const cap = options.limit ?? 1e3;
2514
+ const store = options.store;
2515
+ async function resolve(id) {
2516
+ const cached = handles.get(id);
2517
+ if (cached !== void 0) return cached;
2518
+ if (store !== void 0) {
2519
+ const definition = await store.get(id);
2520
+ if (definition !== void 0) {
2521
+ const factory = drivers[definition.driver];
2522
+ if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${definition.driver}'`, {
2523
+ id,
2524
+ driver: definition.driver
2525
+ });
2526
+ const handle = createDatabase({
2527
+ driver: factory(),
2528
+ tables: expandTables(definition.tables),
2529
+ ...definition.keys === void 0 ? {} : { keys: definition.keys },
2530
+ key
2531
+ });
2532
+ handles.set(id, handle);
2533
+ definitions.set(id, definition);
2534
+ return handle;
2535
+ }
2536
+ }
2537
+ throw new AgentToolError("TOOL", `unknown database '${id}'`, { id });
2538
+ }
2539
+ return createTool({
2540
+ name: options.name ?? "database",
2541
+ description: options.description ?? DATABASE_TOOL_DESCRIPTION,
2542
+ summary: DATABASE_TOOL_SUMMARY,
2543
+ parameters,
2544
+ execute: async (args) => {
2545
+ const call = contract.parse(args);
2546
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed database call", { args });
2547
+ 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 });
2548
+ const read = options.timeout === void 0 ? void 0 : { signal: AbortSignal.timeout(options.timeout) };
2549
+ try {
2550
+ switch (call.operation) {
2551
+ case "create": {
2552
+ if (handles.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 });
2553
+ const name = call.driver ?? "memory";
2554
+ const factory = drivers[name];
2555
+ if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${name}'`, {
2556
+ id: call.id,
2557
+ driver: name
2558
+ });
2559
+ const tables = call.tables;
2560
+ const keys = call.keys;
2561
+ const handle = createDatabase({
2562
+ driver: factory(),
2563
+ tables: expandTables(tables),
2564
+ ...keys === void 0 ? {} : { keys },
2565
+ key
2566
+ });
2567
+ handles.set(call.id, handle);
2568
+ const definition = {
2569
+ id: call.id,
2570
+ driver: name,
2571
+ tables,
2572
+ ...keys === void 0 ? {} : { keys }
2573
+ };
2574
+ definitions.set(call.id, definition);
2575
+ if (store !== void 0) await store.set(definition);
2576
+ return {
2577
+ id: call.id,
2578
+ tables: Object.keys(tables)
2579
+ };
2580
+ }
2581
+ case "tables": {
2582
+ const handle = await resolve(call.id);
2583
+ return { tables: Object.keys(handle.export()).map((name) => {
2584
+ const table = handle.table(name);
2585
+ return {
2586
+ name,
2587
+ primary: table.primary,
2588
+ columns: table.contract.schema
2589
+ };
2590
+ }) };
2591
+ }
2592
+ case "get": {
2593
+ const table = (await resolve(call.id)).table(call.table);
2594
+ const many = Array.isArray(call.key);
2595
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2596
+ const rows = await table.get(keys);
2597
+ return many ? { rows } : { row: rows[0] };
2598
+ }
2599
+ case "records": {
2600
+ const table = (await resolve(call.id)).table(call.table);
2601
+ const { criteria: probe, limit } = clampCriteria(criteriaOf(call.criteria), cap);
2602
+ const rows = await table.records(probe, read);
2603
+ const truncated = rows.length > limit;
2604
+ const sliced = rows.slice(0, limit);
2605
+ return {
2606
+ rows: sliced,
2607
+ count: sliced.length,
2608
+ truncated,
2609
+ limit
2610
+ };
2611
+ }
2612
+ case "count": return { count: await (await resolve(call.id)).table(call.table).count(criteriaOf(call.criteria), read) };
2613
+ case "aggregate": return { value: await (await resolve(call.id)).table(call.table).aggregate(call.function, call.column, criteriaOf(call.criteria), read) };
2614
+ case "add": {
2615
+ const table = (await resolve(call.id)).table(call.table);
2616
+ const many = Array.isArray(call.row);
2617
+ const rows = Array.isArray(call.row) ? call.row : [call.row];
2618
+ const keys = await table.add(rows, read);
2619
+ return many ? { keys } : { key: keys[0] };
2620
+ }
2621
+ case "set": {
2622
+ const table = (await resolve(call.id)).table(call.table);
2623
+ const many = Array.isArray(call.row);
2624
+ const rows = Array.isArray(call.row) ? call.row : [call.row];
2625
+ const keys = await table.set(rows, read);
2626
+ return many ? { keys } : { key: keys[0] };
2627
+ }
2628
+ case "update": {
2629
+ const table = (await resolve(call.id)).table(call.table);
2630
+ const changes = call.changes;
2631
+ const many = Array.isArray(call.key);
2632
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2633
+ const updated = await table.update(keys, changes, read);
2634
+ return many ? { updated } : { updated: updated[0] };
2635
+ }
2636
+ case "remove": {
2637
+ const table = (await resolve(call.id)).table(call.table);
2638
+ const many = Array.isArray(call.key);
2639
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2640
+ const removed = await table.remove(keys, read);
2641
+ return many ? { removed } : { removed: removed[0] };
2642
+ }
2643
+ case "migrate": {
2644
+ const handle = await resolve(call.id);
2645
+ const previous = handle.export();
2646
+ const deployed = Object.entries(previous).map(([name, table]) => tableSchema(name, table));
2647
+ const tables = call.tables;
2648
+ const keys = {};
2649
+ for (const name of Object.keys(tables)) {
2650
+ const existing = previous[name];
2651
+ if (existing !== void 0) keys[name] = existing.key;
2652
+ }
2653
+ const declared = expandTables(tables);
2654
+ const migrated = handle.import(declared, Object.keys(keys).length > 0 ? keys : void 0);
2655
+ const migration = await migrated.migrate(deployed, read);
2656
+ handles.set(call.id, migrated);
2657
+ const tracked = definitions.get(call.id);
2658
+ if (tracked !== void 0) {
2659
+ const updated = {
2660
+ id: call.id,
2661
+ driver: tracked.driver,
2662
+ tables,
2663
+ ...Object.keys(keys).length > 0 ? { keys } : {}
2664
+ };
2665
+ definitions.set(call.id, updated);
2666
+ if (store !== void 0) await store.set(updated);
2667
+ }
2668
+ return { migration };
2669
+ }
2670
+ case "destroy": {
2671
+ const cached = handles.get(call.id);
2672
+ const persisted = store !== void 0 && cached === void 0 ? await store.get(call.id) !== void 0 : false;
2673
+ if (cached !== void 0) {
2674
+ await cached.close();
2675
+ handles.delete(call.id);
2676
+ }
2677
+ definitions.delete(call.id);
2678
+ if (store !== void 0) await store.delete(call.id);
2679
+ return {
2680
+ id: call.id,
2681
+ destroyed: cached !== void 0 || persisted
2682
+ };
2683
+ }
2684
+ }
2685
+ } catch (error) {
2686
+ if (isAgentToolError(error)) throw error;
2687
+ const code = databaseToolCode(error);
2688
+ if (code === void 0) throw error;
2689
+ throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
2690
+ code,
2691
+ operation: call.operation,
2692
+ id: call.id,
2693
+ ..."table" in call ? { table: call.table } : {}
2694
+ });
2695
+ }
2696
+ }
2697
+ });
2698
+ }
2699
+ /**
2700
+ * Build an LLM-callable relation tool — traverse and edit `@orkestrel/relation` relationships
2701
+ * through one `operation`-discriminated call (AGENTS §14, matching {@link createDatabaseTool}'s
2702
+ * single-tool-many-operations shape).
2703
+ *
2704
+ * @remarks
2705
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2706
+ * {@link import('./shapers.js').relationToolShape}, resolves the addressed
2707
+ * {@link import('@orkestrel/relation').RelationManagerInterface} — an explicit `manager` field
2708
+ * must match a key of {@link import('./types.js').RelationToolOptions.managers}, an OMITTED one
2709
+ * resolves to the SOLE registered manager, either miss throwing a typed `TOOL`
2710
+ * {@link import('./errors.js').AgentToolError}
2711
+ * ({@link import('./helpers.js').relationManagerOf}) — then resolves `model` against it
2712
+ * ({@link import('./helpers.js').relationModelOf}, same typed-`TOOL`-on-miss shape), and
2713
+ * dispatches to the matched operation, RETURNING a plain result on success.
2714
+ *
2715
+ * `'load'` / `'find'` expand the call's FLAT dot-path `include` list into a live
2716
+ * `@orkestrel/relation` `Include` tree via {@link import('./helpers.js').expandInclude}, capped
2717
+ * at {@link import('./types.js').RelationToolOptions.depth} (default
2718
+ * {@link import('./constants.js').RELATION_TOOL_DEPTH}) — a path exceeding the cap, or carrying an
2719
+ * empty segment, throws a typed `TOOL` error. `'load'` dispatches on whether `key` is an array
2720
+ * (positional many-key form, AGENTS §9.2) or a single key. `'find'` and `'links'` clamp their
2721
+ * result to {@link import('./types.js').RelationToolOptions.limit} (default
2722
+ * {@link import('./constants.js').RELATION_TOOL_LIMIT}) — `'find'` probes one row past the
2723
+ * effective limit (mirroring {@link import('./helpers.js').clampCriteria}'s idiom) to report
2724
+ * `truncated`; `'links'` (which has no upstream pagination) fetches the FULL linked-key list and
2725
+ * slices/truncates it the same way. `'link'` / `'unlink'` write / remove one `through` junction
2726
+ * row.
2727
+ *
2728
+ * A typed `@orkestrel/relation` failure (`RelationError`) re-surfaces as a typed `RELATION`
2729
+ * `AgentToolError` carrying the original {@link import('@orkestrel/relation').RelationErrorCode}
2730
+ * in `context.code`; a typed `@orkestrel/database` failure underneath it (`DatabaseError`)
2731
+ * re-surfaces as a typed `DATABASE` `AgentToolError`, mirroring {@link createDatabaseTool}'s error
2732
+ * mapping; an `AgentToolError` thrown by this tool's own guards (malformed args, an unknown
2733
+ * manager/model) passes through unwrapped.
2734
+ *
2735
+ * @param options - The tool's configuration (see {@link import('./types.js').RelationToolOptions})
2736
+ * @returns A `ToolInterface` (named {@link import('./constants.js').RELATION_TOOL_NAME} by default)
2737
+ *
2738
+ * @example
2739
+ * ```ts
2740
+ * import { createRelationTool } from '@src/core'
2741
+ *
2742
+ * const tool = createRelationTool({ managers: { shop: manager } })
2743
+ * await tool.execute({ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] })
2744
+ * ```
2745
+ */
2746
+ function createRelationTool(options) {
2747
+ const contract = createContract(relationToolShape);
2748
+ const parameters = schemaToParameters(contract.schema);
2749
+ const depth = options.depth ?? 3;
2750
+ const cap = options.limit ?? 1e3;
2751
+ return createTool({
2752
+ name: options.name ?? "relation",
2753
+ description: options.description ?? RELATION_TOOL_DESCRIPTION,
2754
+ summary: RELATION_TOOL_SUMMARY,
2755
+ parameters,
2756
+ execute: async (args) => {
2757
+ const call = contract.parse(args);
2758
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed relation call", { args });
2759
+ try {
2760
+ const model = relationModelOf(relationManagerOf(options.managers, call.manager), call.model);
2761
+ switch (call.operation) {
2762
+ case "load": {
2763
+ const include = expandInclude(call.include, depth);
2764
+ if (typeof call.key === "string" || typeof call.key === "number") return { row: await model.load(call.key, include) };
2765
+ return { rows: await model.load(call.key, include) };
2766
+ }
2767
+ case "find": {
2768
+ const include = expandInclude(call.include, depth);
2769
+ const effective = Math.min(call.limit ?? cap, cap);
2770
+ const rows = await model.find(include, {
2771
+ limit: effective + 1,
2772
+ ...call.offset === void 0 ? {} : { offset: call.offset },
2773
+ ...call.sort === void 0 ? {} : { sort: call.sort },
2774
+ ...call.direction === void 0 ? {} : { direction: call.direction }
2775
+ });
2776
+ const truncated = rows.length > effective;
2777
+ const sliced = rows.slice(0, effective);
2778
+ return {
2779
+ rows: sliced,
2780
+ count: sliced.length,
2781
+ truncated,
2782
+ limit: effective
2783
+ };
2784
+ }
2785
+ case "link":
2786
+ await model.link(call.key, call.relation, call.target);
2787
+ return { linked: true };
2788
+ case "unlink":
2789
+ await model.unlink(call.key, call.relation, call.target);
2790
+ return { unlinked: true };
2791
+ case "links": {
2792
+ const keys = await model.links(call.key, call.relation);
2793
+ const truncated = keys.length > cap;
2794
+ const sliced = keys.slice(0, cap);
2795
+ return {
2796
+ keys: sliced,
2797
+ count: sliced.length,
2798
+ truncated,
2799
+ limit: cap
2800
+ };
2801
+ }
2802
+ }
2803
+ } catch (error) {
2804
+ if (isAgentToolError(error)) throw error;
2805
+ const relation = relationToolCode(error);
2806
+ if (relation !== void 0) throw new AgentToolError("RELATION", error instanceof Error ? error.message : String(error), {
2807
+ code: relation,
2808
+ operation: call.operation,
2809
+ model: call.model,
2810
+ ..."relation" in call ? { relation: call.relation } : {}
2811
+ });
2812
+ const database = databaseToolCode(error);
2813
+ if (database === void 0) throw error;
2814
+ throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
2815
+ code: database,
2816
+ operation: call.operation
2817
+ });
2818
+ }
2819
+ }
2820
+ });
2821
+ }
1196
2822
  //#endregion
1197
- export { AGENT_TOOL_DEPTH, AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME, AGENT_TOOL_SUMMARY, AgentToolError, DESCRIBE_TOOL_DESCRIPTION, DESCRIBE_TOOL_NAME, DESCRIBE_TOOL_SUMMARY, MAX_WORKFLOW_DEPTH, 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, completeDraft, completePhaseDraft, completeTaskDraft, createAgentFunction, createAgentTool, createDescribeTool, createToolFunction, createWorkflowDraftContract, createWorkflowTool, createWorkspaceTool, describeToolShape, expandSteps, isAgentToolError, phaseDraftShape, stepShape, taskDraftShape, workflowDraftShape, workflowStepsShape, workflowTag, workflowToolSummary, workspaceToolShape };
2823
+ 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, 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, createMemoryDefinitionStore, createPromptTool, createRelationTool, createToolFunction, createWorkflowDraftContract, createWorkflowTool, createWorkspaceTool, criteriaOf, criteriaShape, databaseToolCode, databaseToolShape, describeToolShape, expandInclude, expandSteps, expandTables, includeShape, 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 };
1198
2824
 
1199
2825
  //# sourceMappingURL=index.js.map