Repository navigation
Expand file tree
/
Copy pathtools.ts
More file actions
4411 lines (4188 loc) · 228 KB
/
Copy pathtools.ts
File metadata and controls
4411 lines (4188 loc) · 228 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,
isStatementReadOperation,
} from "@/lib/db/operations/descriptors";
import { actorLabel, executeAuditedOperation } from "@/lib/db/operations/execution";
import type { ExecutionActor, ExecutionPolicy, PolicyDenyCode, TargetScope } from "@/lib/db/operations/policy";
import type { OperationRegistry } from "@/lib/db/operations/registry";
import type {
Container,
DatabaseObject,
KindCount,
DatabaseProvider,
ObjectDetail,
ObjectKindSpec,
ProviderCapabilities,
ProviderLabels,
ReadOnlyStatementMode,
} from "@/lib/db/types";
import type { ContainerEnumeration } from "@/lib/db/container-walk";
import {
enumerationOf,
kindsByContainer,
scopeGroundingContainers,
scopeReadsUnder,
sessionDefaultContainer,
} from "@/lib/db/container-walk";
import {
applicableKinds,
containerDepth,
enumerableKinds,
isCountSampled,
isCountUnavailable,
kindCountIsListing,
kindNamesWithheld,
} from "@/lib/db/object-kinds";
import { pathKey } from "@/lib/db/object-path";
import { machineColumns } from "@/lib/db/detailed-object";
// The inventory route's bounds, and now nobody's second copy of them: one owner, so the
// agent's grounding walk and `POST /api/db/objects/inventory` cannot come to disagree about
// how much of a database an inventory is. They used to be declared again here, because
// `object-route.ts` imports `next/server` at its top level and the agent tree must not
// (#789). Both are stated again in `docs/AGENT.md`.
import {
INVENTORY_LIMIT,
INVENTORY_PAIR_LIMIT,
INVENTORY_TRUNCATION_REASON,
PAIR_TRUNCATION_REASON,
} from "@/lib/db/inventory-bounds";
import { asBytes, binaryText } from "@/lib/export/binary";
import { nonFiniteWord } from "@/lib/non-finite";
import { hasOptimizerHint } from "@/lib/sql/optimizer-hints";
import {
AGENT_LANGUAGE_COPY,
type AgentStatementArgument,
type AgentStatementLanguageId,
type AgentWorkflowVariant,
PLAN_ESTIMATE_OPERATIONS,
requiredVariant,
} from "./agent-manifest";
import { connectionIdentity, heldSnapshotForConnection } from "./context-snapshot";
import { offersRefusalExamples } from "./models";
import type { ColumnSchema, DatabaseConnection, QueryResult } from "@/lib/types";
import { type ProfileTargetResolution, type ResolvedProfileTarget, resolveProfileTarget } from "./inventory-address";
import { addressableObjects } from "./inventory-objects";
import type { AgentInventory, AgentInventoryObject, AgentUnlistedParent, AgentUnlistedParentsNotNamed } from "./types";
import { composeCatalogRead, composeEstimatingExplain } from "./composed-sql";
import {
type AgentCatalogKind,
type AgentCatalogRead,
AgentComposedSqlError,
type AgentEstimatingExplain,
} from "./composed-sql-primitives";
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 { statementFamilyOf } from "./languages/client";
import { engineServerDialect, runServerPack } from "./languages/engines/server";
import type { AgentFamilyOperationIds, AgentRecommendationCard } from "./languages/pack";
import {
CURATED_CALL_LANGUAGE,
LANGUAGE_BASE_DEFINITIONS,
REFERENCE_RECOMMEND_CHANGE,
REFERENCE_RECOMMENDATION_CARD,
REFERENCE_STATEMENT_DEFINITIONS,
languageServer,
languageServerPack,
} from "./languages/server";
import { evaluateAutoExecute } from "./auto-execute";
import { summarisePlan } from "./plan-summary";
import {
MAX_PROFILE_COLUMNS,
type AgentProfileDepth,
type AgentTableProfile,
composeTableProfile,
findUnindexedForeignKeys,
readTableProfile,
} from "./table-profile";
import {
AGENT_ANSWER_CONTRACT,
AGENT_EVIDENCE_CONTRACT,
READING_REFUSAL_TEXT,
UNAVAILABLE_TEXT,
capturedSnapshot,
catalogSelectorSchema,
describeFindings,
evidenceSchema,
handoverText,
presentAnswerSchema,
profileSelectorSchema,
unavailable,
} from "./tool-contracts";
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"
/** Resource efficiency on a cluster: container usage against requests and limits in one namespace. */
| "inspect_usage"
/** Cluster health: one namespace's workloads, their readiness, restarts, missing resources and probes, and events. */
| "profile_workloads"
/**
* Which result IS the answer, and how it should be shown. Reaches no database.
*
* Offered to `data-analysis` alone: the workflow variants in `agent-manifest.ts` are
* the one place a tool set is decided, and only that workflow's verdict asks for an
* answer.
*/
| "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 =
/**
* 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"
/** Every family's own operations, one row per family in `AgentFamilyOperationIds`. */
| AgentFamilyOperationIds[AgentStatementLanguageId];
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;
/**
* Which model is driving, so a tool can decide per model what to say when it refuses.
*
* Here rather than passed to each refusal because a tool that says no should not need the
* drive to tell it who it is saying no to. Every behaviour added from here defaults to what
* was measured before it and turns on per model, which is what stopped a change from winning
* one cell and quietly costing another.
*/
readonly modelId: 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 run's PERSISTED statement language, absent for `sql`. Like `workflowType`, it
* can only have come from the run record, never from the live connection.
*/
readonly statementLanguage?: AgentStatementLanguageId;
/** 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 inventoried, but not under the schema the call qualified it with.
*
* Split from `TABLE_NOT_INVENTORIED` because the two need different sentences: this one
* is a caller that has the right table and the wrong qualifier, and can be told the name
* to use, while that one has no such table at all.
*/
| "TABLE_QUALIFIER_UNKNOWN"
/** The named table is not in the inventory this run captured. */
| "TABLE_NOT_INVENTORIED"
/**
* More than one inventoried object answers to the spelling, so there is nothing to profile
* YET and nothing missing either.
*
* Split from `TABLE_NOT_INVENTORIED` for the reason the other two were split from it, and
* this is the sharpest case of it: the run read BOTH objects and answered that it had read
* neither. Measured against an inventory of ten relations holding `public.orders` and
* `sales.orders`, a call naming `orders` was told the table was not in the inventory at
* all and then offered the first six profilable names, neither of which was a candidate.
* A model can repair an ambiguity by qualifying its spelling and can do nothing at all
* about an absence, so the candidates travel as the detail (#789).
*/
| "TABLE_SPELLING_AMBIGUOUS"
/**
* The named object IS inventoried, and its declared kind is not one with rows to count.
*
* Split from `TABLE_NOT_INVENTORIED` for the reason `TABLE_QUALIFIER_UNKNOWN` was split
* from it: the inventory a run reads carries the schema's views, sequences and functions
* beside its tables (#789), and a model told "that table is not in the inventory" about a
* name it can SEE in the inventory has been told something it can check and disbelieve.
* Measured on the qualifier case, it then repeats the identical call rather than changing
* it. This one confirms the object and refuses the action.
*/
| "OBJECT_NOT_PROFILABLE"
/**
* A catalog KIND the engine does not serve, refused with the reason and the reading that DOES serve it.
*
* Split from `OBJECT_NOT_PROFILABLE` because the two refuse different things: that one refuses an ACTION on an
* object the inventory holds, and this one refuses a KIND the engine's catalog never answers - MongoDB's
* `relations`, for one, because the engine declares no foreign key at all and an empty block would read as an
* absence it never stated.
*/
| "KIND_REFUSED"
/** A catalog read matched no object at all, so there is nothing to inspect or cite. */
| "CATALOG_MATCHED_NOTHING"
/**
* The object exists, and the documents sampled from it held no field, so there is nothing to describe.
*
* Split from `CATALOG_MATCHED_NOTHING` because the two say opposite things about the object: an engine whose fields
* are inferred from a sample of its documents (MongoDB) answers an empty collection, or a view whose sample is
* empty, with no field at all, and "there is no object of that name" would be false of it.
*/
| "CATALOG_OBJECT_EMPTY"
/**
* An index or relation inventory that exists and declares nothing.
*
* Split from `CATALOG_MATCHED_NOTHING` because the two say opposite things: that one denies
* the object, and this one confirms it and reports an absence. "No secondary index" is an
* answer to an optimization question rather than a failed lookup.
*/
| "CATALOG_INVENTORY_EMPTY"
/** 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"
/** A document index whose keys the captured inventory already lists for that collection. */
| "INDEX_ALREADY_EXISTS"
/** 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"
/**
* The language's own reader refused the statement before the policy pipeline saw it, and its sentence is the
* detail. The pipeline's input stage keeps only a reason code, so without this a model refused for `exec` would read
* only that its read had the wrong shape. SQL has no such reader and never meets it.
*/
| "STATEMENT_NOT_ADMITTED"
| AgentDeadlineDenyCode
| AgentRepairDenyCode;
/**
* A refusal that performed nothing, spelled once because six outcomes carried it identically.
*
* `detail` is what this server said no ABOUT — the validator's field paths, the codes it can
* name — and never what it was sent. It exists because the code alone proved undiagnosable:
* eight `INVALID_TOOL_INPUT` refusals in one evaluated model's run said the shape was wrong
* eight times and never which part.
*/
type AgentToolUnavailable = {
readonly kind: "unavailable";
readonly reasonCode: AgentToolUnavailableCode;
readonly modelText: string;
readonly detail?: string;
};
export type AgentToolOutcome =
| { readonly kind: "completed"; readonly artifact: AgentArtifactReference; readonly modelText: string }
| { readonly kind: "refused"; readonly refusal: AgentToolRefusal; readonly modelText: string }
| AgentToolUnavailable;
export type AgentTableProfileOutcome =
| {
readonly kind: "profiled";
readonly artifact: AgentArtifactReference;
readonly profile: AgentTableProfile;
readonly modelText: string;
}
| { readonly kind: "refused"; readonly refusal: AgentToolRefusal; readonly modelText: string }
| AgentToolUnavailable;
export type AgentPlanComparisonOutcome =
| {
readonly kind: "compared";
readonly before: AgentPlanSide;
readonly after: AgentPlanSide;
readonly modelText: string;
}
| AgentToolUnavailable;
/**
* Everything a `recommendation` event carries except when it happened, arm by arm: `Omit` over the union itself would
* keep only the fields both arms share, and lose the statement of one and the container of the other.
*/
export type AgentRecommendation =
Extract<AgentRunEvent, { kind: "recommendation" }> extends infer Arm
? Arm extends unknown
? Omit<Arm, "kind" | "atMs">
: never
: never;
export type AgentRecommendationOutcome =
| { readonly kind: "recommended"; readonly recommendation: AgentRecommendation; readonly modelText: string }
| AgentToolUnavailable;
/** 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 }
| AgentToolUnavailable;
export type AgentReportOutcome =
| { readonly kind: "composed"; readonly claims: readonly AgentReportClaim[]; readonly modelText: string }
| AgentToolUnavailable;
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;
/**
* The key the descriptor's input carries the statement under: `sql` for `sql.query.read`, `statement` for
* `kubectl.query.read`, `command` for `mongo.query.read`. Absent reads as `sql`, so every server-composed SQL read
* is unchanged. The request keeps `sql` as its own field name because it is this server's text, not the model's
* argument - which is also why a mongo command arrives here as JSON TEXT: the model wrote an object, the language's
* `canonicalize` wrote it out in the order the model wrote it, and every layer from the descriptor to the provider
* reads that one text.
*/
readonly argument?: AgentStatementArgument;
/** 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 };
/**
* What the provider is being asked to do with `sql`: run it, or answer with the
* engine's ESTIMATE of how it would run it. Absent means run it.
*
* Only `inspect_plan` sets it, and only because an estimating plan is not a
* statement prefix on every engine. `ReadOnlyStatementMode` in `db/types.ts`
* carries that argument. It rides on the REQUEST rather than on the descriptor
* because it is a property of the one call, not of the operation: the same
* `sql.explain.estimate` descriptor governs both spellings.
*/
readonly mode?: ReadOnlyStatementMode;
/**
* 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
// ============================================================================
/**
* 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 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.
*/
const planComparisonSchema = z.strictObject({
before: z.string().min(1),
after: z.string().min(1),
});
/**
* 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
* model's copy of the contract is derived from this same object with
* `toJSONSchema(schema, { target: 'draft-7', io: 'input' })`
* (`modelToolJsonSchema()` in src/lib/agent/model-tool-schema.ts, the SDK's own `zod4Schema()`
* conversion 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). Hardening that dispatch 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 `observeProbe()` in `src/lib/agent/capability-probe.ts`
* 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.
*/
/**
* A claims array a model sent as a STRING of JSON, read back once before validation.
*
* The same encoding `readSerializedPresentation` was written for, on the tool that ENDS a run.
* That one costs a presentation; this one costs everything the run did.
*
* Measured on `llama3.1:8b` — the most-pulled tool-capable model on Ollama — five operate runs
* produced SEVENTY `INVALID_TOOL_INPUT` declines and every one was the same line:
*
* the fields that did not match — claims: expected array, received string
*
* The model serialized the array rather than nesting it, roughly fourteen times per run, until
* the turn limit ended the run. By then the sentence is complete — it names the field, the type
* expected and the type that arrived — and the model still cannot act on it. A message can only
* do so much; this is the other half, and the repository already decided that half is worth
* having when it wrote the sibling.
*
* Every bound the sibling states holds here unchanged and for the same reasons: read ONCE and
* never recursively, so this accepts a serialization the model chose rather than inventing a
* second encoding; at the CALL BOUNDARY rather than in the schema, so the contract the SDK
* advertises stays byte-identical; and the value still goes through the same strict 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.
*/
/** Whether `claims` arrived as a string that is not JSON, which no read here can recover. */
function claimsArrivedAsUnparseableText(input: unknown): boolean {
if (typeof input !== "object" || input === null) return false;
const { claims } = input as { claims?: unknown };
if (typeof claims !== "string") return false;
try {
JSON.parse(claims);
return false;
} catch {
return true;
}
}
/**
* What a run is told when its claims arrived as text that is not JSON.
*
* `readSerializedClaims` recovers the case a model serialized properly. This is the case it
* cannot: measured on `llama3.1:8b`, the claims arrive as a PYTHON repr — single quotes
* throughout — with the claim true, the source right and the correlation id one the run actually
* produced. Only the quote character is wrong. Converting it here would be inventing an encoding
* rather than reading one the model chose, and it breaks on the first apostrophe in a sentence.
*
* What was wrong was the sentence. `claims: expected array, received string` is true and, to a
* model that believes it sent an array, unusable — across five assess runs it re-sent the
* identical bytes THIRTY times. This names the fault and what a JSON array requires, and quotes
* nothing the model wrote: the rule the refusals here are bounded by is that a server sentence
* carries the path and the shape, never the value.
*/
const AGENT_CLAIMS_NOT_JSON =
"Your claims argument arrived as TEXT rather than as an array, and it is not JSON either. Send the array itself as the argument value — not a string containing it. If your tooling can only send a string, it must be JSON: double quotes around every key and every string value, never single quotes.";
function readSerializedClaims(input: unknown): unknown {
if (typeof input !== "object" || input === null) return input;
const { claims } = input as { claims?: unknown };
if (typeof claims !== "string") return input;
try {
return { ...input, claims: JSON.parse(claims) };
} catch {
// Left as the string it was, for the sibling's reason: the schema refuses it, and reporting a
// parse failure here would replace the contract's own wording with this function's.
return input;
}
}
/**
* A key that is the schema's own name wearing an affix, moved onto the field it names.
*
* `renamesAmong` works this pairing out already and has stated it in the refusal since #4xx -
* "rename artifact_id to artifact" - and the models kept re-sending the same key. Measured twice:
* `llama3.1:8b` had `present_answer` declined in all five analyze runs, never once on the value it
* carried, and the 2026-09-17 argument capture found the same call again, five of seventeen
* refusals, `{"artifact_id": "<a real id>"}` with nothing wrong but the key.
*
* Naming it left the model two sentences - a field absent AND a field surplus - for what is one
* displaced key plus, here, one genuine omission. Reading the key leaves one sentence about the one
* thing actually missing, which is the difference between a refusal a model can act on and a wall.
*
* The pairing rule is `renamesAmong`'s, deliberately: the two names must be the same word once
* punctuation and case are set aside, one possibly carrying an affix the other does not, and each
* side is claimed once so two surplus keys can never both land on one field. A confident rename to
* the WRONG field would be worse than the two sentences it replaces.
*/
function readNearMissKeys(input: unknown, keys: readonly string[]): unknown {
if (typeof input !== "object" || input === null || Array.isArray(input)) return input;
const read = { ...(input as Record<string, unknown>) };
const bare = (name: string): string => name.toLowerCase().replaceAll(/[^a-z0-9]/g, "");
const absent = keys.filter((key) => read[key] === undefined);
const claimed = new Set<string>();
for (const key of Object.keys(read)) {
if (keys.includes(key)) continue;
const match = absent.find(
(name) => !claimed.has(name) && (bare(key).includes(bare(name)) || bare(name).includes(bare(key))),
);
if (match === undefined) continue;
claimed.add(match);
read[match] = read[key];
delete read[key];
}
return read;
}
/**
* The two ways a run that HAS its answer fails to say how to show it.
*
* Measured 2026-09-19 with the argument capture left on for a whole sweep: 206 of 221 refused calls
* are these two, and both belong to the two models whose `data-analysis` cell sits at 0/5. Neither
* is a model that failed to do the work - both read the data, produced the artifact, and lost the
* run at the rendering.
*
* A SPEC ON A TABLE. 113 refusals, all one model, all shaped like
* `{"kind":"table","spec":{"x":"total_rows","y":9488,"caption":"Total rows"}}`. It is not a chart
* and could not become one - no `type`, and `y` holds a number where a list of columns goes. It
* is a caption the model wanted to hang on a table. `kind` is explicit, so the surplus goes and
* the table stays: a decoration is not a reason to discard the answer.
*
* NO PRESENTATION AT ALL. 93 refusals of `{"artifact":"<a real id>"}`. This reverses the line
* drawn on 2026-09-17, when the same call was left refused because defaulting it would be the
* server choosing how the user's answer is displayed. The measurement is what changed the
* reading: a table is not a choice between renderings, it is this contract's own statement that
* a result shown as itself is a complete answer - and the alternative on offer was never a better
* rendering, it was no answer at all.
*
* Bounded to an ABSENT presentation. One that arrived and failed to validate is a model saying
* something specific, and overriding that would be the server choosing: `{"kind":"spreadsheet"}`
* stays refused.
*/
function readMisrenderedPresentation(input: unknown): unknown {
if (typeof input !== "object" || input === null || Array.isArray(input)) return input;
const read = { ...(input as Record<string, unknown>) };
if (read["artifact"] === undefined) return read;
const { presentation } = read;
if (presentation === undefined) return { ...read, presentation: { kind: "table" } };
if (typeof presentation !== "object" || presentation === null || Array.isArray(presentation)) return read;
const shown = presentation as Record<string, unknown>;
/*
A table keeps `kind` and nothing else.
The first version dropped `spec` by name and left three more surplus keys that models use for
the same purpose - 47 further refusals in one sweep: `data` holding the row, `rows` holding the
list, `columns` holding name/value pairs. The model is pasting the RESULT into the presentation,
which it never needs to: the artifact beside it already names those rows and `presentation` only
says how to show them. Dropping by name is the mistake that produced the second round.
Safe because a table takes no options at all. A CHART is left untouched - its `spec` IS the
instruction, and discarding an unrecognised key there could change the picture silently.
*/
if (shown["kind"] === "table") {
return Object.keys(shown).length === 1 ? read : { ...read, presentation: { kind: "table" } };
}
return read;
}
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;
}
}
/**
* The one-line skeleton of the `present_answer` CALL, for failures in the wrapper rather than
* in the presentation inside it.
*
* `AGENT_ANSWER_CONTRACT` above describes `presentation` in full — chart types, y columns, when
* a table is the right answer — and never says what the call itself looks like. Measured across
* every data-analysis and query-optimization loss on record (423 runs): `present_answer` is 1023
* of 1887 `INVALID_TOOL_INPUT` refusals, more than `compose_report` and `recommend_change`
* together, and its three commonest details are all the wrapper: `artifact: expected string`
* (409), `the arguments object: remove presentation` (184), `evidence: expected array` (154). A
* model that misplaced the id was answered with a careful explanation of the half it got right.
*
* Ungated, on the same split `AGENT_CLAIM_SHAPE` makes: one line stating the contract goes to
* every model, while `exampleAnswerCall` — a whole call rebuilt from this run's ledger — stays
* behind `refusalExamples`.
*/
const AGENT_ANSWER_SHAPE =
'The call is ONE object: {"artifact": "<the id a completed step reported>", "presentation": { ... }} — "artifact" is that id as a plain string, and nothing else belongs beside these two fields.';
/**
* Whether the arguments failed in the WRAPPER rather than inside `presentation`.
*
* A wrong chart type is a fault in the object the contract already explains at length, and
* answering it with the wrapper's shape would bury the one word that has to change.
*/
function isAnswerShapeFailure(problems: string): boolean {
return /\bartifact:|arguments object:|^presentation: |\bpresentation: expected/.test(problems);
}
export const AGENT_TOOL_DEFINITIONS: Readonly<Record<AgentToolName, AgentToolDefinition>> = Object.freeze({
...REFERENCE_STATEMENT_DEFINITIONS,
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: REFERENCE_RECOMMEND_CHANGE,
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",
},
...LANGUAGE_BASE_DEFINITIONS,
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>);
/**
* The definition a run of `workflow` in `language` is offered for the tool `name`.
*
* Every SQL run, and every run recorded before languages existed, reads the record above unchanged, which is what
* keeps the SQL tool schemas byte-identical. A workflow on a later language overrides only the entries whose argument
* it names differently; the lookup is here so that the run loop's offer and its dispatch read the same definition.
*/
export function agentToolDefinition(
language: AgentStatementLanguageId | undefined,
workflow: AgentRunWorkflowType,
name: AgentToolName,
): AgentToolDefinition {
return (
languageServerPack(statementFamilyOf(language)).toolOverrides[workflow]?.[name] ?? AGENT_TOOL_DEFINITIONS[name]
);
}
/** 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), read from the workflow's
* variant in `agent-manifest.ts`, which is the one place a tool set is decided.
*
* Memoised per VARIANT, not per workflow or language, so a run is handed the same
* frozen array on every turn, as it was when each set was a constant here, and so two
* variants of one workflow can never share a set by accident.
*/
const VARIANT_TOOLS = new WeakMap<AgentWorkflowVariant, readonly AgentToolDefinition[]>();
function workflowTools(
language: AgentStatementLanguageId | undefined,
workflow: AgentRunWorkflowType,
): readonly AgentToolDefinition[] {
const variant = requiredVariant(language, workflow);
let tools = VARIANT_TOOLS.get(variant);
if (tools === undefined) {
tools = Object.freeze(variant.tools.map((name) => agentToolDefinition(language, workflow, name)));
VARIANT_TOOLS.set(variant, tools);
}
return tools;
}
/**
* The tools this run may use, decided from its persisted mode, workflow type and
* statement language and nothing else.
*
* The parameter is the run record (narrowed to the three 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" | "statementLanguage">,
): readonly AgentToolDefinition[] {
return run.mode === "agent" ? workflowTools(run.statementLanguage, run.workflowType) : NO_TOOLS;
}
// ============================================================================
// Model-facing text
// ============================================================================
/**
* 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