forked from libredb/libredb-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.ts
More file actions
2858 lines (2692 loc) · 142 KB
/
Copy pathtools.ts
File metadata and controls
2858 lines (2692 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The agent's tool layer over the M1 operation pipeline (#329, epic #325).
*
* This is the only place in the agent runtime that reaches a database, and it does
* so through exactly one path: `executeAuditedOperation` (`src/lib/db/operations/`)
* against a provider acquired under the agent read-only execution profile. There is
* no second path, no direct `provider.query()`, and no provider method reached
* outside a registered operation — a reach that skipped this module would be a
* defect by the milestone's own constraint, not a shortcut.
*
* Four properties are load-bearing, and each is asserted rather than asserted-in-prose:
*
* 1. **Tool selection is a server-side function of the run's persisted mode and
* workflow type.** `selectAgentTools` reads nothing else. Planning yields an EMPTY set whatever
* the run is for, and
* a client-supplied tool list has no way in — not because it is filtered, but
* because there is no parameter for it. The same rule is enforced a second time
* at the execution seam, and since the plan-mode grounding design of 2026-08-15
* the seam states it precisely: outside agent mode a call is refused
* (`MODE_HAS_NO_TOOLS`, before the ledger, the deadline or an acquisition) UNLESS
* it is marked `grounding`, which is the server establishing a plan run's context
* before the model's first turn. Nothing a model sends can carry that flag — a
* planning run is still handed an empty tool set, so no dispatch of a model's tool
* call reaches the seam at all — and the two exported grounding entry points
* (`readCatalogForGrounding`, `readStatementForGrounding`) are called by
* `establishContext` with SERVER-composed statements. The property that survives
* unchanged is the one that matters: no model, in any mode, executes anything the
* selector did not offer it. What is NOT claimed is that the seam is a boundary
* against the server's own callers: `readStatementForGrounding` takes arbitrary
* SQL, and what keeps it read-only is the same statement guard, policy, profile
* and audit trail every other call meets, not the mode check.
* 2. **A policy denial is a different KIND of outcome than a database error.** The
* two travel as distinct variants of `AgentToolRefusal` (T2 pinned that union so
* a denial has no readable `message` field at all), and the text handed to the
* model says a boundary decided this, never that the statement was ill-formed.
* Feeding a denial back as if it were bad SQL is what turns a refusal into a
* repair loop against the security layer.
* 3. **The repair loop is bounded and never repeats a failed statement.** Every
* call passes the run's `AgentRepairLedger` first, keyed on a canonical
* fingerprint. A denial records the statement as unrepeatable but does NOT
* consume a repair attempt: nothing ran, and there is nothing to repair.
* 4. **Database content is untrusted input.** Every result and every engine message
* that crosses into a prompt goes through `fenceUntrustedContent` first. Nothing
* in this module hands a model text that a row could have written.
*
* The run's wall-clock deadline (`deadline.ts`) is consulted here too, because this
* is the layer that knows a call is about to be made: `admit` refuses a call that
* no longer fits and clamps the statement timeout down to what is left of the run.
* The clamp is applied by handing the pipeline a policy whose `statementTimeoutMs`
* is the granted value, so the timeout the execution profile receives is the
* pipeline's own `effectiveBudget` — there is no second budget to keep in step.
*
* The provider acquirer is INJECTED rather than imported. Two reasons, both real:
* the spy-provider invariant above needs a seam, and a static import of
* `@/lib/db/factory` would make this module's behaviour depend on whether some
* other test file has replaced that module process-wide (`mock.module` is global —
* five suites already stub the factory). Only the `ExecutionProfile` TYPE is
* imported, so the profile literal still cannot drift from the factory's vocabulary.
*/
import { z } from "zod";
import { type AuditReason, emitAuditEvent } from "@/lib/audit";
import type { ExecutionProfile } from "@/lib/db/factory";
import { ConnectionError, DatabaseConfigError, DatabaseError, PoolExhaustedError, QueryError } from "@/lib/db/errors";
import type { ExecutionArtifactStore } from "@/lib/db/operations/artifacts";
import type { ExecutionBudget, ExecutionBudgetTracker } from "@/lib/db/operations/budgets";
import {
type AgentCuratedReadInput,
type CuratedOperationKind,
agentCuratedReadInput,
} from "@/lib/db/operations/descriptors";
import { actorLabel, executeAuditedOperation } from "@/lib/db/operations/execution";
import { inspectAgentStatement } from "@/lib/db/operations/statement-guard";
import type { ExecutionActor, ExecutionPolicy, PolicyDenyCode, TargetScope } from "@/lib/db/operations/policy";
import type { OperationRegistry } from "@/lib/db/operations/registry";
import type { DatabaseProvider, ProviderCapabilities, ProviderLabels } from "@/lib/db/types";
import { hasOptimizerHint } from "@/lib/sql/optimizer-hints";
import type { ColumnSchema, DatabaseConnection, QueryResult, TableSchema } from "@/lib/types";
import {
type AgentCatalogKind,
AgentComposedSqlError,
composeCatalogRead,
composeEstimatingExplain,
} from "./composed-sql";
import type { AgentDeadlineDenyCode, AgentRunDeadline } from "./deadline";
import {
AGENT_EXECUTION_PROFILE,
AGENT_MINIMUM_CALL_MS,
AGENT_OPERATIONS_PROFILE,
AGENT_WORKFLOW_BUDGETS,
} from "./execution-policy";
import type { AgentRepairDenyCode, AgentRepairLedger } from "./repair-ledger";
import { fingerprintStatement } from "./repair-ledger";
import { evaluateAutoExecute } from "./auto-execute";
import { summarisePlan } from "./plan-summary";
import {
MAX_PROFILE_COLUMNS,
type AgentProfileDepth,
type AgentProfileFinding,
type AgentTableProfile,
composeTableProfile,
findUnindexedForeignKeys,
readTableProfile,
} from "./table-profile";
import type {
AgentArtifactReference,
AgentChartSpec,
AgentContextSnapshot,
AgentEvidenceReference,
AgentPlanSide,
AgentReadingDenyCode,
AgentReportClaim,
AgentRunActor,
AgentRunEvent,
AgentRunMode,
AgentRunRecord,
AgentRunWorkflowType,
AgentToolRefusal,
} from "./types";
import { fenceUntrustedContent } from "./untrusted-content";
/** The tools an agent-mode run may be offered. Nothing else is a tool. */
export type AgentToolName =
| "inspect_schema"
| "run_read_query"
| "inspect_plan"
| "compose_report"
/** Database assessment only: bounded per-table profiling, counts only. */
| "profile_table"
/** Query optimization only: two estimated plans of the same question. */
| "compare_plans"
/** Query optimization only: a change the user may apply. Never executed here. */
| "recommend_change"
/** Operations only: one curated reading of what the engine says about itself. */
| "inspect_operations"
/**
* Which result IS the answer, and how it should be shown. Reaches no database.
*
* Offered by no workflow yet: the record below is the one place a tool set is
* decided, and this slice decides that nothing may call it until the workflow that
* asks for an answer exists.
*/
| "present_answer";
/**
* The canonical operations a tool may drive. `sql.explain.analyze` is a member so
* the approval gate is reachable — and therefore testable — from this layer, NOT
* because a tool maps onto it: no entry in `AGENT_TOOL_DEFINITIONS` names it, and
* its descriptor is default-denied, so the pipeline can only ever answer
* require-approval for it.
*/
export type AgentOperationId =
| "sql.query.read"
| "sql.explain.estimate"
| "sql.explain.analyze"
/** Bounded per-table profiling; #330 T3 reopened the three-descriptor decision. */
| "sql.table.profile"
/**
* A curated operational reading. The one operation on this list that carries no
* statement — see `dbOperationsReadDescriptor` for why it needs its own id.
*/
| "db.operations.read"
/**
* The provider's own schema inspection, driven by the SERVER's grounding read and
* by no tool — see `dbSchemaReadDescriptor` for why it needs its own id. It is on
* this list because the audited path types every operation it runs through it, not
* because a model can ask for it.
*/
| "db.schema.read";
export interface AgentToolDefinition {
readonly name: AgentToolName;
readonly description: string;
/** The contract a caller enforces on the model's arguments before invoking the tool. */
readonly inputSchema: z.ZodType<unknown>;
/** The canonical operation this tool drives; absent for the tool that reaches no database. */
readonly operationId?: AgentOperationId;
}
export type AgentProviderAcquirer = (
connection: DatabaseConnection,
profile: ExecutionProfile,
) => Promise<DatabaseProvider>;
/**
* Everything one run's tool call needs. Note what is NOT here: no execution
* policy (this layer reads the frozen constant, so no caller can widen it) and no
* tool list (the mode decides).
*/
export interface AgentToolContext {
readonly runId: string;
/** The run's PERSISTED mode. The only thing that decides which tools exist. */
readonly mode: AgentRunMode;
/**
* The run's PERSISTED workflow. It decides which tools exist and, through
* `AGENT_WORKFLOW_BUDGETS`, what this run may spend.
*
* Here rather than read from a module-level constant because the ceilings differ
* per workflow: a layer that enforced one constant while the meter stated another
* would be stating a number the server does not enforce. Like `mode`, it can only
* have come from the run record — there is no parameter through which a request
* body could contribute one.
*/
readonly workflowType: AgentRunWorkflowType;
/** The persisted actor — the sole authority for authorizing this call. */
readonly actor: AgentRunActor;
readonly connection: DatabaseConnection;
readonly capabilities: ProviderCapabilities;
/**
* The provider's own vocabulary, read the same way and at the same moment as its
* capabilities (#414).
*
* Here for one job: what this engine CALLS the rows of a schema inventory. Every
* block a run is shown said "table" on every engine until a live drive found what
* that costs on a keyspace — see `inventory-noun.ts`. The alternative was branching
* on `connection.type` in the prompt layer, which `CLAUDE.md` forbids and which
* would have had to be extended by hand for every engine added since.
*
* The whole `ProviderLabels` rather than the two fields the prompts use, because
* the resource is what the provider hands over and narrowing it here would make the
* next sentence that needs `rowName` a second plumbing job.
*/
readonly labels: ProviderLabels;
readonly registry: OperationRegistry;
readonly scope: TargetScope;
readonly tracker: ExecutionBudgetTracker;
readonly artifacts: ExecutionArtifactStore<QueryResult>;
readonly deadline: AgentRunDeadline;
readonly repairs: AgentRepairLedger;
readonly acquireProvider: AgentProviderAcquirer;
/** Injected for the audited-execution elapsed measurement, as in `execution.ts`. */
readonly clock?: () => number;
}
/**
* Why a tool produced no result and no refusal. These are the run loop's own
* outcomes — nothing was attempted at the database and no policy was consulted — so
* they are deliberately not `AgentToolRefusal` variants (T2 pinned that union
* closed, and widening it from here would blur "the boundary said no" with "the run
* decided not to ask").
*/
export type AgentToolUnavailableCode =
| "MODE_HAS_NO_TOOLS"
| "INVALID_TOOL_INPUT"
| "UNVERIFIABLE_EVIDENCE"
/** A cited plan is not an estimating plan THIS run produced. */
| "UNVERIFIABLE_PLAN"
/** The named table is not in the inventory this run captured. */
| "TABLE_NOT_INVENTORIED"
/** The profile ran, and its aggregate row could not be read back. */
| "PROFILE_UNREADABLE"
/** The requested column offset is past the end of the table. */
| "NO_COLUMNS_AT_OFFSET"
/** One plan cited as both sides: a before and an after have to be two plans. */
| "IDENTICAL_PLANS"
/** The statement does not match the card it is offered under. */
| "RECOMMENDATION_SHAPE_MISMATCH"
/** The plan was this run's, and its rows are no longer held to be read. */
| "PLAN_RESULT_RELEASED"
/** This run has already recorded an answer, and a run answers once. */
| "ANSWER_ALREADY_RECORDED"
/** The answer names an artifact this run never produced. */
| "ANSWER_ARTIFACT_UNKNOWN"
/** The answer's result is this run's, and it is not a reading of the DATA. */
| "ANSWER_NOT_A_DATA_READ"
/** The answer's result exists, and no statement this run drafted produced it. */
| "ANSWER_STATEMENT_UNKNOWN"
/** The answer's result was this run's, and its rows are no longer held to be checked. */
| "ANSWER_RESULT_RELEASED"
/** A chart names a column the result does not have. */
| "CHART_COLUMN_NOT_IN_RESULT"
/** A chart's value column does not hold numbers in the rows that were delivered. */
| "CHART_COLUMN_NOT_NUMERIC"
/** A chart of fewer than two rows: the component renders an empty state. */
| "CHART_TOO_FEW_ROWS"
/** The chart type does not fit the columns named. */
| "CHART_SHAPE_MISMATCH"
| AgentDeadlineDenyCode
| AgentRepairDenyCode;
export type AgentToolOutcome =
| { readonly kind: "completed"; readonly artifact: AgentArtifactReference; readonly modelText: string }
| { readonly kind: "refused"; readonly refusal: AgentToolRefusal; readonly modelText: string }
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
export type AgentTableProfileOutcome =
| {
readonly kind: "profiled";
readonly artifact: AgentArtifactReference;
readonly profile: AgentTableProfile;
readonly modelText: string;
}
| { readonly kind: "refused"; readonly refusal: AgentToolRefusal; readonly modelText: string }
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
export type AgentPlanComparisonOutcome =
| {
readonly kind: "compared";
readonly before: AgentPlanSide;
readonly after: AgentPlanSide;
readonly modelText: string;
}
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
/** Everything a `recommendation` event carries except when it happened. */
export type AgentRecommendation = Omit<Extract<AgentRunEvent, { kind: "recommendation" }>, "kind" | "atMs">;
export type AgentRecommendationOutcome =
| { readonly kind: "recommended"; readonly recommendation: AgentRecommendation; readonly modelText: string }
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
/** Everything an `answer-composed` event carries except when it happened. */
export type AgentComposedAnswer = Omit<Extract<AgentRunEvent, { kind: "answer-composed" }>, "kind" | "atMs">;
/** How an answer is to be shown, as the event records it and the description shows it. */
type AgentAnswerPresentation = AgentComposedAnswer["presentation"];
export type AgentAnswerOutcome =
| { readonly kind: "answered"; readonly answer: AgentComposedAnswer; readonly modelText: string }
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
export type AgentReportOutcome =
| { readonly kind: "composed"; readonly claims: readonly AgentReportClaim[]; readonly modelText: string }
| { readonly kind: "unavailable"; readonly reasonCode: AgentToolUnavailableCode; readonly modelText: string };
export interface AgentOperationRequest {
readonly operationId: AgentOperationId;
/** The statement as it will be evaluated — composed by the server for two of the tools. */
readonly sql: string;
/** Prose naming what the result is, for the untrusted-content header. */
readonly label?: string;
/** Declared target dimensions, so a scope allowlist can bound them. */
readonly target?: { readonly catalog?: string; readonly schema?: string };
/**
* Marks this call as the SERVER's own grounding read rather than a tool the model
* asked for — the one thing that may reach a database outside agent mode.
*
* The mode gate below exists to enforce "a planning run's MODEL cannot invoke a
* tool", and it enforced that by refusing every call any planning run made. Since
* the plan-mode grounding design of 2026-08-15 a planning run establishes its
* context server-side before its first turn, exactly as an agent run does, so the
* gate has to distinguish the two things it was conflating. It is spelled as a flag
* on the REQUEST rather than on the context because a context is what the tool
* dispatch already holds: a marker there would travel to every call the dispatch
* makes, while this one can only be set by a caller composing a specific statement.
*
* Nothing else about the call is relaxed. The statement is still server-composed,
* still read-only, still audited, still bounded by the run's budget and deadline,
* and still refused by the same policy — and the model is still handed no tools.
*/
readonly grounding?: boolean;
}
// ============================================================================
// Tool definitions and server-side selection
// ============================================================================
const catalogSelectorSchema = z.strictObject({
/**
* Which inventory to read. Absent means the column inventory, which is what a
* bare catalog inspection has always meant — so a model that never sends this
* field gets exactly the behaviour it got before the field existed.
*/
kind: z.enum(["columns", "relations", "indexes"]).optional(),
schema: z.string().optional(),
table: z.string().optional(),
});
/**
* The same selector, plus the one kind the model is not offered.
*
* `statistics` is composed only while the SERVER establishes a run's context, and it
* is deliberately absent from the model-facing schema above: a kind the tool
* description does not explain is a kind a model would call blind. Both schemas parse
* the same shape otherwise, so the grounding path gets the same argument validation
* rather than a private, unvalidated one.
*/
const groundingSelectorSchema = catalogSelectorSchema.extend({
kind: z.enum(["columns", "relations", "indexes", "statistics"]).optional(),
});
const readStatementSchema = z.strictObject({
sql: z.string().min(1),
/**
* Why the model wrote this statement. Accepted here and NOT recorded at this
* commit: the `statement-drafted` event that carries it (`types.ts`) is emitted by
* the run service, which does not exist yet. It is in the declared contract so the
* model is asked for it from the first run rather than having the tool's shape
* change under it later. Deliberately no `min(1)`: refusing an otherwise valid read
* because its rationale came back blank would be a disproportionate refusal.
*/
rationale: z.string().optional(),
});
const planStatementSchema = z.strictObject({ sql: z.string().min(1) });
const evidenceSchema = z.discriminatedUnion("source", [
z.strictObject({
source: z.literal("artifact"),
correlationId: z.string().min(1),
locator: z.string().min(1).optional(),
}),
z.strictObject({
source: z.literal("context-snapshot"),
fingerprint: z.string().min(1),
locator: z.string().min(1).optional(),
}),
]);
/**
* ONE citation, rendered as the object the schema above accepts (#350).
*
* A function rather than a pair of string constants, because the same two calls
* produce both things that have to agree: the EXAMPLE a description shows, with a
* placeholder where the id goes, and the CONCRETE citation a completed step hands
* over with the id filled in. A model that copies what it was shown is producing
* what the parser was going to accept, because the same code wrote both.
*
* `satisfies AgentEvidenceReference` is what ties them to the durable contract, and
* `tests/unit/lib/agent/tools.test.ts` closes the loop from the other side: it lifts
* every literal object out of each description and parses it through that tool's own
* `inputSchema`, so a description offering a shape the schema refuses fails there
* rather than in a run.
*
* Why it exists at all: the evidence contract is a two-arm discriminated union, and
* two live runs (#350) inferred it wrong from the serialized JSON schema alone — the
* ledger records the model asking itself whether an evidence item is "an array of
* table row objects or strings?" and spending a database round trip on the question.
* Nothing it was TOLD named `source`, `correlationId` or `fingerprint`.
*/
const citeArtifact = (correlationId: string): string =>
JSON.stringify({ source: "artifact", correlationId } satisfies AgentEvidenceReference);
export const citeSnapshot = (fingerprint: string): string =>
JSON.stringify({ source: "context-snapshot", fingerprint } satisfies AgentEvidenceReference);
/**
* The evidence contract in one sentence, said identically wherever it is said.
*
* Exported because `investigation.ts` states it too — in the run's opening rules —
* and two wordings of the same contract would be two things to keep equal, with the
* one that drifted being the one a model followed into a refusal.
*/
export const AGENT_EVIDENCE_CONTRACT = [
`Each evidence item is ONE object: ${citeArtifact("<the artifact id a completed step reported>")} for a result this run read,`,
`or ${citeSnapshot("<the fingerprint of the schema snapshot this run captured>")} for that inventory.`,
'Add "locator" only to point at a part of it.',
].join(" ");
const reportSchema = z.strictObject({
claims: z.array(z.strictObject({ claim: z.string().min(1), evidence: z.array(evidenceSchema).min(1) })).min(1),
});
/**
* A plan comparison names two artifacts and NOTHING else.
*
* Deliberately no statement text: the ledger already records which statement each
* plan inspection explained, so the server joins them itself. A model-supplied
* label would let a comparison attribute a plan to a statement that never produced
* it — the exact mislabelling a before/after claim rests on not doing.
*/
/**
* A profile names a TABLE, never columns and never SQL. The columns come from the
* run's own captured inventory, so a profile cannot be aimed at something the run
* never established exists — the same rule `compare_plans` follows about plans.
*/
const profileSelectorSchema = z.strictObject({
schema: z.string().optional(),
table: z.string().min(1),
depth: z.enum(["basic", "distribution", "pattern"]).optional(),
/** Where in the table's column list to start. The server bounds how many follow. */
fromColumn: z.number().int().min(0).optional(),
});
const planComparisonSchema = z.strictObject({
before: z.string().min(1),
after: z.string().min(1),
});
/**
* The chart types a spec may ask for, as a total record over the durable union.
*
* A record rather than a bare list, for the reason `EVENT_KINDS` is one: the compiler
* is the exhaustiveness check. A type added to `AgentChartSpec` and not offered here
* would be a type the ledger can hold and the model is never told about.
*/
const CHART_TYPES: Readonly<Record<AgentChartSpec["type"], true>> = Object.freeze({
bar: true,
line: true,
area: true,
pie: true,
scatter: true,
"stacked-bar": true,
});
const CHART_TYPE_NAMES = Object.keys(CHART_TYPES) as [AgentChartSpec["type"], ...AgentChartSpec["type"][]];
const chartSpecSchema = z.strictObject({
type: z.enum(CHART_TYPE_NAMES),
x: z.string().min(1),
y: z.array(z.string().min(1)).min(1),
caption: z.string().min(1),
});
/**
* An answer names ONE artifact and how to show it, and nothing else.
*
* Deliberately no statement text, for the reason `compare_plans` takes none: the
* ledger already records which statement produced which result, so the server joins
* them itself. A model-supplied statement would let an answer hand the user a
* statement that produced something other than the result on screen.
*/
const presentAnswerSchema = z.strictObject({
artifact: z.string().min(1),
presentation: z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("table") }),
z.strictObject({ kind: z.literal("chart"), spec: chartSpecSchema }),
]),
});
/**
* A presentation a model sent as a STRING of JSON, read back once before validation.
*
* Measured 2026-08-16: `qwen3.8` called `present_answer` three times with a correct artifact id
* and a correct chart spec — right type, right x, right y, columns spelled as the result spells
* them — and every call was refused as `INVALID_TOOL_INPUT`, because it had serialized the nested
* object rather than nesting it:
*
* {"artifact": "67fb…", "presentation": "{\"kind\": \"chart\", \"spec\": {…}}"}
*
* The run then reported without an answer and was scored `no-answer`, so what a reader saw was a
* model that would not present — while its own closing prose said the presentation "is being
* persistently rejected despite conforming to the declared shape". It was.
*
* Read ONCE and never recursively: this accepts a serialization the model chose, it does not
* invent a second encoding. The value still goes through the same schema, so a string holding the
* wrong shape is refused exactly as the object would have been — nothing is admitted here that
* would not have been admitted written properly.
*
* At the CALL BOUNDARY rather than inside the schema, and that placement is the whole of what
* makes it safe. Wrapping the field in `z.preprocess` instead would produce a `ZodPipe`, and the
* SDK derives the model's copy of the contract from this same object with
* `toJSONSchema(schema, { target: 'draft-7', io: 'input' })`
* (node_modules/@ai-sdk/provider-utils/src/schema.ts:251, reached from `declaredTools()` in
* src/lib/agent/investigation.ts) — where a `ZodPipe` is not counted as a required key. Measured
* over every entry of `AGENT_TOOL_DEFINITIONS` with that wrapper in place, `present_answer` was
* the ONLY tool whose two contracts disagreed: runtime `[artifact, presentation]` against
* advertised `[artifact]`, while all eight others matched exactly. So a model that OBEYED the
* advertised contract would send `artifact` alone and be refused — and because this tool is
* ledger-only, its refusal records no event and the run is scored `no-answer` with nothing saying
* why: the same invisible failure this fix exists to remove, re-created for correct models instead
* of sloppy ones. Reading here leaves the advertised schema byte-identical to what it always was.
*
* That placement puts a dependency between this read and the run loop, and it is worth naming
* because it is invisible from here. The SDK validates the model's arguments against this same
* strict schema BEFORE any of this runs, and a serialized presentation fails it: measured against
* `ai@7.0.59`, `doParseToolCall` throws, the SDK catches it, re-parses the raw JSON without a
* schema and enqueues the tool-call part anyway with `invalid: true`. So this function is reached
* only because `takeTurn` dispatches every tool-call part without consulting that flag
* (src/lib/agent/investigation.ts:1042). Hardening that line to `!part.invalid` would drop the call
* before it arrives here and silently undo this fix — and it is a plausible edit rather than an
* imagined one, because `capability-probe.ts:279` already treats the flag as meaningful
* (`part.invalid !== true`). `tests/isolated/agent-investigation.test.ts` drives the whole path
* through the real SDK so that edit fails a test rather than a run.
*/
function readSerializedPresentation(input: unknown): unknown {
if (typeof input !== "object" || input === null) return input;
const { presentation } = input as { presentation?: unknown };
if (typeof presentation !== "string") return input;
try {
return { ...input, presentation: JSON.parse(presentation) };
} catch {
// Left as the string it was: the schema refuses it, and reporting a parse failure here would
// replace the contract's own wording with this function's.
return input;
}
}
/** ONE presentation, rendered as the object `presentAnswerSchema` accepts for its `presentation`. */
const showAs = (presentation: AgentAnswerPresentation): string => JSON.stringify(presentation);
/**
* The presentation contract in one place, said identically wherever it is said.
*
* The `AGENT_EVIDENCE_CONTRACT` pattern, and it exists for the same reason: the
* EXAMPLE the description shows and the object the parser accepts are produced by the
* same call, so the two cannot disagree. `tests/unit/lib/agent/tools.test.ts` closes
* the loop from the other side — it lifts every literal object out of the description
* and parses it through this tool's own `inputSchema`.
*
* Exported, and it was module-private until the `data-analysis` workflow arrived:
* that workflow's opening rules state the contract too, and the whole point of one
* string is that the description and the rules cannot tell a model two different
* bars for one tool. It is stated in a second file by importing this, never by
* copying it.
*/
export const AGENT_ANSWER_CONTRACT = [
`"presentation" is ONE object: ${showAs({ kind: "table" })} for a table,`,
`or ${showAs({
kind: "chart",
spec: {
type: "bar",
x: "<a column of that result>",
y: ["<a numeric column of that result>"],
caption: "<what the chart shows, in your own words>",
},
})} for a chart.`,
`"type" is one of: ${CHART_TYPE_NAMES.join(", ")}. For several series, name several y columns: there is no separate series field.`,
"Every column a chart names must be a column of THAT result, spelled as the result spells it, and every y column must hold numbers.",
"A chart needs at least two rows; a pie takes exactly one y; a scatter needs a numeric x as well.",
"Present a table when the result is a single number, has one row, or has no numeric column: that is a complete answer, not a lesser one.",
"When the objective asks for a chart and the result can carry one, chart it: the user named the shape of the answer they wanted.",
].join(" ");
const recommendationSchema = z.strictObject({
change: z.enum(["index", "rewrite"]),
statement: z.string().min(1),
rationale: z.string().min(1),
evidence: z.array(evidenceSchema).min(1),
});
export const AGENT_TOOL_DEFINITIONS: Readonly<Record<AgentToolName, AgentToolDefinition>> = Object.freeze({
inspect_schema: {
name: "inspect_schema",
description:
"Read the database's own catalog, optionally narrowed to one schema or table. Pass kind to choose the inventory: columns (the default: tables and their columns), relations (foreign keys) or indexes. The statement is composed by the server; you supply only the selector. On a large database pass a schema or table selector: the result is subject to the same row budget as any read and is refused, not truncated, if it overflows.",
inputSchema: catalogSelectorSchema,
operationId: "sql.query.read",
},
run_read_query: {
name: "run_read_query",
description:
"Run one bounded read-only SQL statement. Writes, DDL and multi-statement text are refused before the database is reached.",
inputSchema: readStatementSchema,
operationId: "sql.query.read",
},
inspect_plan: {
name: "inspect_plan",
description:
"Ask the engine for the ESTIMATED plan of one read-only statement. The plan is described, never executed, so no timings are produced.",
inputSchema: planStatementSchema,
operationId: "sql.explain.estimate",
},
profile_table: {
name: "profile_table",
description:
"Profile one table the run has already inventoried. The server chooses the columns from the captured schema and composes the aggregates; you supply only the table and how deep to go. Depth basic counts rows and missing values, distribution adds distinct counts, pattern adds a shape test for personal data. Only COUNTS are returned — no value is ever read out of a column.",
inputSchema: profileSelectorSchema,
operationId: "sql.table.profile",
},
compare_plans: {
name: "compare_plans",
description:
"Record a before/after comparison of two ESTIMATED plans this run already inspected. Pass the artifact ids of two inspect_plan results; the server reads both plans itself and states how each reaches its rows. Nothing is executed, and no timings exist — the executing form of EXPLAIN is refused by policy.",
inputSchema: planComparisonSchema,
},
recommend_change: {
name: "recommend_change",
description: `Propose one index or one rewrite for the user to apply themselves. The statement is never executed by this run; it is offered to the user's editor. Every recommendation must cite evidence this run produced. ${AGENT_EVIDENCE_CONTRACT}`,
inputSchema: recommendationSchema,
},
inspect_operations: {
name: "inspect_operations",
description:
"Read what the engine says about ITSELF, right now. Pass kind to choose the reading: sessions (who is connected, what each is running, how long it has been running and whether it is blocked), slow-queries (the statements this engine reports as costly), table-stats (row counts and sizes, and dead rows where the engine tracks them), index-stats (size and how many scans each index has served, so an unused one is visible), storage (space and its growth) or health (one row of connection, size and cache figures). No SQL is involved: you name the reading and the server calls the engine's own reporting interface, so these are the readings that work on every engine. limit bounds EVERY kind, and schema narrows the table and index ones; the server applies both itself, so they hold whatever the engine does with them. EVERY READING IS A MOMENT, not a history: it says what is true as it is taken, and calling it twice does not make a trend.",
inputSchema: agentCuratedReadInput,
operationId: "db.operations.read",
},
present_answer: {
name: "present_answer",
description: `Record that one result you have already read IS the answer, and how it should be shown. Only a result of a run_read_query you drafted can be the answer: a plan describes a statement without running it and a profile returns counts about a table, so neither may be presented — both may still be cited as evidence. Pass the artifact id that read reported; the statement behind it comes from this run's own ledger, so you do not supply it. The columns a chart names are checked against that result's real columns and refused if they do not match. Your report must then cite this same artifact in at least one claim: the presentation shows the result and the claims say what it means, so a report resting on other evidence entirely leaves the run scored as not having answered. ${AGENT_ANSWER_CONTRACT}`,
inputSchema: presentAnswerSchema,
},
compose_report: {
name: "compose_report",
description: `Compose the run's findings and finish. Every claim must cite at least one artifact this run read or the schema snapshot it captured; an uncited claim is refused. ${AGENT_EVIDENCE_CONTRACT}`,
inputSchema: reportSchema,
},
} satisfies Record<AgentToolName, AgentToolDefinition>);
const AGENT_MODE_TOOLS: readonly AgentToolDefinition[] = Object.freeze([
AGENT_TOOL_DEFINITIONS.inspect_schema,
AGENT_TOOL_DEFINITIONS.run_read_query,
AGENT_TOOL_DEFINITIONS.inspect_plan,
AGENT_TOOL_DEFINITIONS.compose_report,
]);
/** Planning is toolless. Not "filtered to nothing" — there is nothing to filter. */
const NO_TOOLS: readonly AgentToolDefinition[] = Object.freeze([]);
/**
* Workflow type → the tools that workflow may use (#330 T2).
*
* A total record, so a workflow type added to the contract stops this file compiling
* until somebody decides what it may do. All three name the same set today, and that
* is the honest state rather than a placeholder: M3's two templates are about what
* the model is ASKED to produce and how the run is JUDGED, and the tools that would
* distinguish them — bounded per-table profiling, a monitor snapshot — arrive with
* the templates themselves (#330 T3). What exists now is the seam, in the one place
* a tool set may be decided, so widening one workflow later cannot become a second
* decision about where that decision lives.
*/
/**
* The optimization template's own two, on top of the read-class four.
*
* Offered to ONE workflow rather than added to `AGENT_MODE_TOOLS`, which is what
* makes the axis load-bearing: an investigation that calls `compare_plans` is told
* there is no such tool, because for that run there is not.
*/
const QUERY_OPTIMIZATION_TOOLS: readonly AgentToolDefinition[] = Object.freeze([
...AGENT_MODE_TOOLS,
AGENT_TOOL_DEFINITIONS.compare_plans,
AGENT_TOOL_DEFINITIONS.recommend_change,
]);
/** The assessment template's own tool, on top of the read-class four. */
const DATABASE_ASSESSMENT_TOOLS: readonly AgentToolDefinition[] = Object.freeze([
...AGENT_MODE_TOOLS,
AGENT_TOOL_DEFINITIONS.profile_table,
]);
/**
* The operations template's tools, and the ONLY set that is not built on the
* read-class four.
*
* Deliberately not `[...AGENT_MODE_TOOLS, inspect_operations]`, which is what every
* other template does. All three of the read-class tools this leaves out —
* `inspect_schema`, `run_read_query`, `inspect_plan` — reach the database through
* `provider.queryReadOnly`, which only PostgreSQL and SQLite implement. Offering any
* of them here would reintroduce, tool by tool, the exact engine restriction this
* workflow exists to escape: the run would open on MySQL, be offered a tool, call it,
* and be answered by an acquisition that refuses the engine.
*
* `inspect_schema` was checked rather than assumed, per the spec's condition:
* `inspectSchemaTool` composes a statement and hands it to `executeAgentOperation`,
* whose invoke callback is `runStatement`, which calls `provider.queryReadOnly`. It
* depends on it, so it is left out.
*
* `recommend_change` is here and `compare_plans` is not: a comparison names two
* `inspect_plan` artifacts this run cannot produce, so offering it would be offering
* a tool that can only ever refuse.
*/
const OPERATIONS_TOOLS: readonly AgentToolDefinition[] = Object.freeze([
AGENT_TOOL_DEFINITIONS.inspect_operations,
AGENT_TOOL_DEFINITIONS.recommend_change,
AGENT_TOOL_DEFINITIONS.compose_report,
]);
/**
* The analysis template's two tools, on top of the read-class four.
*
* `present_answer` is the one this workflow's verdict requires, and it is offered
* HERE and nowhere else for exactly that reason: a tool a run's bar never asks for is
* a tool that can only distract it.
*
* `profile_table` is borrowed from the assessment template rather than duplicated,
* and it is borrowed at the design's cheapest recommendation (§5.4). The schema
* carries no row counts, so a 400 M-row fact table and a 12-row lookup table are
* indistinguishable in the inventory, and a `shipped_at` that is 80% null and a
* `placed_at` that is fully populated say which date column the business actually
* fills. Basic depth answers both, costs one statement per table, and reads no value
* out of any column — which is what makes pointing it at a table of personal data
* acceptable at all.
*/
const DATA_ANALYSIS_TOOLS: readonly AgentToolDefinition[] = Object.freeze([
...AGENT_MODE_TOOLS,
AGENT_TOOL_DEFINITIONS.profile_table,
AGENT_TOOL_DEFINITIONS.present_answer,
]);
const WORKFLOW_TOOLS: Readonly<Record<AgentRunWorkflowType, readonly AgentToolDefinition[]>> = Object.freeze({
investigation: AGENT_MODE_TOOLS,
"query-optimization": QUERY_OPTIMIZATION_TOOLS,
"database-assessment": DATABASE_ASSESSMENT_TOOLS,
operations: OPERATIONS_TOOLS,
"data-analysis": DATA_ANALYSIS_TOOLS,
} satisfies Record<AgentRunWorkflowType, readonly AgentToolDefinition[]>);
/**
* The tools this run may use, decided from its persisted mode and workflow type and
* nothing else.
*
* The parameter is the run record (narrowed to the two fields that matter) rather
* than bare strings, so the values can only have come from persisted state. There is
* no parameter through which a request body could contribute a tool, which is what
* "a client-supplied tool list is ignored, not merged" means here.
*
* Mode is checked FIRST and the workflow cannot override it: planning is toolless by
* contract whatever it is for, so a workflow type is never a way to give a planning
* run a tool.
*/
export function selectAgentTools(run: Pick<AgentRunRecord, "mode" | "workflowType">): readonly AgentToolDefinition[] {
return run.mode === "agent" ? WORKFLOW_TOOLS[run.workflowType] : NO_TOOLS;
}
// ============================================================================
// Model-facing text
// ============================================================================
const UNAVAILABLE_TEXT: Readonly<Record<AgentToolUnavailableCode, string>> = Object.freeze({
// "Produce a plan in prose" until 2026-08-15, when the plan-mode design made the
// deliverable ONE runnable statement (or an explicit `NO STATEMENT:` refusal) for
// every workflow but `operations`. This sentence is said to a model that has just
// reached for a tool, which is exactly the moment it must not be handed a second,
// looser contract than the one its rules state: two wordings of one contract is how
// #350 happened. So it says what is true here — nothing can be called — and leaves
// what to produce to the rules that already say it.
MODE_HAS_NO_TOOLS:
"This run is in planning mode, which has no tools at all: no database call is possible from here. Answer with what your instructions asked you to produce.",
// Said by every tool, including the two that reach no database and compose no SQL,
// so it may not promise a statement (#350). `recommend_change` and `compose_report`
// shared a sentence written for the SQL-composing tools, and a model that got an
// evidence object wrong was answered with a sentence about statements.
INVALID_TOOL_INPUT:
"The arguments did not match the shape this tool declares, so nothing was done. Correct them and call the tool again.",
UNVERIFIABLE_EVIDENCE: `At least one evidence reference does not match anything this run produced. Cite an artifact this run actually read, or the schema snapshot it captured. ${AGENT_EVIDENCE_CONTRACT}`,
UNVERIFIABLE_PLAN:
"At least one of those references is not an estimated plan this run produced. Inspect the plan of each statement first, then compare the two artifacts those inspections returned.",
TABLE_NOT_INVENTORIED:
"That table is not in the schema inventory this run captured. Call inspect_schema for it first, then profile it by the name the inventory uses.",
NO_COLUMNS_AT_OFFSET:
"That column offset is past the end of the table, so there is nothing there to profile. Start from an earlier column, or profile a different table.",
PROFILE_UNREADABLE:
"The profile ran but its result could not be read as counts. Try a shallower depth, or profile a different table.",
IDENTICAL_PLANS:
"Both sides of that comparison name the same plan, so there is no before and no after. Inspect the plan of your rewrite as well, then compare the two.",
RECOMMENDATION_SHAPE_MISMATCH:
"That statement is not the kind of change the card claims. An index recommendation must be one CREATE INDEX statement; a rewrite must be one bounded read.",
PLAN_RESULT_RELEASED:
"That plan was this run's, but its rows are no longer held and cannot be read again. Inspect the plan once more if the comparison still matters.",
// The answer refusals each restate the half of the contract they enforce, and each
// one names the way out. A description is read by a model that is not yet confused;
// these are read by one that demonstrably is, and a table is almost always a correct
// answer it can give instead.
//
// This first one is the exception to that shape: nothing about the arguments was
// wrong, so there is no contract half to restate and no second attempt to invite.
// The only thing left for the run to do is say what the answer MEANS.
ANSWER_ALREADY_RECORDED:
"This run has already recorded its answer, and a run answers once: nothing was changed and no second answer was composed. If that answer was the wrong one, say so in your claims. Now call compose_report — the presentation shows the result, the claims are the answer.",
ANSWER_ARTIFACT_UNKNOWN:
"That is not the id of a result this run read, so there is nothing to present. Pass the artifact id a completed read reported in this run, or read the data first.",
ANSWER_NOT_A_DATA_READ:
"That result is this run's, and it is not a reading of the data, so it cannot be the answer: a plan DESCRIBES a statement without running it, and a profile returns counts the server composed about a table. Present the result of a run_read_query you drafted — run the read first if you have not. A plan or a profile can still be cited as evidence in your report.",
ANSWER_STATEMENT_UNKNOWN:
"That result was not produced by a statement you wrote, so there is no statement to put behind the answer. Answer with a read you drafted yourself.",
ANSWER_RESULT_RELEASED:
"That result was this run's, but its rows are no longer held, so a chart's columns cannot be checked against them. Read it again, or present the answer as a table.",
CHART_COLUMN_NOT_IN_RESULT:
"A chart may only name columns of the result it presents, and at least one of these is not one. The result's own column names follow: spell them exactly as they are spelled there, or present the answer as a table.",
CHART_COLUMN_NOT_NUMERIC:
"Every y column of a chart has to hold numbers in the rows that were delivered, and at least one of these does not. Chart a column that holds numbers, or present the answer as a table — a table is a complete answer.",
CHART_TOO_FEW_ROWS:
"A chart needs at least two rows and this result has fewer, so a chart of it would render an empty state. Present the answer as a table: one row is a complete answer, not a lesser one.",
CHART_SHAPE_MISMATCH:
"That chart type does not fit the columns named: a pie takes exactly one y column, and a scatter needs a numeric x as well as a numeric y. Choose a type that fits the columns, or present the answer as a table.",
RUN_DEADLINE_EXCEEDED:
"The run has spent its whole time budget. Stop calling tools and finish with what has already been established.",
INSUFFICIENT_TIME_REMAINING:
"Too little time is left in the run for a call of this size. Ask for something cheaper, or finish now.",
STATEMENT_ALREADY_FAILED:
"This exact statement has already failed in this run. Draft a different statement rather than sending the same one again.",
REPAIR_BUDGET_EXHAUSTED:
"This run has used all of its repair attempts. Stop drafting statements and report what has been established.",
});
/**
* What a denial tells the model it may try next. Three answers, because the codes
* genuinely differ in whether ANYTHING the model can change would help:
*
* - `absolute` — the run is not permitted to do this at all (privilege, risk class,
* budget, a malformed server context). No statement the model writes changes it,
* and saying otherwise invites a repair loop against the security layer.
* - `shape` — the statement fell outside the bounded-read CONTRACT. Not a syntax
* error (the SQL may be perfectly valid), and a differently shaped read genuinely
* can be admitted: the guard refuses `SELECT copy FROM ads` because `copy` reads
* as a side-effect word and admits `SELECT "copy" FROM ads`, which
* `statement-guard.ts` records as the escape hatch. Telling the model not to
* bother is how a legitimate column becomes unreachable for the whole run.
* - `target` — the DECLARED target is outside the run's scope. The statement's
* wording is irrelevant, but a tool that takes a target selector (today
* `inspect_schema`) can be asked for an in-scope one instead.
*
* A total `Record` rather than a comparison against a string: a new
* `PolicyDenyCode` must not silently inherit whichever branch happened to be the
* default. This is the same compiler-mirror pattern `DENY_REASONS` uses in
* `execution.ts` and `DEADLINE_REASONS` uses below.
*
* The advice is keyed on the DENY CODE and not on the tool, which is a real
* imprecision worth naming: for `inspect_schema` and `inspect_plan` the statement is
* server-composed, so an `INPUT_VALIDATION_FAILED` there would be a server defect
* rather than something the model shaped, and `shape`'s "a differently shaped read
* may still be admitted" is advice it cannot act on. Left as-is on purpose. No
* reachable case exists — every composed statement in `composed-sql.ts` is guard-clean
* for both dialects and pinned by a test, and `inspect_plan`'s only model-supplied
* part is the inner statement, which genuinely IS a shape the model chose. A per-tool
* override would therefore be an uncoverable branch under the 100% line gate, which is
* a worse trade than a sentence that is imprecise only in a state that cannot occur.
*/
type DenialAdvice = "absolute" | "shape" | "target";
const DENIAL_ADVICE: Record<PolicyDenyCode, DenialAdvice> = {
UNKNOWN_OPERATION: "absolute",
AMBIGUOUS_OPERATION: "absolute",
MALFORMED_POLICY_CONTEXT: "absolute",
INVALID_ACTOR: "absolute",
TARGET_OUT_OF_SCOPE: "target",
INPUT_VALIDATION_FAILED: "shape",
CAPABILITY_UNSUPPORTED: "absolute",
ROLE_FORBIDDEN: "absolute",
MODE_FORBIDDEN: "absolute",
RISK_EXCEEDS_POLICY: "absolute",
CONCURRENCY_BUDGET_EXCEEDED: "absolute",
STATEMENT_BUDGET_EXCEEDED: "absolute",
TOTAL_RUN_BUDGET_EXCEEDED: "absolute",
};
const DENIAL_ADVICE_TEXT: Record<DenialAdvice, string> = {
absolute:
"This is a decision about what this run is permitted to do at all, not a remark about how the statement is written, so rewording it will not change the answer.",
shape:
"The statement's shape falls outside what a bounded read-only inspection may be, which is a decision about the contract rather than about valid SQL; a differently shaped read may still be admitted.",
target:
"The target this call declared falls outside the scope this run may reach, which is not about how the statement is written; where a tool takes a target selector, an in-scope one may still be admitted.",
};
/**
* The text a policy denial produces. It names the reason code, says a boundary
* decided this, and never describes the statement as ill-formed.
*
* The version is the one that DECIDED — the run's own workflow policy — rather than a
* module-level constant, so what the model is told and what an operator can trace the
* denial back to are the same string.
*/
function denialText(reasonCode: PolicyDenyCode, policyVersion: string): string {
return [
`The database operation layer refused this call: ${reasonCode} (policy ${policyVersion}).`,
DENIAL_ADVICE_TEXT[DENIAL_ADVICE[reasonCode]],
"Choose a different approach that stays inside a bounded read-only inspection.",
].join(" ");
}
/**
* What a refused curated reading tells the model, and both sentences are advice it
* can actually act on.
*
* `READING_OVER_BUDGET`'s advice is only worth giving because `limit` is applied by
* the projection for EVERY kind rather than only by the two provider methods that
* take one — see `runCuratedRead`. Advice a tool cannot honour is worse than none:
* the model would spend its statement budget re-asking for a reading it can never be
* given.
*/
const READING_REFUSAL_TEXT: Record<AgentReadingDenyCode, string> = {
KIND_UNSUPPORTED_BY_PROVIDER:
"This database serves no reading of that kind, so nothing was read. Ask for a different kind, or report what the other readings established — including that this one is unavailable here.",
READING_OVER_BUDGET:
"That reading came back larger than this run may carry, so none of it was kept: a partial reading would be a misleading one. Ask again with a smaller limit; it bounds every kind of reading, not only the ones the engine limits itself.",
};
function approvalText(operationId: string): string {
return [
`The operation ${operationId} is default-denied and needs a human approval this run does not carry, so nothing was executed.`,
"Use the estimating plan inspection instead; it describes a plan without running the statement.",
].join(" ");
}
function unavailable(
reasonCode: AgentToolUnavailableCode,
detail?: string,
): AgentToolOutcome & { kind: "unavailable" } {
const base = UNAVAILABLE_TEXT[reasonCode];
return { kind: "unavailable", reasonCode, modelText: detail === undefined ? base : `${base} (${detail})` };
}
/**
* The bad-input refusal the two evidence-bearing tools give, with the contract in it.
*
* `INVALID_TOOL_INPUT` is shared by every tool, and a selector this layer could not
* read has nothing to do with citing — so the contract is added HERE, at the two call
* sites where the arguments that failed to parse carried evidence, rather than to the
* shared sentence.
*
* Why a refusal restates something the description already said (#350): a description
* is read by a model that is not yet confused, and a refusal is read by one that
* demonstrably is. It got the shape wrong, and this reply is the next thing it reads.
* `UNVERIFIABLE_EVIDENCE` carries the contract in `UNAVAILABLE_TEXT` itself, because
* only these same two tools can produce it.
*/
function invalidEvidenceInput(): AgentToolOutcome & { kind: "unavailable" } {
return {
kind: "unavailable",
reasonCode: "INVALID_TOOL_INPUT",
modelText: `${UNAVAILABLE_TEXT.INVALID_TOOL_INPUT} ${AGENT_EVIDENCE_CONTRACT}`,
};
}
/**
* Renders result rows for a prompt.
*
* `bigint` is replaced rather than left to `JSON.stringify`, which throws on one: