@orkestrel/tool 0.0.2 → 0.0.4

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,5 +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, samplesToSchema, schemaToObject, schemaToParameters, schemaToShape, stringShape, unionShape } from "@orkestrel/contract";
2
2
  import { isTerminalError } from "@orkestrel/terminal";
3
+ import { createDatabase, createMemoryDriver, generateUUID, isDatabaseError, shapeToColumnType } from "@orkestrel/database";
4
+ import { isRelationError } from "@orkestrel/relation";
3
5
  import { WorkspaceError, createTool, createWorkspaceManager, isText, rangeOf } from "@orkestrel/agent";
4
6
  import { WorkflowError, createWorkflowContract } from "@orkestrel/workflow";
5
7
  //#region src/core/constants.ts
@@ -295,6 +297,235 @@ var ANSWER_TOOL_DESCRIPTION = [
295
297
  value: true
296
298
  })
297
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");
298
529
  //#endregion
299
530
  //#region src/core/errors.ts
300
531
  /**
@@ -305,6 +536,9 @@ var ANSWER_TOOL_DESCRIPTION = [
305
536
  * (`DEADLOCK`), a prompt that expired before it was answered (`EXPIRE`), or an answer that
306
537
  * failed to apply (`ANSWER`) — the last three thrown by
307
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`.
308
542
  *
309
543
  * @remarks
310
544
  * Carries a machine-readable `code` (see {@link import('./types.js').AgentToolErrorCode}) and
@@ -675,6 +909,326 @@ var workspaceToolShape = unionShape(objectShape({
675
909
  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." }),
676
910
  id: stringShape({ description: "The id of the workspace to make active (from the \"workspaces\" listing)." })
677
911
  }));
912
+ /** A {@link import('./types.js').ColumnKind} literal — the leaf {@link columnSpecShape} wraps. */
913
+ var columnKindShape = literalShape([
914
+ "string",
915
+ "integer",
916
+ "number",
917
+ "boolean"
918
+ ], { description: "A column type: \"string\" | \"integer\" | \"number\" | \"boolean\"." });
919
+ /** A {@link import('./types.js').ColumnSpec} — a bare {@link columnKindShape}, or `{ type, optional }`. */
920
+ var columnSpecShape = unionShape(columnKindShape, objectShape({
921
+ type: columnKindShape,
922
+ optional: optionalShape(booleanShape({ description: "Whether the column may be absent from a row." }))
923
+ }));
924
+ /** A {@link import('./types.js').TableSpec} — table name to `{ columns }`, each column a {@link columnSpecShape}. */
925
+ var tableSpecShape = recordShape(objectShape({ columns: recordShape(columnSpecShape, { description: "Column name to its type." }) }), { description: "Table name to its column layout." });
926
+ /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
927
+ 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." }));
928
+ /** A loose row — a flat object of column name to JSON value; the array form (multiple rows) resolves FIRST per AGENTS §9.2. */
929
+ var rowShape = recordShape(jsonShape(), { description: "A row as a flat object of column name to value." });
930
+ /** One or many loose rows — the array form resolves FIRST per AGENTS §9.2. */
931
+ var rowsShape = unionShape(arrayShape(rowShape, { description: "Multiple rows." }), rowShape);
932
+ /** One SERIALIZED WHERE condition — `values` is ALWAYS an array, even for a single-value operator. */
933
+ var conditionShape = objectShape({
934
+ column: stringShape({ description: "The column this condition applies to." }),
935
+ operator: literalShape([
936
+ "equals",
937
+ "not",
938
+ "above",
939
+ "below",
940
+ "from",
941
+ "to",
942
+ "between",
943
+ "like",
944
+ "glob",
945
+ "starts",
946
+ "ends",
947
+ "any",
948
+ "none",
949
+ "absent",
950
+ "present"
951
+ ], { description: "The comparison operator." }),
952
+ values: arrayShape(jsonShape(), { description: "The operand values the operator needs (always an array, even for one value)." }),
953
+ connector: optionalShape(literalShape(["and", "or"], { description: "Joins this condition to the next; omit on the last condition." }))
954
+ });
955
+ /** One sort term. */
956
+ var orderShape = objectShape({
957
+ column: stringShape({ description: "The column to sort by." }),
958
+ direction: literalShape(["ascending", "descending"], { description: "The sort direction." })
959
+ });
960
+ /** The SERIALIZED criteria form — conditions, order, and pagination. */
961
+ var criteriaShape = objectShape({
962
+ conditions: optionalShape(arrayShape(conditionShape, { description: "The WHERE conditions, folded left to right." })),
963
+ order: optionalShape(arrayShape(orderShape, { description: "The sort terms, applied in order." })),
964
+ limit: optionalShape(integerShape({
965
+ min: 0,
966
+ description: "Max rows to return."
967
+ })),
968
+ offset: optionalShape(integerShape({
969
+ min: 0,
970
+ description: "Rows to skip before returning."
971
+ }))
972
+ });
973
+ /**
974
+ * The shape of {@link import('./factories.js').createDatabaseTool}'s call arguments —
975
+ * discriminated by `operation` into the 12 database operations (`'create'` / `'tables'` /
976
+ * `'get'` / `'records'` / `'count'` / `'aggregate'` / `'add'` / `'set'` / `'update'` /
977
+ * `'remove'` / `'migrate'` / `'destroy'`).
978
+ *
979
+ * @remarks
980
+ * Every arm carries `id` (the database id). `'create'` / `'migrate'` carry `tables` (the
981
+ * {@link import('./types.js').TableSpec} column DSL, compiled via
982
+ * {@link import('./helpers.js').expandTables}); `'get'` / `'update'` / `'remove'` carry `key`
983
+ * (one key or an array of keys, positional); `'add'` / `'set'` carry `row` (one row or an array of
984
+ * rows); `'update'` also carries `changes` (a loose partial row); `'records'` / `'count'` /
985
+ * `'aggregate'` carry an optional `criteria` (the SERIALIZED form — `values` is ALWAYS an array,
986
+ * even for a single-value operator, so a caller never chains method calls or guesses arity).
987
+ */
988
+ var databaseToolShape = unionShape(objectShape({
989
+ operation: literalShape(["create"], { description: "Define a new database." }),
990
+ id: stringShape({
991
+ min: 1,
992
+ description: "The database id."
993
+ }),
994
+ tables: tableSpecShape,
995
+ driver: optionalShape(stringShape({
996
+ min: 1,
997
+ description: "The registered driver key. Defaults to \"memory\"."
998
+ })),
999
+ keys: optionalShape(recordShape(stringShape(), { description: "Table name to its primary-key column." }))
1000
+ }), objectShape({
1001
+ operation: literalShape(["tables"], { description: "List a database's table names." }),
1002
+ id: stringShape({
1003
+ min: 1,
1004
+ description: "The database id."
1005
+ })
1006
+ }), objectShape({
1007
+ operation: literalShape(["get"], { description: "Fetch one or more rows by primary key." }),
1008
+ id: stringShape({
1009
+ min: 1,
1010
+ description: "The database id."
1011
+ }),
1012
+ table: stringShape({
1013
+ min: 1,
1014
+ description: "The table name."
1015
+ }),
1016
+ key: keyShape
1017
+ }), objectShape({
1018
+ operation: literalShape(["records"], { description: "List rows matching criteria." }),
1019
+ id: stringShape({
1020
+ min: 1,
1021
+ description: "The database id."
1022
+ }),
1023
+ table: stringShape({
1024
+ min: 1,
1025
+ description: "The table name."
1026
+ }),
1027
+ criteria: optionalShape(criteriaShape)
1028
+ }), objectShape({
1029
+ operation: literalShape(["count"], { description: "Count rows matching criteria." }),
1030
+ id: stringShape({
1031
+ min: 1,
1032
+ description: "The database id."
1033
+ }),
1034
+ table: stringShape({
1035
+ min: 1,
1036
+ description: "The table name."
1037
+ }),
1038
+ criteria: optionalShape(criteriaShape)
1039
+ }), objectShape({
1040
+ operation: literalShape(["aggregate"], { description: "Compute an aggregate over a column." }),
1041
+ id: stringShape({
1042
+ min: 1,
1043
+ description: "The database id."
1044
+ }),
1045
+ table: stringShape({
1046
+ min: 1,
1047
+ description: "The table name."
1048
+ }),
1049
+ function: literalShape([
1050
+ "count",
1051
+ "sum",
1052
+ "average",
1053
+ "minimum",
1054
+ "maximum"
1055
+ ], { description: "The aggregate function." }),
1056
+ column: stringShape({
1057
+ min: 1,
1058
+ description: "The column to aggregate."
1059
+ }),
1060
+ criteria: optionalShape(criteriaShape)
1061
+ }), objectShape({
1062
+ operation: literalShape(["add"], { description: "Insert one or more rows (fails on a duplicate key)." }),
1063
+ id: stringShape({
1064
+ min: 1,
1065
+ description: "The database id."
1066
+ }),
1067
+ table: stringShape({
1068
+ min: 1,
1069
+ description: "The table name."
1070
+ }),
1071
+ row: rowsShape
1072
+ }), objectShape({
1073
+ operation: literalShape(["set"], { description: "Upsert one or more rows." }),
1074
+ id: stringShape({
1075
+ min: 1,
1076
+ description: "The database id."
1077
+ }),
1078
+ table: stringShape({
1079
+ min: 1,
1080
+ description: "The table name."
1081
+ }),
1082
+ row: rowsShape
1083
+ }), objectShape({
1084
+ operation: literalShape(["update"], { description: "Patch one or more existing rows." }),
1085
+ id: stringShape({
1086
+ min: 1,
1087
+ description: "The database id."
1088
+ }),
1089
+ table: stringShape({
1090
+ min: 1,
1091
+ description: "The table name."
1092
+ }),
1093
+ key: keyShape,
1094
+ changes: rowShape
1095
+ }), objectShape({
1096
+ operation: literalShape(["remove"], { description: "Delete one or more rows by key." }),
1097
+ id: stringShape({
1098
+ min: 1,
1099
+ description: "The database id."
1100
+ }),
1101
+ table: stringShape({
1102
+ min: 1,
1103
+ description: "The table name."
1104
+ }),
1105
+ key: keyShape
1106
+ }), objectShape({
1107
+ operation: literalShape(["migrate"], { description: "Replace the table layout in place." }),
1108
+ id: stringShape({
1109
+ min: 1,
1110
+ description: "The database id."
1111
+ }),
1112
+ tables: tableSpecShape
1113
+ }), objectShape({
1114
+ operation: literalShape(["destroy"], { description: "Drop a database entirely." }),
1115
+ id: stringShape({
1116
+ min: 1,
1117
+ description: "The database id."
1118
+ })
1119
+ }));
1120
+ /** One key value — a string or number; the array form (multiple keys, positional) resolves FIRST per AGENTS §9.2. */
1121
+ 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." }));
1122
+ /** A single row key (not an array) — used by `'link'` / `'unlink'` / `'links'`, which address exactly one owning row. */
1123
+ var singleKeyShape = unionShape(stringShape({ description: "The owning row key." }), numberShape({ description: "The owning row key." }));
1124
+ /** Flat dot-path relation include list, expanded via {@link import('./helpers.js').expandInclude}. */
1125
+ 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." }));
1126
+ /** Which registered relation manager to address — omitted resolves to the sole registered manager. */
1127
+ var managerShape = optionalShape(stringShape({
1128
+ min: 1,
1129
+ description: "Which registered relation manager to address."
1130
+ }));
1131
+ /**
1132
+ * The shape of {@link import('./factories.js').createRelationTool}'s call arguments —
1133
+ * discriminated by `operation` into the 5 relation operations (`'load'` / `'find'` / `'link'` /
1134
+ * `'unlink'` / `'links'`).
1135
+ *
1136
+ * @remarks
1137
+ * `'load'` fetches one or more rows (positional key/array) with `include` attached. `'find'`
1138
+ * fetches rows (pagination / sort only) with `include` attached. `'link'` / `'unlink'` write /
1139
+ * remove a `through` junction row; `'links'` lists a `through` relation's linked keys.
1140
+ */
1141
+ var relationToolShape = unionShape(objectShape({
1142
+ operation: literalShape(["load"], { description: "Fetch one or more rows by key, with related rows attached." }),
1143
+ manager: managerShape,
1144
+ model: stringShape({
1145
+ min: 1,
1146
+ description: "The model (table) name."
1147
+ }),
1148
+ key: relationKeyShape,
1149
+ include: includeShape
1150
+ }), objectShape({
1151
+ operation: literalShape(["find"], { description: "List rows, with related rows attached." }),
1152
+ manager: managerShape,
1153
+ model: stringShape({
1154
+ min: 1,
1155
+ description: "The model (table) name."
1156
+ }),
1157
+ include: includeShape,
1158
+ limit: optionalShape(integerShape({
1159
+ min: 0,
1160
+ description: "Max rows to return."
1161
+ })),
1162
+ offset: optionalShape(integerShape({
1163
+ min: 0,
1164
+ description: "Rows to skip before returning."
1165
+ })),
1166
+ sort: optionalShape(stringShape({
1167
+ min: 1,
1168
+ description: "The column to sort by."
1169
+ })),
1170
+ direction: optionalShape(literalShape(["ascending", "descending"], { description: "The sort direction." }))
1171
+ }), objectShape({
1172
+ operation: literalShape(["link"], { description: "Connect two rows through a \"through\" relation." }),
1173
+ manager: managerShape,
1174
+ model: stringShape({
1175
+ min: 1,
1176
+ description: "The model (table) name."
1177
+ }),
1178
+ key: singleKeyShape,
1179
+ relation: stringShape({
1180
+ min: 1,
1181
+ description: "The \"through\" relation name."
1182
+ }),
1183
+ target: singleKeyShape
1184
+ }), objectShape({
1185
+ operation: literalShape(["unlink"], { description: "Disconnect two rows previously linked through a \"through\" relation." }),
1186
+ manager: managerShape,
1187
+ model: stringShape({
1188
+ min: 1,
1189
+ description: "The model (table) name."
1190
+ }),
1191
+ key: singleKeyShape,
1192
+ relation: stringShape({
1193
+ min: 1,
1194
+ description: "The \"through\" relation name."
1195
+ }),
1196
+ target: singleKeyShape
1197
+ }), objectShape({
1198
+ operation: literalShape(["links"], { description: "List every key linked to a row through a \"through\" relation." }),
1199
+ manager: managerShape,
1200
+ model: stringShape({
1201
+ min: 1,
1202
+ description: "The model (table) name."
1203
+ }),
1204
+ key: singleKeyShape,
1205
+ relation: stringShape({
1206
+ min: 1,
1207
+ description: "The \"through\" relation name."
1208
+ })
1209
+ }));
1210
+ /**
1211
+ * The shape of {@link import('./factories.js').createInferTool}'s call arguments — one or more
1212
+ * example `samples` to infer a JSON Schema from, plus per-call `format` / `enum` toggles and an
1213
+ * optional `candidates` array to check against the inferred schema.
1214
+ *
1215
+ * @remarks
1216
+ * `samples` requires at least one element (`min: 1`) — an empty array parses to `undefined`,
1217
+ * surfaced by the handler as a typed `TOOL` {@link import('./errors.js').AgentToolError}. When
1218
+ * `candidates` is present (any array, including empty), the handler compiles a contract from the
1219
+ * freshly inferred schema and checks each candidate against it with a STRICT guard (`.is`, no
1220
+ * coercion) — the opposite of {@link import('./factories.js').createEndpointTool}'s NORMALIZING
1221
+ * `.parse` enforcement.
1222
+ */
1223
+ var inferToolShape = objectShape({
1224
+ samples: arrayShape(jsonShape(), {
1225
+ min: 1,
1226
+ description: "The example values to infer a JSON Schema from (at least one)."
1227
+ }),
1228
+ format: optionalShape(booleanShape({ description: "Infer string formats (date-time, email, ...) from the samples. Defaults to false." })),
1229
+ enum: optionalShape(booleanShape({ description: "Infer enum constraints from repeated literal values. Defaults to false." })),
1230
+ 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." }))
1231
+ });
678
1232
  //#endregion
679
1233
  //#region src/core/helpers.ts
680
1234
  /**
@@ -880,6 +1434,390 @@ function terminalToolCode(error) {
880
1434
  if (error.code === "EXPIRE") return "EXPIRE";
881
1435
  return "TOOL";
882
1436
  }
1437
+ /** Narrow an unknown value to a {@link ColumnSpec} — a valid {@link import('./types.js').ColumnKind} shorthand, or `{ type, optional }` with a valid `type`. */
1438
+ function isColumnSpec(value) {
1439
+ if (isColumnKind(value)) return true;
1440
+ if (!isRecord(value)) return false;
1441
+ return isColumnKind(value.type) && (value.optional === void 0 || typeof value.optional === "boolean");
1442
+ }
1443
+ /** Narrow an unknown value to a {@link import('./types.js').ColumnKind}. */
1444
+ function isColumnKind(value) {
1445
+ return value === "string" || value === "integer" || value === "number" || value === "boolean";
1446
+ }
1447
+ /**
1448
+ * Compile a {@link TableSpec} into the `@orkestrel/database` {@link TablesShape} it configures —
1449
+ * each {@link ColumnSpec} maps to the matching primitive shaper (`'string'` → `stringShape()`,
1450
+ * `'integer'` → `integerShape()`, `'number'` → `numberShape()`, `'boolean'` → `booleanShape()`),
1451
+ * wrapped in `optionalShape` when the column declares `optional: true`. Total, pure.
1452
+ *
1453
+ * @param spec - The small-model-facing table layout
1454
+ * @returns The compiled `TablesShape` a `@orkestrel/database` `createDatabase` call accepts
1455
+ */
1456
+ function expandTables(spec) {
1457
+ const tables = {};
1458
+ for (const [table, definition] of Object.entries(spec)) {
1459
+ const columns = {};
1460
+ for (const [column, kind] of Object.entries(definition.columns)) columns[column] = columnShape(kind);
1461
+ tables[table] = columns;
1462
+ }
1463
+ return tables;
1464
+ }
1465
+ /** Compile one {@link ColumnSpec} into its `@orkestrel/database` column shape — the per-column leaf {@link expandTables} maps over. */
1466
+ function columnShape(spec) {
1467
+ const kind = isString(spec) ? spec : spec.type;
1468
+ const optional = !isString(spec) && spec.optional === true;
1469
+ const shape = kindShape(kind);
1470
+ return optional ? optionalShape(shape) : shape;
1471
+ }
1472
+ /** Map one {@link import('./types.js').ColumnKind} to its primitive `@orkestrel/database` shape — the leaf {@link columnShape} wraps. */
1473
+ function kindShape(kind) {
1474
+ if (kind === "string") return stringShape();
1475
+ if (kind === "integer") return integerShape();
1476
+ if (kind === "number") return numberShape();
1477
+ return booleanShape();
1478
+ }
1479
+ /**
1480
+ * Narrow an unknown value to a {@link DatabaseDefinition} — a non-empty `id` + `driver`, a
1481
+ * `tables` record whose every value is `{ columns: record of valid ColumnSpec }`, and an optional
1482
+ * `keys` record of strings. The boundary guard a {@link import('./types.js').DefinitionStoreInterface}
1483
+ * applies to an untrusted persisted blob before trusting it as a definition (never an `as`).
1484
+ */
1485
+ function isDatabaseDefinition(value) {
1486
+ if (!isRecord(value)) return false;
1487
+ if (!isNonEmptyString(value.id) || !isNonEmptyString(value.driver)) return false;
1488
+ if (!isRecord(value.tables)) return false;
1489
+ for (const table of Object.values(value.tables)) {
1490
+ if (!isRecord(table) || !isRecord(table.columns)) return false;
1491
+ for (const column of Object.values(table.columns)) if (!isColumnSpec(column)) return false;
1492
+ }
1493
+ if (value.keys !== void 0) {
1494
+ if (!isRecord(value.keys)) return false;
1495
+ for (const key of Object.values(value.keys)) if (!isString(key)) return false;
1496
+ }
1497
+ return true;
1498
+ }
1499
+ /**
1500
+ * Map a caught error to the {@link AgentToolErrorCode} the upcoming database tool should throw
1501
+ * with — the pure classification step of that factory's error handling, mirroring
1502
+ * {@link terminalToolCode}'s idiom for `@orkestrel/database`.
1503
+ *
1504
+ * @param error - The value caught from a `@orkestrel/database` table operation
1505
+ * @returns The granular {@link DatabaseErrorCode}, or `undefined` if `error` is not a `DatabaseError`
1506
+ */
1507
+ function databaseToolCode(error) {
1508
+ return isDatabaseError(error) ? error.code : void 0;
1509
+ }
1510
+ /**
1511
+ * Map a caught error to the {@link AgentToolErrorCode} the upcoming relation tool should throw
1512
+ * with — the pure classification step of that factory's error handling, mirroring
1513
+ * {@link terminalToolCode}'s idiom for `@orkestrel/relation`.
1514
+ *
1515
+ * @param error - The value caught from a `@orkestrel/relation` operation
1516
+ * @returns The granular {@link RelationErrorCode}, or `undefined` if `error` is not a `RelationError`
1517
+ */
1518
+ function relationToolCode(error) {
1519
+ return isRelationError(error) ? error.code : void 0;
1520
+ }
1521
+ /**
1522
+ * Expand the relation tool's FLAT dot-path `include` list into a live `@orkestrel/relation`
1523
+ * {@link Include} tree — the pure leaf {@link import('./factories.js').createRelationTool} calls
1524
+ * before a `'load'` / `'find'` call.
1525
+ *
1526
+ * @remarks
1527
+ * Each path splits on `'.'` into a chain of relation names, deep-merged into one nested
1528
+ * `Include` object with a leaf `true`. A longer path SUBSUMES a shorter sibling's bare `true` —
1529
+ * `'contacts'` followed by `'contacts.account'` yields `{ contacts: { account: true } }`, never
1530
+ * overwriting the deeper chain. An EMPTY segment (`''`, from a leading/trailing/doubled `.`) or a
1531
+ * path whose segment count exceeds `depth` throws a typed `TOOL` {@link AgentToolError}.
1532
+ *
1533
+ * @param paths - The flat dot-path `include` list (or `undefined` — yields `{}`)
1534
+ * @param depth - The max segment count a single path may reach
1535
+ * @returns The equivalent nested {@link Include}
1536
+ *
1537
+ * @example
1538
+ * ```ts
1539
+ * import { expandInclude } from '@src/core'
1540
+ *
1541
+ * expandInclude(['contacts', 'contacts.account'], 3)
1542
+ * // { contacts: { account: true } }
1543
+ * ```
1544
+ */
1545
+ function expandInclude(paths, depth) {
1546
+ function merge(base, segments) {
1547
+ const [head, ...rest] = segments;
1548
+ const existing = base[head];
1549
+ if (rest.length === 0) return {
1550
+ ...base,
1551
+ [head]: existing === void 0 ? true : existing
1552
+ };
1553
+ const nextBase = typeof existing === "object" ? existing : {};
1554
+ return {
1555
+ ...base,
1556
+ [head]: merge(nextBase, rest)
1557
+ };
1558
+ }
1559
+ let include = {};
1560
+ for (const path of paths ?? []) {
1561
+ const segments = path.split(".");
1562
+ if (segments.length > depth || segments.some((segment) => segment.length === 0)) throw new AgentToolError("TOOL", `malformed include path '${path}'`, {
1563
+ path,
1564
+ depth
1565
+ });
1566
+ include = merge(include, segments);
1567
+ }
1568
+ return include;
1569
+ }
1570
+ /**
1571
+ * Resolve which registered {@link RelationManagerInterface} a relation-tool call addresses — the
1572
+ * pure manager-resolution leaf {@link import('./factories.js').createRelationTool} calls on
1573
+ * every operation.
1574
+ *
1575
+ * @remarks
1576
+ * An explicit `name` must match a key of `managers` (a miss throws a typed `TOOL`
1577
+ * {@link AgentToolError} naming the registered managers). An OMITTED `name` resolves to the sole
1578
+ * registered manager when exactly one is registered, else throws the same typed error.
1579
+ *
1580
+ * @param managers - The tool's registered `RelationManagerInterface` map
1581
+ * @param name - The call's optional `manager` field
1582
+ * @returns The resolved {@link RelationManagerInterface}
1583
+ */
1584
+ function relationManagerOf(managers, name) {
1585
+ if (name !== void 0) {
1586
+ const manager = managers[name];
1587
+ if (manager === void 0) throw new AgentToolError("TOOL", `unknown relation manager '${name}'`, {
1588
+ manager: name,
1589
+ managers: Object.keys(managers)
1590
+ });
1591
+ return manager;
1592
+ }
1593
+ const names = Object.keys(managers);
1594
+ if (names.length === 1) return managers[names[0]];
1595
+ throw new AgentToolError("TOOL", "no relation manager resolved for the call", { managers: names });
1596
+ }
1597
+ /**
1598
+ * Resolve a `model` name against a live {@link RelationManagerInterface} — the pure model-lookup
1599
+ * leaf {@link import('./factories.js').createRelationTool} calls on every operation, mirroring
1600
+ * {@link relationManagerOf}'s guard shape.
1601
+ *
1602
+ * @param manager - The resolved {@link RelationManagerInterface}
1603
+ * @param name - The call's `model` field
1604
+ * @returns The model's {@link ModelInterface}
1605
+ */
1606
+ function relationModelOf(manager, name) {
1607
+ if (!manager.has(name)) throw new AgentToolError("TOOL", `unknown model '${name}'`, {
1608
+ model: name,
1609
+ models: manager.models()
1610
+ });
1611
+ return manager.model(name);
1612
+ }
1613
+ /**
1614
+ * Normalize the database tool's parsed SERIALIZED criteria into a live `@orkestrel/database`
1615
+ * {@link Criteria} — default each condition's OMITTED `connector` to `'and'`.
1616
+ *
1617
+ * @remarks
1618
+ * The wire form ({@link import('./shapers.js').databaseToolShape}) lets a caller drop `connector`
1619
+ * on the last condition (it has nothing to join FORWARD to); the compiled `Condition` a live
1620
+ * `@orkestrel/database` table call accepts always carries one, so this fills the gap. `order` /
1621
+ * `limit` / `offset` pass through unchanged. Pure and total.
1622
+ *
1623
+ * @param criteria - The parsed criteria (or `undefined`)
1624
+ * @returns The equivalent live `Criteria`, or `undefined` when `criteria` is `undefined`
1625
+ */
1626
+ function criteriaOf(criteria) {
1627
+ if (criteria === void 0) return void 0;
1628
+ const conditions = criteria.conditions?.map((condition) => ({
1629
+ ...condition,
1630
+ connector: condition.connector ?? "and"
1631
+ }));
1632
+ return {
1633
+ ...conditions === void 0 ? {} : { conditions },
1634
+ ...criteria.order === void 0 ? {} : { order: criteria.order },
1635
+ ...criteria.limit === void 0 ? {} : { limit: criteria.limit },
1636
+ ...criteria.offset === void 0 ? {} : { offset: criteria.offset }
1637
+ };
1638
+ }
1639
+ /**
1640
+ * Clamp a `'records'` call's criteria to a row cap, and build the PROBE criteria the caller reads
1641
+ * with — the pure leaf {@link import('./factories.js').createDatabaseTool}'s `'records'` operation
1642
+ * uses to detect truncation without a separate `count` round trip.
1643
+ *
1644
+ * @remarks
1645
+ * The effective limit is `min(criteria?.limit ?? cap, cap)`, floored at `0` (so a caller can never
1646
+ * exceed the configured cap by supplying a larger `criteria.limit`). The returned probe criteria
1647
+ * requests ONE MORE row than the effective limit (`limit: effective + 1`) — if storage returns
1648
+ * that many, the caller knows the true result was truncated (`rows.length > effective`) and slices
1649
+ * back down to `effective` before returning.
1650
+ *
1651
+ * @example
1652
+ * ```ts
1653
+ * import { clampCriteria } from '@src/core'
1654
+ *
1655
+ * const { criteria, limit } = clampCriteria(undefined, 100)
1656
+ * // limit === 100, criteria.limit === 101 — a probe fetching one extra row
1657
+ * const rows = await table.records(criteria)
1658
+ * const truncated = rows.length > limit // true when storage had more than `limit` rows
1659
+ * ```
1660
+ *
1661
+ * @param criteria - The live criteria to clamp (or `undefined`)
1662
+ * @param cap - The row-count ceiling
1663
+ * @returns The PROBE criteria (`limit` bumped by one) and the effective `limit`
1664
+ */
1665
+ function clampCriteria(criteria, cap) {
1666
+ const limit = Math.max(0, Math.min(criteria?.limit ?? cap, cap));
1667
+ return {
1668
+ criteria: {
1669
+ ...criteria,
1670
+ limit: limit + 1
1671
+ },
1672
+ limit
1673
+ };
1674
+ }
1675
+ /** Map a column NAME + its live `@orkestrel/database` `ContractShape` to a {@link ColumnSchema} — the leaf {@link tableSchema} maps over. */
1676
+ function columnSchema(name, shape) {
1677
+ return {
1678
+ name,
1679
+ type: shapeToColumnType(shape),
1680
+ nullable: shape.type === "optional" || shape.type === "nullable"
1681
+ };
1682
+ }
1683
+ /**
1684
+ * Build one {@link TableSchema} from a table NAME and its `@orkestrel/database` `TableExport` —
1685
+ * the "deployed" schema shape `DatabaseInterface.migrate` diffs against, derived from a LIVE
1686
+ * handle's `export()` rather than a re-declared {@link TableSpec}, so it works for ANY handle
1687
+ * (config-tracked or caller-supplied).
1688
+ *
1689
+ * @param name - The table name
1690
+ * @param table - The table's `TableExport` (`{ key, columns }`, `@orkestrel/database`)
1691
+ * @returns The equivalent {@link TableSchema} (`indexes` empty — this package declares none)
1692
+ */
1693
+ function tableSchema(name, table) {
1694
+ return {
1695
+ name,
1696
+ primary: table.key,
1697
+ columns: Object.entries(table.columns).map(([column, shape]) => columnSchema(column, shape)),
1698
+ indexes: []
1699
+ };
1700
+ }
1701
+ //#endregion
1702
+ //#region src/core/stores/MemoryDefinitionStore.ts
1703
+ /**
1704
+ * The in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of
1705
+ * {@link DatabaseDefinition}s keyed by database id, the DEFAULT store
1706
+ * {@link import('../factories.js').createMemoryDefinitionStore} builds. The EXACT twin of
1707
+ * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore}.
1708
+ *
1709
+ * @remarks
1710
+ * A plain `Map<string, DatabaseDefinition>` (AGENTS §21 — the definition is already pure,
1711
+ * self-contained CONFIG-only JSON, so no encoding is needed for the memory tier). There is NO
1712
+ * idle-TTL and NO eviction: a persisted definition lives until an explicit `delete`. A durable
1713
+ * backend (JSON / SQLite / IndexedDB) swaps in through the SAME interface without touching a
1714
+ * consumer — its driver-pluggable twin is
1715
+ * {@link import('./DatabaseDefinitionStore.js').DatabaseDefinitionStore} (the definition as one
1716
+ * opaque JSON column).
1717
+ *
1718
+ * - **`get` resolves the persisted definition for an id**, or `undefined` if none is stored.
1719
+ * - **`set` inserts / replaces under the definition's OWN `id`** (no separate id param).
1720
+ * - **`delete` drops a definition by id**; an absent id is a no-op (no throw).
1721
+ *
1722
+ * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1723
+ * bijection with {@link DefinitionStoreInterface}).
1724
+ *
1725
+ * @example
1726
+ * ```ts
1727
+ * import { createMemoryDefinitionStore } from '@src/core'
1728
+ *
1729
+ * const store = createMemoryDefinitionStore()
1730
+ * await store.set({ id: 'shop', driver: 'memory', tables: {} })
1731
+ * const definition = await store.get('shop')
1732
+ * await store.delete('shop')
1733
+ * ```
1734
+ */
1735
+ var MemoryDefinitionStore = class {
1736
+ #definitions = /* @__PURE__ */ new Map();
1737
+ get(id) {
1738
+ return Promise.resolve(this.#definitions.get(id));
1739
+ }
1740
+ set(definition) {
1741
+ this.#definitions.set(definition.id, definition);
1742
+ return Promise.resolve();
1743
+ }
1744
+ delete(id) {
1745
+ this.#definitions.delete(id);
1746
+ return Promise.resolve();
1747
+ }
1748
+ };
1749
+ //#endregion
1750
+ //#region src/core/stores/DatabaseDefinitionStore.ts
1751
+ /**
1752
+ * A {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database` layer — a
1753
+ * database's durable CONFIG state IS a row, so persistence reduces to keyed point-access
1754
+ * (`get` / `set` / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the
1755
+ * plain-`Map` {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}.
1756
+ *
1757
+ * @remarks
1758
+ * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
1759
+ * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /
1760
+ * IndexedDB backend swaps in WITHOUT touching a consumer — the same seam as
1761
+ * {@link import('./MemoryDefinitionStore.js').MemoryDefinitionStore}. The driver defaults to
1762
+ * memory ({@link import('../factories.js').createDatabaseDefinitionStore} passes
1763
+ * `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the durable
1764
+ * plumbing by passing a JSON / SQLite / IndexedDB driver.
1765
+ *
1766
+ * The {@link DatabaseDefinition} is stored as ONE OPAQUE JSON COLUMN — the table is a row of
1767
+ * `{ id; definition }` ({@link DatabaseDefinitionRow}). The definition is already a COMPLETE,
1768
+ * self-contained, pure-JSON CONFIG payload (never a live handle), so storing it whole is lossless
1769
+ * AND keeps the row type flat (`definition` reads back as `unknown`).
1770
+ *
1771
+ * - **`set(definition)` upserts under the definition's OWN `id`** (no separate id param) — it
1772
+ * writes the row `{ id: definition.id, definition }`.
1773
+ * - **`get(id)` resolves the stored definition for an id**, narrowing the opaque JSON column back
1774
+ * to a {@link DatabaseDefinition} ({@link import('../helpers.js').isDatabaseDefinition} — the
1775
+ * AGENTS §14 boundary narrow for an untrusted storage read), or `undefined` if none is stored
1776
+ * or the stored blob is malformed.
1777
+ * - **`delete(id)` drops a definition by id**; an absent id is a no-op (no throw).
1778
+ *
1779
+ * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
1780
+ * bijection with {@link DefinitionStoreInterface}).
1781
+ *
1782
+ * @example
1783
+ * ```ts
1784
+ * import { createDatabaseDefinitionStore, createMemoryDriver } from '@src/core'
1785
+ *
1786
+ * const store = createDatabaseDefinitionStore(createMemoryDriver()) // a durable driver swaps in here
1787
+ * await store.set({ id: 'shop', driver: 'memory', tables: {} }) // persist the config (one JSON column)
1788
+ * const definition = await store.get('shop')
1789
+ * await store.delete('shop')
1790
+ * ```
1791
+ */
1792
+ var DatabaseDefinitionStore = class {
1793
+ #table;
1794
+ /**
1795
+ * Wrap a table as a definition store.
1796
+ *
1797
+ * @param table - The {@link TableInterface} holding the definitions — its row is the
1798
+ * {@link DatabaseDefinitionRow} `{ id; definition }` shape (the definition one opaque JSON column)
1799
+ */
1800
+ constructor(table) {
1801
+ this.#table = table;
1802
+ }
1803
+ /** Resolve the persisted definition for `id`, narrowing the opaque JSON column back to a `DatabaseDefinition`. */
1804
+ async get(id) {
1805
+ const row = await this.#table.get(id);
1806
+ if (row === void 0) return void 0;
1807
+ return isDatabaseDefinition(row.definition) ? row.definition : void 0;
1808
+ }
1809
+ /** Insert or replace under the definition's OWN `id` (no separate id param) — the row is `{ id, definition }`. */
1810
+ async set(definition) {
1811
+ await this.#table.set({
1812
+ id: definition.id,
1813
+ definition
1814
+ });
1815
+ }
1816
+ /** Drop a definition by id; an absent id is a no-op (no throw). */
1817
+ async delete(id) {
1818
+ await this.#table.remove(id);
1819
+ }
1820
+ };
883
1821
  //#endregion
884
1822
  //#region src/core/factories.ts
885
1823
  /**
@@ -1586,7 +2524,636 @@ function createAnswerTool(options) {
1586
2524
  }
1587
2525
  });
1588
2526
  }
2527
+ /**
2528
+ * Create the in-memory {@link DefinitionStoreInterface} — a process-lifetime `Map` of database
2529
+ * definitions, the DEFAULT store the upcoming database / relation tools will persist their
2530
+ * `DatabaseDefinition` configs through.
2531
+ *
2532
+ * @returns A {@link DefinitionStoreInterface}
2533
+ *
2534
+ * @example
2535
+ * ```ts
2536
+ * import { createMemoryDefinitionStore } from '@src/core'
2537
+ *
2538
+ * const store = createMemoryDefinitionStore()
2539
+ * ```
2540
+ */
2541
+ function createMemoryDefinitionStore() {
2542
+ return new MemoryDefinitionStore();
2543
+ }
2544
+ /**
2545
+ * Create a {@link DefinitionStoreInterface} backed by one table of the `@orkestrel/database`
2546
+ * layer — the driver-pluggable twin of {@link createMemoryDefinitionStore}, storing each
2547
+ * database's definition as one opaque JSON column.
2548
+ *
2549
+ * @param driver - The {@link DriverInterface} backing the table (default an in-memory driver)
2550
+ * @returns A {@link DefinitionStoreInterface}
2551
+ *
2552
+ * @example
2553
+ * ```ts
2554
+ * import { createDatabaseDefinitionStore } from '@src/core'
2555
+ *
2556
+ * const store = createDatabaseDefinitionStore() // in-memory by default
2557
+ * ```
2558
+ */
2559
+ function createDatabaseDefinitionStore(driver = createMemoryDriver()) {
2560
+ return new DatabaseDefinitionStore(createDatabase({
2561
+ driver,
2562
+ tables: { definitions: {
2563
+ id: stringShape(),
2564
+ definition: rawShape({})
2565
+ } }
2566
+ }).table("definitions"));
2567
+ }
2568
+ /**
2569
+ * Build an LLM-callable database tool — create, query, and mutate `@orkestrel/database`
2570
+ * databases through one `operation`-discriminated call (AGENTS §14, matching
2571
+ * {@link createWorkspaceTool}'s single-tool-many-operations shape).
2572
+ *
2573
+ * @remarks
2574
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2575
+ * {@link import('./shapers.js').databaseToolShape}, dispatches to the matching operation, and
2576
+ * RETURNS a plain result on success. A database is resolved lazily and cached for the tool's
2577
+ * lifetime — `'create'` mints one from `tables` ({@link import('./helpers.js').expandTables}) and
2578
+ * a registered `driver` key ({@link import('./types.js').DatabaseToolOptions.drivers}, default
2579
+ * `{ memory: () => createMemoryDriver() }`); any other operation addressing an uncached id falls
2580
+ * back to {@link import('./types.js').DatabaseToolOptions.store} (an unknown id throws a typed
2581
+ * `TOOL` {@link import('./errors.js').AgentToolError}). When a `store` is configured, `'create'`
2582
+ * persists the new {@link import('./types.js').DatabaseDefinition} and `'destroy'` deletes it.
2583
+ *
2584
+ * `'migrate'` re-declares a LIVE handle's tables via `DatabaseInterface.import` (the SAME driver
2585
+ * and storage, a NEW typed view) and calls its `migrate` against the OLD deployed schema —
2586
+ * derived from the handle's OWN `export()` (via {@link import('./helpers.js').tableSchema}), so it
2587
+ * works for any handle, config-tracked or caller-supplied via
2588
+ * {@link import('./types.js').DatabaseToolOptions.databases}. `'records'` clamps its `criteria` to
2589
+ * {@link import('./types.js').DatabaseToolOptions.limit} (default
2590
+ * {@link import('./constants.js').DATABASE_TOOL_LIMIT}) via
2591
+ * {@link import('./helpers.js').clampCriteria}, reporting `truncated` when storage held more rows
2592
+ * than the cap. Every operation's `criteria` is normalized via
2593
+ * {@link import('./helpers.js').criteriaOf} (defaults an omitted condition `connector` to `'and'`).
2594
+ * When {@link import('./types.js').DatabaseToolOptions.readonly} is `true`, every mutating
2595
+ * operation throws a typed `TOOL` `AgentToolError` before doing anything. When
2596
+ * {@link import('./types.js').DatabaseToolOptions.timeout} is set, every `@orkestrel/database` call
2597
+ * this tool makes is given a fresh `AbortSignal.timeout(timeout)`. A typed `@orkestrel/database`
2598
+ * failure (`DatabaseError`) re-surfaces as a typed `DATABASE` `AgentToolError` carrying the
2599
+ * original {@link import('@orkestrel/database').DatabaseErrorCode} in `context.code`
2600
+ * ({@link import('./helpers.js').databaseToolCode}); an `AgentToolError` thrown by this tool's own
2601
+ * guards passes through unwrapped.
2602
+ *
2603
+ * A lazily re-minted database over the DEFAULT in-memory driver yields an EMPTY database — only
2604
+ * the {@link import('./types.js').DatabaseDefinition} schema persists in `store`, never rows;
2605
+ * durable rows need a persistent driver factory registered in
2606
+ * {@link import('./types.js').DatabaseToolOptions.drivers}. `'destroy'` closes whatever handle is
2607
+ * cached for the id, including an embedder-supplied
2608
+ * {@link import('./types.js').DatabaseToolOptions.databases} handle — the embedder relinquishes
2609
+ * that handle's lifecycle to this tool for any id it wires in. This tool assumes the
2610
+ * single-writer, non-reentrant model `@orkestrel/database` itself assumes — concurrent calls
2611
+ * against one id are NOT serialized by this tool. `'get'` is uncapped by
2612
+ * {@link import('./types.js').DatabaseToolOptions.limit} (bounded only by the caller's `key` array
2613
+ * size), unlike `'records'` / `'find'` / `'links'`.
2614
+ *
2615
+ * @param options - The tool's configuration (see {@link import('./types.js').DatabaseToolOptions})
2616
+ * @returns A `ToolInterface` (named {@link import('./constants.js').DATABASE_TOOL_NAME} by default)
2617
+ *
2618
+ * @example
2619
+ * ```ts
2620
+ * import { createDatabaseTool } from '@src/core'
2621
+ *
2622
+ * const tool = createDatabaseTool()
2623
+ * await tool.execute({
2624
+ * operation: 'create',
2625
+ * id: 'shop',
2626
+ * tables: { products: { columns: { name: 'string', price: 'number' } } },
2627
+ * })
2628
+ * ```
2629
+ */
2630
+ function createDatabaseTool(options = {}) {
2631
+ const contract = createContract(databaseToolShape);
2632
+ const parameters = schemaToParameters(contract.schema);
2633
+ const handles = new Map(Object.entries(options.databases ?? {}));
2634
+ const definitions = /* @__PURE__ */ new Map();
2635
+ const drivers = options.drivers ?? { memory: () => createMemoryDriver() };
2636
+ const key = options.key ?? generateUUID;
2637
+ const cap = options.limit ?? 1e3;
2638
+ const store = options.store;
2639
+ async function resolve(id) {
2640
+ const cached = handles.get(id);
2641
+ if (cached !== void 0) return cached;
2642
+ if (store !== void 0) {
2643
+ const definition = await store.get(id);
2644
+ if (definition !== void 0) {
2645
+ const factory = drivers[definition.driver];
2646
+ if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${definition.driver}'`, {
2647
+ id,
2648
+ driver: definition.driver
2649
+ });
2650
+ const handle = createDatabase({
2651
+ driver: factory(),
2652
+ tables: expandTables(definition.tables),
2653
+ ...definition.keys === void 0 ? {} : { keys: definition.keys },
2654
+ key
2655
+ });
2656
+ handles.set(id, handle);
2657
+ definitions.set(id, definition);
2658
+ return handle;
2659
+ }
2660
+ }
2661
+ throw new AgentToolError("TOOL", `unknown database '${id}'`, { id });
2662
+ }
2663
+ return createTool({
2664
+ name: options.name ?? "database",
2665
+ description: options.description ?? DATABASE_TOOL_DESCRIPTION,
2666
+ summary: DATABASE_TOOL_SUMMARY,
2667
+ parameters,
2668
+ execute: async (args) => {
2669
+ const call = contract.parse(args);
2670
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed database call", { args });
2671
+ 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 });
2672
+ const read = options.timeout === void 0 ? void 0 : { signal: AbortSignal.timeout(options.timeout) };
2673
+ try {
2674
+ switch (call.operation) {
2675
+ case "create": {
2676
+ 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 });
2677
+ const name = call.driver ?? "memory";
2678
+ const factory = drivers[name];
2679
+ if (factory === void 0) throw new AgentToolError("TOOL", `unknown driver '${name}'`, {
2680
+ id: call.id,
2681
+ driver: name
2682
+ });
2683
+ const tables = call.tables;
2684
+ const keys = call.keys;
2685
+ const handle = createDatabase({
2686
+ driver: factory(),
2687
+ tables: expandTables(tables),
2688
+ ...keys === void 0 ? {} : { keys },
2689
+ key
2690
+ });
2691
+ handles.set(call.id, handle);
2692
+ const definition = {
2693
+ id: call.id,
2694
+ driver: name,
2695
+ tables,
2696
+ ...keys === void 0 ? {} : { keys }
2697
+ };
2698
+ definitions.set(call.id, definition);
2699
+ if (store !== void 0) await store.set(definition);
2700
+ return {
2701
+ id: call.id,
2702
+ tables: Object.keys(tables)
2703
+ };
2704
+ }
2705
+ case "tables": {
2706
+ const handle = await resolve(call.id);
2707
+ return { tables: Object.keys(handle.export()).map((name) => {
2708
+ const table = handle.table(name);
2709
+ return {
2710
+ name,
2711
+ primary: table.primary,
2712
+ columns: table.contract.schema
2713
+ };
2714
+ }) };
2715
+ }
2716
+ case "get": {
2717
+ const table = (await resolve(call.id)).table(call.table);
2718
+ const many = Array.isArray(call.key);
2719
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2720
+ const rows = await table.get(keys);
2721
+ return many ? { rows } : { row: rows[0] };
2722
+ }
2723
+ case "records": {
2724
+ const table = (await resolve(call.id)).table(call.table);
2725
+ const { criteria: probe, limit } = clampCriteria(criteriaOf(call.criteria), cap);
2726
+ const rows = await table.records(probe, read);
2727
+ const truncated = rows.length > limit;
2728
+ const sliced = rows.slice(0, limit);
2729
+ return {
2730
+ rows: sliced,
2731
+ count: sliced.length,
2732
+ truncated,
2733
+ limit
2734
+ };
2735
+ }
2736
+ case "count": return { count: await (await resolve(call.id)).table(call.table).count(criteriaOf(call.criteria), read) };
2737
+ case "aggregate": return { value: await (await resolve(call.id)).table(call.table).aggregate(call.function, call.column, criteriaOf(call.criteria), read) };
2738
+ case "add": {
2739
+ const table = (await resolve(call.id)).table(call.table);
2740
+ const many = Array.isArray(call.row);
2741
+ const rows = Array.isArray(call.row) ? call.row : [call.row];
2742
+ const keys = await table.add(rows, read);
2743
+ return many ? { keys } : { key: keys[0] };
2744
+ }
2745
+ case "set": {
2746
+ const table = (await resolve(call.id)).table(call.table);
2747
+ const many = Array.isArray(call.row);
2748
+ const rows = Array.isArray(call.row) ? call.row : [call.row];
2749
+ const keys = await table.set(rows, read);
2750
+ return many ? { keys } : { key: keys[0] };
2751
+ }
2752
+ case "update": {
2753
+ const table = (await resolve(call.id)).table(call.table);
2754
+ const changes = call.changes;
2755
+ const many = Array.isArray(call.key);
2756
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2757
+ const updated = await table.update(keys, changes, read);
2758
+ return many ? { updated } : { updated: updated[0] };
2759
+ }
2760
+ case "remove": {
2761
+ const table = (await resolve(call.id)).table(call.table);
2762
+ const many = Array.isArray(call.key);
2763
+ const keys = Array.isArray(call.key) ? call.key : [call.key];
2764
+ const removed = await table.remove(keys, read);
2765
+ return many ? { removed } : { removed: removed[0] };
2766
+ }
2767
+ case "migrate": {
2768
+ const handle = await resolve(call.id);
2769
+ const previous = handle.export();
2770
+ const deployed = Object.entries(previous).map(([name, table]) => tableSchema(name, table));
2771
+ const tables = call.tables;
2772
+ const keys = {};
2773
+ for (const name of Object.keys(tables)) {
2774
+ const existing = previous[name];
2775
+ if (existing !== void 0) keys[name] = existing.key;
2776
+ }
2777
+ const declared = expandTables(tables);
2778
+ const migrated = handle.import(declared, Object.keys(keys).length > 0 ? keys : void 0);
2779
+ const migration = await migrated.migrate(deployed, read);
2780
+ handles.set(call.id, migrated);
2781
+ const tracked = definitions.get(call.id);
2782
+ if (tracked !== void 0) {
2783
+ const updated = {
2784
+ id: call.id,
2785
+ driver: tracked.driver,
2786
+ tables,
2787
+ ...Object.keys(keys).length > 0 ? { keys } : {}
2788
+ };
2789
+ definitions.set(call.id, updated);
2790
+ if (store !== void 0) await store.set(updated);
2791
+ }
2792
+ return { migration };
2793
+ }
2794
+ case "destroy": {
2795
+ const cached = handles.get(call.id);
2796
+ const persisted = store !== void 0 && cached === void 0 ? await store.get(call.id) !== void 0 : false;
2797
+ if (cached !== void 0) {
2798
+ await cached.close();
2799
+ handles.delete(call.id);
2800
+ }
2801
+ definitions.delete(call.id);
2802
+ if (store !== void 0) await store.delete(call.id);
2803
+ return {
2804
+ id: call.id,
2805
+ destroyed: cached !== void 0 || persisted
2806
+ };
2807
+ }
2808
+ }
2809
+ } catch (error) {
2810
+ if (isAgentToolError(error)) throw error;
2811
+ const code = databaseToolCode(error);
2812
+ if (code === void 0) throw error;
2813
+ throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
2814
+ code,
2815
+ operation: call.operation,
2816
+ id: call.id,
2817
+ ..."table" in call ? { table: call.table } : {}
2818
+ });
2819
+ }
2820
+ }
2821
+ });
2822
+ }
2823
+ /**
2824
+ * Build an LLM-callable relation tool — traverse and edit `@orkestrel/relation` relationships
2825
+ * through one `operation`-discriminated call (AGENTS §14, matching {@link createDatabaseTool}'s
2826
+ * single-tool-many-operations shape).
2827
+ *
2828
+ * @remarks
2829
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2830
+ * {@link import('./shapers.js').relationToolShape}, resolves the addressed
2831
+ * {@link import('@orkestrel/relation').RelationManagerInterface} — an explicit `manager` field
2832
+ * must match a key of {@link import('./types.js').RelationToolOptions.managers}, an OMITTED one
2833
+ * resolves to the SOLE registered manager, either miss throwing a typed `TOOL`
2834
+ * {@link import('./errors.js').AgentToolError}
2835
+ * ({@link import('./helpers.js').relationManagerOf}) — then resolves `model` against it
2836
+ * ({@link import('./helpers.js').relationModelOf}, same typed-`TOOL`-on-miss shape), and
2837
+ * dispatches to the matched operation, RETURNING a plain result on success.
2838
+ *
2839
+ * `'load'` / `'find'` expand the call's FLAT dot-path `include` list into a live
2840
+ * `@orkestrel/relation` `Include` tree via {@link import('./helpers.js').expandInclude}, capped
2841
+ * at {@link import('./types.js').RelationToolOptions.depth} (default
2842
+ * {@link import('./constants.js').RELATION_TOOL_DEPTH}) — a path exceeding the cap, or carrying an
2843
+ * empty segment, throws a typed `TOOL` error. `'load'` dispatches on whether `key` is an array
2844
+ * (positional many-key form, AGENTS §9.2) or a single key. `'find'` and `'links'` clamp their
2845
+ * result to {@link import('./types.js').RelationToolOptions.limit} (default
2846
+ * {@link import('./constants.js').RELATION_TOOL_LIMIT}) — `'find'` probes one row past the
2847
+ * effective limit (mirroring {@link import('./helpers.js').clampCriteria}'s idiom) to report
2848
+ * `truncated`; `'links'` (which has no upstream pagination) fetches the FULL linked-key list and
2849
+ * slices/truncates it the same way. `'link'` / `'unlink'` write / remove one `through` junction
2850
+ * row.
2851
+ *
2852
+ * A typed `@orkestrel/relation` failure (`RelationError`) re-surfaces as a typed `RELATION`
2853
+ * `AgentToolError` carrying the original {@link import('@orkestrel/relation').RelationErrorCode}
2854
+ * in `context.code`; a typed `@orkestrel/database` failure underneath it (`DatabaseError`)
2855
+ * re-surfaces as a typed `DATABASE` `AgentToolError`, mirroring {@link createDatabaseTool}'s error
2856
+ * mapping; an `AgentToolError` thrown by this tool's own guards (malformed args, an unknown
2857
+ * manager/model) passes through unwrapped.
2858
+ *
2859
+ * @param options - The tool's configuration (see {@link import('./types.js').RelationToolOptions})
2860
+ * @returns A `ToolInterface` (named {@link import('./constants.js').RELATION_TOOL_NAME} by default)
2861
+ *
2862
+ * @example
2863
+ * ```ts
2864
+ * import { createRelationTool } from '@src/core'
2865
+ *
2866
+ * const tool = createRelationTool({ managers: { shop: manager } })
2867
+ * await tool.execute({ operation: 'load', model: 'accounts', key: 'acc1', include: ['contacts'] })
2868
+ * ```
2869
+ */
2870
+ function createRelationTool(options) {
2871
+ const contract = createContract(relationToolShape);
2872
+ const parameters = schemaToParameters(contract.schema);
2873
+ const depth = options.depth ?? 3;
2874
+ const cap = options.limit ?? 1e3;
2875
+ return createTool({
2876
+ name: options.name ?? "relation",
2877
+ description: options.description ?? RELATION_TOOL_DESCRIPTION,
2878
+ summary: RELATION_TOOL_SUMMARY,
2879
+ parameters,
2880
+ execute: async (args) => {
2881
+ const call = contract.parse(args);
2882
+ if (call === void 0) throw new AgentToolError("TOOL", "malformed relation call", { args });
2883
+ try {
2884
+ const model = relationModelOf(relationManagerOf(options.managers, call.manager), call.model);
2885
+ switch (call.operation) {
2886
+ case "load": {
2887
+ const include = expandInclude(call.include, depth);
2888
+ if (typeof call.key === "string" || typeof call.key === "number") return { row: await model.load(call.key, include) };
2889
+ return { rows: await model.load(call.key, include) };
2890
+ }
2891
+ case "find": {
2892
+ const include = expandInclude(call.include, depth);
2893
+ const effective = Math.min(call.limit ?? cap, cap);
2894
+ const rows = await model.find(include, {
2895
+ limit: effective + 1,
2896
+ ...call.offset === void 0 ? {} : { offset: call.offset },
2897
+ ...call.sort === void 0 ? {} : { sort: call.sort },
2898
+ ...call.direction === void 0 ? {} : { direction: call.direction }
2899
+ });
2900
+ const truncated = rows.length > effective;
2901
+ const sliced = rows.slice(0, effective);
2902
+ return {
2903
+ rows: sliced,
2904
+ count: sliced.length,
2905
+ truncated,
2906
+ limit: effective
2907
+ };
2908
+ }
2909
+ case "link":
2910
+ await model.link(call.key, call.relation, call.target);
2911
+ return { linked: true };
2912
+ case "unlink":
2913
+ await model.unlink(call.key, call.relation, call.target);
2914
+ return { unlinked: true };
2915
+ case "links": {
2916
+ const keys = await model.links(call.key, call.relation);
2917
+ const truncated = keys.length > cap;
2918
+ const sliced = keys.slice(0, cap);
2919
+ return {
2920
+ keys: sliced,
2921
+ count: sliced.length,
2922
+ truncated,
2923
+ limit: cap
2924
+ };
2925
+ }
2926
+ }
2927
+ } catch (error) {
2928
+ if (isAgentToolError(error)) throw error;
2929
+ const relation = relationToolCode(error);
2930
+ if (relation !== void 0) throw new AgentToolError("RELATION", error instanceof Error ? error.message : String(error), {
2931
+ code: relation,
2932
+ operation: call.operation,
2933
+ model: call.model,
2934
+ ..."relation" in call ? { relation: call.relation } : {}
2935
+ });
2936
+ const database = databaseToolCode(error);
2937
+ if (database === void 0) throw error;
2938
+ throw new AgentToolError("DATABASE", error instanceof Error ? error.message : String(error), {
2939
+ code: database,
2940
+ operation: call.operation
2941
+ });
2942
+ }
2943
+ }
2944
+ });
2945
+ }
2946
+ /**
2947
+ * Build a standalone LLM-callable tool that infers a JSON Schema from example values — the
2948
+ * utility half of the "existing API/DB → MCP tool" bridge (the other half,
2949
+ * {@link createEndpointTool}, wraps one CONCRETE endpoint).
2950
+ *
2951
+ * @remarks
2952
+ * The universal tool-handler contract (AGENTS §14): validates the call args against
2953
+ * {@link import('./shapers.js').inferToolShape} (`samples` non-empty, `format` / `enum` optional
2954
+ * booleans, `candidates` an optional array), infers a schema via `@orkestrel/contract`'s
2955
+ * `samplesToSchema`, wraps a non-object root as `{ value: <schema> }` via `schemaToObject` (mirrors
2956
+ * the tool-parameters convention every other `create*Tool` factory advertises), and RETURNS the
2957
+ * resulting parameters record. An empty `samples` array fails `inferToolShape`'s `min: 1` bound —
2958
+ * `contract.parse` returns `undefined` and the handler throws a typed `TOOL`
2959
+ * {@link import('./errors.js').AgentToolError}.
2960
+ *
2961
+ * When `candidates` is ABSENT, the return is the bare parameters record — unchanged from before
2962
+ * this array existed. When `candidates` is PRESENT (any array, including empty), the handler
2963
+ * compiles a SEPARATE per-call contract from the RAW inferred schema (via `@orkestrel/contract`'s
2964
+ * `schemaToShape`, NOT the `schemaToObject`-wrapped parameters — a bare-value sample checks a
2965
+ * bare-value candidate) and returns `{ parameters, checks }`, one check per candidate at the same
2966
+ * index. Every entry has a UNIFORM shape — `{ index, valid, coercible }`, with `faults` added ONLY
2967
+ * when `valid` is `false`: `valid` is the STRICT guard verdict (`checker.is(candidate)`), the
2968
+ * OPPOSITE of {@link createEndpointTool}'s enforcement, which coerces (`7` becomes `'7'` for a
2969
+ * string slot) — here a conformance report answers "does this value conform AS-IS": `7` against a
2970
+ * string slot is `valid: false`, full stop. `coercible` answers a SEPARATE question — "would the
2971
+ * NORMALIZING parse accept this value", i.e. would {@link createEndpointTool}'s default enforcement
2972
+ * admit it (`checker.parse(candidate) !== undefined`) — computed for every candidate regardless of
2973
+ * `valid`; by the house parse/guard round-trip guarantee (AGENTS §14), a `valid: true` entry is
2974
+ * ALWAYS also `coercible: true`. `@orkestrel/contract` 0.0.7's `explain` mirrors the normalizing
2975
+ * `parse`'s leniency, not `is`'s strictness — so a strictly-invalid but coercible candidate (`7`
2976
+ * against a string slot) yields `{ valid: false, coercible: true, faults: [] }`: EMPTY faults, since
2977
+ * the mismatch the normalizing parse would silently fix is not one `explain` reports. `faults`
2978
+ * therefore only ever populates for a NON-coercible mismatch — a wrong type the parse can't coerce
2979
+ * (a boolean in a string slot), a missing required key, or an out-of-enum value — where
2980
+ * `coercible: false`. `checker.is` / `.parse` / `.explain` are all total over JSON-safe input — a
2981
+ * JSON-safe hostile candidate (a `__proto__`-carrying object, deeply nested data) reaches all three
2982
+ * and yields a bounded, non-throwing per-candidate verdict; a NON-JSON-safe candidate (e.g. a
2983
+ * throwing-getter `Proxy`) never reaches the checker at all — it fails the OUTER `args` parse
2984
+ * against {@link import('./shapers.js').inferToolShape} and rejects the WHOLE call with the same
2985
+ * `TOOL` {@link import('./errors.js').AgentToolError} a malformed `samples`/`format`/`enum` throws,
2986
+ * with no per-candidate verdict produced.
2987
+ *
2988
+ * @param options - Advertised `name` / `description` overrides (see
2989
+ * {@link import('./types.js').InferToolOptions})
2990
+ * @returns A `ToolInterface` (named {@link import('./constants.js').INFER_TOOL_NAME} by default)
2991
+ *
2992
+ * @example
2993
+ * ```ts
2994
+ * import { createInferTool } from '@src/core'
2995
+ * import { createToolManager } from '@orkestrel/agent'
2996
+ *
2997
+ * const tool = createInferTool()
2998
+ * const tools = createToolManager()
2999
+ * tools.add(tool)
3000
+ *
3001
+ * const result = await tools.execute({
3002
+ * id: 'call-1',
3003
+ * name: 'infer',
3004
+ * arguments: { samples: [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bob' }] },
3005
+ * })
3006
+ * // result.value -> { type: 'object', properties: { id: {...}, name: {...} }, ... }
3007
+ *
3008
+ * // with candidates, the result is wrapped with per-candidate verdicts
3009
+ * const checked = await tools.execute({
3010
+ * id: 'call-2',
3011
+ * name: 'infer',
3012
+ * arguments: {
3013
+ * samples: [{ id: 1, name: 'Ada' }],
3014
+ * candidates: [{ id: 2, name: 'Bob' }, { id: 'x', name: 'Cy' }],
3015
+ * },
3016
+ * })
3017
+ * // checked.value -> { parameters: {...}, checks: [
3018
+ * // { index: 0, valid: true, coercible: true },
3019
+ * // { index: 1, valid: false, coercible: false, faults: [...] },
3020
+ * // ] }
3021
+ * ```
3022
+ */
3023
+ function createInferTool(options) {
3024
+ const contract = createContract(inferToolShape);
3025
+ const parameters = schemaToParameters(contract.schema);
3026
+ return createTool({
3027
+ name: options?.name ?? "infer",
3028
+ description: options?.description ?? INFER_TOOL_DESCRIPTION,
3029
+ summary: INFER_TOOL_SUMMARY,
3030
+ parameters,
3031
+ execute: async (args) => {
3032
+ const parsed = contract.parse(args);
3033
+ if (parsed === void 0) throw new AgentToolError("TOOL", "malformed infer arguments", { args });
3034
+ const schema = samplesToSchema(parsed.samples, {
3035
+ format: parsed.format ?? false,
3036
+ enum: parsed.enum ?? false
3037
+ });
3038
+ const result = schemaToParameters(schemaToObject(schema));
3039
+ if (result === void 0) throw new AgentToolError("TOOL", "could not infer a schema", { args });
3040
+ if (parsed.candidates === void 0) return result;
3041
+ const checker = createContract(schemaToShape(schema));
3042
+ return {
3043
+ parameters: result,
3044
+ checks: parsed.candidates.map((candidate, index) => {
3045
+ const valid = checker.is(candidate);
3046
+ const coercible = checker.parse(candidate) !== void 0;
3047
+ return valid ? {
3048
+ index,
3049
+ valid,
3050
+ coercible
3051
+ } : {
3052
+ index,
3053
+ valid,
3054
+ coercible,
3055
+ faults: checker.explain(candidate)
3056
+ };
3057
+ })
3058
+ };
3059
+ }
3060
+ });
3061
+ }
3062
+ /**
3063
+ * Wrap one CONCRETE endpoint ({@link import('./types.js').EndpointDefinition}) as an LLM-callable
3064
+ * `ToolInterface` — the endpoint half of the "existing API/DB → MCP tool" bridge (the other half,
3065
+ * {@link createInferTool}, is a standalone inference utility).
3066
+ *
3067
+ * @remarks
3068
+ * `parameters` is inferred ONCE at construction from `definition.samples` via
3069
+ * `@orkestrel/contract`'s `samplesToSchema` (tuned by {@link import('./types.js').EndpointToolOptions}'s
3070
+ * `format` / `enum`), wrapping a non-object root as `{ value: <schema> }` via `schemaToObject` —
3071
+ * the SAME object-rooted schema is both the ADVERTISED `parameters` and, by default
3072
+ * ({@link import('./types.js').EndpointToolOptions.validate} `true`), the ENFORCED contract:
3073
+ * `@orkestrel/contract` 0.0.7's `schemaToShape` compiles it ONCE (via `createContract`) into a
3074
+ * `ContractInterface` whose `.parse` runs on every call's `args` before `definition.invoke` — a
3075
+ * NORMALIZING parse, not a strict type check: a scalar is COERCED to its inferred type where the
3076
+ * house parsers coerce (a number to/from a numeric string, a boolean from `'1'`/`'0'`/`'true'`/
3077
+ * `'false'`/`1`/`0`), so `definition.invoke` receives the COERCED value (e.g. `7` sent for a
3078
+ * string slot arrives as `'7'`), not the raw call value. A call whose `args` fails to parse into
3079
+ * a record — a required key missing, or a value not coercible to its slot's type — THROWS a
3080
+ * typed `TOOL` {@link import('./errors.js').AgentToolError} carrying the compiled contract's
3081
+ * structured `explain` faults, and `definition.invoke` is never called. `format` annotations are
3082
+ * NEVER asserted, and a key outside the closed inferred schema is SILENTLY DROPPED rather than
3083
+ * rejected (see {@link import('./types.js').EndpointToolOptions.validate}). With
3084
+ * `validate: false`, `execute` PASSES THROUGH the model-supplied `args` to `definition.invoke`
3085
+ * WITHOUT re-validation — the pre-0.0.7 behavior, preserved as an explicit opt-out. Either way,
3086
+ * `invoke`'s return flows back as the tool call's plain result; a throw PROPAGATES uncaught,
3087
+ * isolated by the `ToolManagerInterface` (`@orkestrel/agent`) into the canonical error envelope
3088
+ * (AGENTS §14) — never caught or re-wrapped here.
3089
+ *
3090
+ * @param definition - The endpoint's identity, non-empty samples, and local handler (see
3091
+ * {@link import('./types.js').EndpointDefinition})
3092
+ * @param options - Construction-time inference tuning + the validate opt-out (see
3093
+ * {@link import('./types.js').EndpointToolOptions})
3094
+ * @returns A `ToolInterface` named `definition.name`
3095
+ *
3096
+ * @example
3097
+ * ```ts
3098
+ * import { createEndpointTool } from '@src/core'
3099
+ * import { createToolManager } from '@orkestrel/agent'
3100
+ *
3101
+ * const tool = createEndpointTool({
3102
+ * name: 'lookupUser',
3103
+ * description: 'Look up a user by id.',
3104
+ * samples: [{ id: '1', name: 'Ada' }, { id: '2', name: 'Bob' }],
3105
+ * invoke: (args) => ({ id: args.id, name: 'Ada' }),
3106
+ * })
3107
+ * const tools = createToolManager()
3108
+ * tools.add(tool)
3109
+ *
3110
+ * // conforming args (all required keys present) parse and reach `invoke`
3111
+ * const result = await tools.execute({
3112
+ * id: 'call-1',
3113
+ * name: 'lookupUser',
3114
+ * arguments: { id: '1', name: 'Ada' },
3115
+ * })
3116
+ * // result.value -> { id: '1', name: 'Ada' }
3117
+ *
3118
+ * // a nonconforming call (id is not coercible to the required string) is rejected before
3119
+ * // `invoke` runs
3120
+ * const rejected = await tools.execute({
3121
+ * id: 'call-2',
3122
+ * name: 'lookupUser',
3123
+ * arguments: { id: true, name: 'Ada' },
3124
+ * })
3125
+ * // rejected.error -> the TOOL AgentToolError message
3126
+ * ```
3127
+ */
3128
+ function createEndpointTool(definition, options) {
3129
+ if (definition.samples.length === 0) throw new AgentToolError("TOOL", "endpoint requires at least one sample", { name: definition.name });
3130
+ const objectSchema = schemaToObject(samplesToSchema(definition.samples, {
3131
+ format: options?.format ?? false,
3132
+ enum: options?.enum ?? false
3133
+ }));
3134
+ const parameters = schemaToParameters(objectSchema);
3135
+ if (!(options?.validate ?? true)) return createTool({
3136
+ name: definition.name,
3137
+ description: definition.description,
3138
+ parameters,
3139
+ execute: (args) => definition.invoke(args)
3140
+ });
3141
+ const contract = createContract(schemaToShape(objectSchema));
3142
+ return createTool({
3143
+ name: definition.name,
3144
+ description: definition.description,
3145
+ parameters,
3146
+ execute: (args) => {
3147
+ const parsed = contract.parse(args);
3148
+ if (parsed === void 0 || !isRecord(parsed)) throw new AgentToolError("TOOL", "malformed endpoint call arguments", {
3149
+ name: definition.name,
3150
+ faults: contract.explain(args)
3151
+ });
3152
+ return definition.invoke(parsed);
3153
+ }
3154
+ });
3155
+ }
1589
3156
  //#endregion
1590
- export { AGENT_TOOL_DEPTH, AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME, AGENT_TOOL_SUMMARY, ANSWER_TOOL_DESCRIPTION, ANSWER_TOOL_NAME, ANSWER_TOOL_SUMMARY, AgentToolError, DESCRIBE_TOOL_DESCRIPTION, DESCRIBE_TOOL_NAME, DESCRIBE_TOOL_SUMMARY, MAX_WORKFLOW_DEPTH, PROMPT_TOOL_DESCRIPTION, PROMPT_TOOL_NAME, PROMPT_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, coerceAnswer, completeDraft, completePhaseDraft, completeTaskDraft, createAgentFunction, createAgentTool, createAnswerTool, createDescribeTool, createPromptTool, createToolFunction, createWorkflowDraftContract, createWorkflowTool, createWorkspaceTool, describeToolShape, expandSteps, isAgentToolError, phaseDraftShape, promptToolShape, stepShape, taskDraftShape, terminalToolCode, workflowDraftShape, workflowStepsShape, workflowTag, workflowToolSummary, workspaceToolShape };
3157
+ 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, 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 };
1591
3158
 
1592
3159
  //# sourceMappingURL=index.js.map