prefix-safe-json 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +57 -3
  2. package/dist/coordinator/coordinator.d.ts +53 -0
  3. package/dist/coordinator/coordinator.d.ts.map +1 -0
  4. package/dist/coordinator/coordinator.js +477 -0
  5. package/dist/coordinator/coordinator.js.map +1 -0
  6. package/dist/coordinator/diagnostic-codes.d.ts +37 -0
  7. package/dist/coordinator/diagnostic-codes.d.ts.map +1 -0
  8. package/dist/coordinator/diagnostic-codes.js +48 -0
  9. package/dist/coordinator/diagnostic-codes.js.map +1 -0
  10. package/dist/coordinator/protocol.d.ts +62 -0
  11. package/dist/coordinator/protocol.d.ts.map +1 -0
  12. package/dist/coordinator/protocol.js +2 -0
  13. package/dist/coordinator/protocol.js.map +1 -0
  14. package/dist/coordinator/types.d.ts +104 -0
  15. package/dist/coordinator/types.d.ts.map +1 -0
  16. package/dist/coordinator/types.js +7 -0
  17. package/dist/coordinator/types.js.map +1 -0
  18. package/dist/diagnostics/codes.d.ts +24 -0
  19. package/dist/diagnostics/codes.d.ts.map +1 -0
  20. package/dist/diagnostics/codes.js +28 -0
  21. package/dist/diagnostics/codes.js.map +1 -0
  22. package/dist/diagnostics/factory.d.ts +8 -0
  23. package/dist/diagnostics/factory.d.ts.map +1 -0
  24. package/dist/diagnostics/factory.js +17 -0
  25. package/dist/diagnostics/factory.js.map +1 -0
  26. package/dist/gate/decide.d.ts +27 -0
  27. package/dist/gate/decide.d.ts.map +1 -0
  28. package/dist/gate/decide.js +179 -0
  29. package/dist/gate/decide.js.map +1 -0
  30. package/dist/gate/gate.d.ts +25 -0
  31. package/dist/gate/gate.d.ts.map +1 -0
  32. package/dist/gate/gate.js +96 -0
  33. package/dist/gate/gate.js.map +1 -0
  34. package/dist/gate/types.d.ts +184 -0
  35. package/dist/gate/types.d.ts.map +1 -0
  36. package/dist/gate/types.js +2 -0
  37. package/dist/gate/types.js.map +1 -0
  38. package/dist/grammar/frame.d.ts +58 -0
  39. package/dist/grammar/frame.d.ts.map +1 -0
  40. package/dist/grammar/frame.js +87 -0
  41. package/dist/grammar/frame.js.map +1 -0
  42. package/dist/grammar/pointer.d.ts +10 -0
  43. package/dist/grammar/pointer.d.ts.map +1 -0
  44. package/dist/grammar/pointer.js +20 -0
  45. package/dist/grammar/pointer.js.map +1 -0
  46. package/dist/grammar/stack.d.ts +73 -0
  47. package/dist/grammar/stack.d.ts.map +1 -0
  48. package/dist/grammar/stack.js +168 -0
  49. package/dist/grammar/stack.js.map +1 -0
  50. package/dist/guard/ai-sdk.d.ts +48 -0
  51. package/dist/guard/ai-sdk.d.ts.map +1 -0
  52. package/dist/guard/ai-sdk.js +51 -0
  53. package/dist/guard/ai-sdk.js.map +1 -0
  54. package/dist/guard/provider-guard.d.ts +4 -0
  55. package/dist/guard/provider-guard.d.ts.map +1 -0
  56. package/dist/guard/provider-guard.js +38 -0
  57. package/dist/guard/provider-guard.js.map +1 -0
  58. package/dist/guard/types.d.ts +48 -0
  59. package/dist/guard/types.d.ts.map +1 -0
  60. package/dist/guard/types.js +2 -0
  61. package/dist/guard/types.js.map +1 -0
  62. package/dist/index.d.ts +85 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +99 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/lexer/scanner.d.ts +106 -0
  67. package/dist/lexer/scanner.d.ts.map +1 -0
  68. package/dist/lexer/scanner.js +658 -0
  69. package/dist/lexer/scanner.js.map +1 -0
  70. package/dist/lexer/states.d.ts +31 -0
  71. package/dist/lexer/states.d.ts.map +1 -0
  72. package/dist/lexer/states.js +35 -0
  73. package/dist/lexer/states.js.map +1 -0
  74. package/dist/lexer/tokens.d.ts +22 -0
  75. package/dist/lexer/tokens.d.ts.map +1 -0
  76. package/dist/lexer/tokens.js +22 -0
  77. package/dist/lexer/tokens.js.map +1 -0
  78. package/dist/limits.d.ts +14 -0
  79. package/dist/limits.d.ts.map +1 -0
  80. package/dist/limits.js +23 -0
  81. package/dist/limits.js.map +1 -0
  82. package/dist/parser.d.ts +6 -0
  83. package/dist/parser.d.ts.map +1 -0
  84. package/dist/parser.js +922 -0
  85. package/dist/parser.js.map +1 -0
  86. package/dist/providers/adapter.d.ts +10 -0
  87. package/dist/providers/adapter.d.ts.map +1 -0
  88. package/dist/providers/adapter.js +2 -0
  89. package/dist/providers/adapter.js.map +1 -0
  90. package/dist/providers/ai-sdk.d.ts +63 -0
  91. package/dist/providers/ai-sdk.d.ts.map +1 -0
  92. package/dist/providers/ai-sdk.js +240 -0
  93. package/dist/providers/ai-sdk.js.map +1 -0
  94. package/dist/providers/anthropic.d.ts +45 -0
  95. package/dist/providers/anthropic.d.ts.map +1 -0
  96. package/dist/providers/anthropic.js +112 -0
  97. package/dist/providers/anthropic.js.map +1 -0
  98. package/dist/providers/gemini.d.ts +31 -0
  99. package/dist/providers/gemini.d.ts.map +1 -0
  100. package/dist/providers/gemini.js +94 -0
  101. package/dist/providers/gemini.js.map +1 -0
  102. package/dist/providers/openai-compatible.d.ts +33 -0
  103. package/dist/providers/openai-compatible.d.ts.map +1 -0
  104. package/dist/providers/openai-compatible.js +160 -0
  105. package/dist/providers/openai-compatible.js.map +1 -0
  106. package/dist/providers/openai.d.ts +55 -0
  107. package/dist/providers/openai.d.ts.map +1 -0
  108. package/dist/providers/openai.js +263 -0
  109. package/dist/providers/openai.js.map +1 -0
  110. package/dist/providers/openrouter.d.ts +35 -0
  111. package/dist/providers/openrouter.d.ts.map +1 -0
  112. package/dist/providers/openrouter.js +55 -0
  113. package/dist/providers/openrouter.js.map +1 -0
  114. package/dist/semantic/builder.d.ts +55 -0
  115. package/dist/semantic/builder.d.ts.map +1 -0
  116. package/dist/semantic/builder.js +140 -0
  117. package/dist/semantic/builder.js.map +1 -0
  118. package/dist/semantic/events.d.ts +2 -0
  119. package/dist/semantic/events.d.ts.map +1 -0
  120. package/dist/semantic/events.js +5 -0
  121. package/dist/semantic/events.js.map +1 -0
  122. package/dist/semantic/snapshot.d.ts +56 -0
  123. package/dist/semantic/snapshot.d.ts.map +1 -0
  124. package/dist/semantic/snapshot.js +230 -0
  125. package/dist/semantic/snapshot.js.map +1 -0
  126. package/dist/types.d.ts +156 -0
  127. package/dist/types.d.ts.map +1 -0
  128. package/dist/types.js +5 -0
  129. package/dist/types.js.map +1 -0
  130. package/dist/utf8/decoder.d.ts +53 -0
  131. package/dist/utf8/decoder.d.ts.map +1 -0
  132. package/dist/utf8/decoder.js +323 -0
  133. package/dist/utf8/decoder.js.map +1 -0
  134. package/package.json +2 -1
@@ -0,0 +1,25 @@
1
+ import { CoordinatorLimits, JsonSchemaLike } from "../coordinator/types.js";
2
+ import { ParserOptions } from "../types.js";
3
+ import { ToolCallExecutionGate } from "./types.js";
4
+ /**
5
+ * Creates a fail-closed execution-decision gate for streamed LLM tool calls.
6
+ * Wraps a `ToolCallStreamCoordinator` (same constructor arguments) and adds
7
+ * exactly one operation: turn each call's settled state into an
8
+ * `ExecutionDecision` (`execute` / `retry` / `reject`) via a deterministic,
9
+ * fully-typed decision table. See `docs/EXECUTION_GATE.md`.
10
+ *
11
+ * ```ts
12
+ * const gate = createToolCallExecutionGate(undefined, undefined, {
13
+ * write_file: { type: "object", required: ["path", "content"], properties: {
14
+ * path: { type: "string" }, content: { type: "string" } } },
15
+ * });
16
+ * for (const raw of providerEvents) {
17
+ * for (const normalized of adapter.push(raw)) gate.push(normalized);
18
+ * }
19
+ * for (const decision of gate.finish().decisions) {
20
+ * if (decision.action === "execute") await tools[decision.name](decision.value);
21
+ * }
22
+ * ```
23
+ */
24
+ export declare function createToolCallExecutionGate(limits?: Partial<CoordinatorLimits>, parserOptions?: ParserOptions, toolSchemas?: Record<string, JsonSchemaLike>): ToolCallExecutionGate;
25
+ //# sourceMappingURL=gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gate.d.ts","sourceRoot":"","sources":["../../src/gate/gate.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,iBAAiB,EAEjB,cAAc,EAGf,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,OAAO,EAEL,qBAAqB,EAEtB,MAAM,YAAY,CAAC;AA+EpB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,2BAA2B,CACzC,MAAM,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,EACnC,aAAa,CAAC,EAAE,aAAa,EAC7B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,GAC3C,qBAAqB,CAEvB"}
@@ -0,0 +1,96 @@
1
+ // ---------------------------------------------------------------------------
2
+ // ToolCallExecutionGate — high-level execution safety layer.
3
+ //
4
+ // Built by composition over ToolCallStreamCoordinator, not by extending or
5
+ // reimplementing it: the gate holds a coordinator instance and adds exactly
6
+ // one thing coordinator state doesn't already capture - which stream-end
7
+ // reason actually got applied - then maps every ToolCallState through the
8
+ // pure decideExecution() table. No re-parsing, no duplicate event pipeline.
9
+ // ---------------------------------------------------------------------------
10
+ import { createToolCallStreamCoordinator } from "../coordinator/coordinator.js";
11
+ import { decideExecution } from "./decide.js";
12
+ class DefaultToolCallExecutionGate {
13
+ coordinator;
14
+ // Mirrors the coordinator's own "first provider_stream_end (from push(),
15
+ // or from finish()'s meta if none arrived) wins" rule - see push()/finish()
16
+ // below and DefaultToolCallStreamCoordinator.finish()'s matching
17
+ // `if (!this.isFinished)` guard. streamEndProviderReason is captured
18
+ // alongside streamEndReason purely for DecisionEvidence.providerReason -
19
+ // it is never read by decideExecution()'s own logic.
20
+ streamEndReason;
21
+ streamEndProviderReason;
22
+ streamEndCaptured = false;
23
+ constructor(limits, parserOptions, toolSchemas) {
24
+ this.coordinator = createToolCallStreamCoordinator(limits, parserOptions, toolSchemas);
25
+ }
26
+ push(event) {
27
+ if (event.type === "provider_stream_end" && !this.streamEndCaptured) {
28
+ this.streamEndCaptured = true;
29
+ this.streamEndReason = event.reason;
30
+ this.streamEndProviderReason = event.providerReason;
31
+ }
32
+ return this.coordinator.push(event);
33
+ }
34
+ snapshot() {
35
+ const snap = this.coordinator.snapshot();
36
+ const ctx = {
37
+ // Pre-finish, no stream-end reason has been observed yet ("unknown"
38
+ // is a neutral placeholder here, not a claim anything went wrong) -
39
+ // every in-flight call is still "collecting" regardless, so this
40
+ // never influences whether something looks executable.
41
+ streamEndReason: this.streamEndReason ?? "unknown",
42
+ streamEndProviderReason: this.streamEndProviderReason,
43
+ diagnostics: snap.diagnostics,
44
+ };
45
+ return snap.calls.map((call) => decideExecution(call, ctx));
46
+ }
47
+ drainEvents() {
48
+ return this.coordinator.drainEvents();
49
+ }
50
+ finish(meta) {
51
+ if (!this.streamEndCaptured) {
52
+ this.streamEndCaptured = true;
53
+ this.streamEndReason = meta?.reason ?? "unknown";
54
+ this.streamEndProviderReason = meta?.providerReason;
55
+ }
56
+ const result = this.coordinator.finish(meta);
57
+ const diagnostics = this.coordinator.snapshot().diagnostics;
58
+ // Unlike snapshot() above, this point is only ever reached after
59
+ // streamEndCaptured is guaranteed true (set on entry to this method, or
60
+ // already true from an earlier push()/finish() call) - and every path
61
+ // that sets streamEndCaptured sets streamEndReason to a defined value in
62
+ // the same branch, so the pre-finish "unknown" placeholder never applies
63
+ // here.
64
+ const ctx = {
65
+ streamEndReason: this.streamEndReason,
66
+ streamEndProviderReason: this.streamEndProviderReason,
67
+ diagnostics,
68
+ };
69
+ const decisions = result.calls.map((call) => decideExecution(call, ctx));
70
+ return { decisions, diagnostics };
71
+ }
72
+ }
73
+ /**
74
+ * Creates a fail-closed execution-decision gate for streamed LLM tool calls.
75
+ * Wraps a `ToolCallStreamCoordinator` (same constructor arguments) and adds
76
+ * exactly one operation: turn each call's settled state into an
77
+ * `ExecutionDecision` (`execute` / `retry` / `reject`) via a deterministic,
78
+ * fully-typed decision table. See `docs/EXECUTION_GATE.md`.
79
+ *
80
+ * ```ts
81
+ * const gate = createToolCallExecutionGate(undefined, undefined, {
82
+ * write_file: { type: "object", required: ["path", "content"], properties: {
83
+ * path: { type: "string" }, content: { type: "string" } } },
84
+ * });
85
+ * for (const raw of providerEvents) {
86
+ * for (const normalized of adapter.push(raw)) gate.push(normalized);
87
+ * }
88
+ * for (const decision of gate.finish().decisions) {
89
+ * if (decision.action === "execute") await tools[decision.name](decision.value);
90
+ * }
91
+ * ```
92
+ */
93
+ export function createToolCallExecutionGate(limits, parserOptions, toolSchemas) {
94
+ return new DefaultToolCallExecutionGate(limits, parserOptions, toolSchemas);
95
+ }
96
+ //# sourceMappingURL=gate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gate.js","sourceRoot":"","sources":["../../src/gate/gate.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6DAA6D;AAC7D,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,0EAA0E;AAC1E,4EAA4E;AAC5E,8EAA8E;AAE9E,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAUhF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAO9C,MAAM,4BAA4B;IACf,WAAW,CAA4B;IAExD,yEAAyE;IACzE,4EAA4E;IAC5E,iEAAiE;IACjE,qEAAqE;IACrE,yEAAyE;IACzE,qDAAqD;IAC7C,eAAe,CAA8B;IAC7C,uBAAuB,CAAqB;IAC5C,iBAAiB,GAAG,KAAK,CAAC;IAElC,YACE,MAAmC,EACnC,aAA6B,EAC7B,WAA4C;QAE5C,IAAI,CAAC,WAAW,GAAG,+BAA+B,CAAC,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;IACzF,CAAC;IAED,IAAI,CAAC,KAAgC;QACnC,IAAI,KAAK,CAAC,IAAI,KAAK,qBAAqB,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YACpE,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC9B,IAAI,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AAE,IAAI,CAAC,eAAkC;YACxD,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW;SACZ,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;QAEzE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;IACpC,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,2BAA2B,CACzC,MAAmC,EACnC,aAA6B,EAC7B,WAA4C;IAE5C,OAAO,IAAI,4BAA4B,CAAC,MAAM,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,184 @@
1
+ import { JsonValue, Diagnostic } from "../types.js";
2
+ import { CoordinatorDiagnostic, CoordinatorPushResult, ToolCallCoordinatorEvent } from "../coordinator/types.js";
3
+ import { NormalizedToolStreamEvent, ProviderName, StreamEndReason } from "../coordinator/protocol.js";
4
+ /**
5
+ * What to do with a tool call right now.
6
+ *
7
+ * - `"execute"`: the arguments are complete, unfabricated, and (if a schema
8
+ * was registered for this tool) schema-valid. Safe to run.
9
+ * - `"retry"`: the provider's output was incomplete or truncated. There is
10
+ * nothing wrong with the data received so far - there just isn't a
11
+ * trustworthy complete value yet. Re-request/continue generation.
12
+ * - `"reject"`: the data itself is the problem (malformed JSON, a schema
13
+ * mismatch, a resource limit, a provider-side error, or a content-policy
14
+ * termination). Re-sending the exact same partial input will not fix it.
15
+ */
16
+ export type ExecutionAction = "execute" | "retry" | "reject";
17
+ /**
18
+ * Machine-readable classification of *why* an `ExecutionAction` was chosen.
19
+ * See `docs/EXECUTION_GATE.md` for the full decision table.
20
+ */
21
+ export type ExecutionReason = "complete" | "truncated" | "stream_incomplete" | "schema_invalid" | "malformed" | "resource_limit" | "provider_error" | "content_filtered" | "sdk_execution_observed" | "unknown";
22
+ /**
23
+ * Why a decision came out the way it did - observability, not a second
24
+ * decision input. Every field here is read-only, derived state already held
25
+ * elsewhere (`ToolCallState`, the stream-level `DecisionContext`); nothing
26
+ * on this object ever feeds back into `decideExecution()`'s own logic, and
27
+ * changing what it reports can never change `action`/`executable`/`reason`.
28
+ *
29
+ * Deliberately excludes anything that would require new cross-layer
30
+ * plumbing to derive reliably (e.g. a received-chunk count - the parser
31
+ * only tracks cumulative bytes, not `push()` call counts, and adding that
32
+ * tracking purely to populate a metric here was judged not worth the
33
+ * coupling for this release).
34
+ */
35
+ export interface DecisionEvidence {
36
+ /** Which provider adapter produced this call (`ToolCallState.provider`). */
37
+ readonly provider: ProviderName;
38
+ /**
39
+ * The provider's own, pre-normalization finish/stop reason string, when
40
+ * the stream-ending event carried one (e.g. `"length"`, `"max_output_tokens"`,
41
+ * `"content_filter"`). `undefined` when the stream never reported one, or
42
+ * reported one without a `providerReason` (e.g. a default `finish()` call
43
+ * with no `meta`).
44
+ */
45
+ readonly providerReason?: string;
46
+ /** The normalized, library-level stream-end reason applied to this call. */
47
+ readonly streamEndReason: StreamEndReason;
48
+ /**
49
+ * Whether a real `provider_stream_end` reason was ever observed, as
50
+ * opposed to the neutral `"unknown"` default a gate reports before any
51
+ * stream-end signal has arrived at all. `true` here does NOT mean the
52
+ * reason was safe - a confirmed `"length"` still has `terminalConfirmed:
53
+ * true` - only that the stream's end state is genuinely known rather than
54
+ * merely unclassified or never observed.
55
+ */
56
+ readonly terminalConfirmed: boolean;
57
+ /**
58
+ * Whether the parser's root JSON container actually closed
59
+ * (`ToolCallState.parser.rootComplete`) - independent of whether that
60
+ * closure was genuine or reached via a safe-close repair, and independent
61
+ * of whether the stream-end reason makes it trustworthy. A syntactically
62
+ * complete value cut short by `length` has `structurallyComplete: true`
63
+ * and `parserExecutable: false` at the same time - that combination *is*
64
+ * the scenario this library exists to catch.
65
+ */
66
+ readonly structurallyComplete: boolean;
67
+ /** `ToolCallState.parser.executable`, verbatim - the parser's own fail-closed verdict. */
68
+ readonly parserExecutable: boolean;
69
+ /**
70
+ * `ToolCallState.schemaValid`, verbatim. `undefined` when no schema was
71
+ * registered for this tool, or the call never reached a structurally
72
+ * complete outcome.
73
+ */
74
+ readonly schemaValid?: boolean;
75
+ /** Total bytes received for this call's argument stream (`ToolCallState.parser.receivedBytes`). */
76
+ readonly receivedBytes: number;
77
+ }
78
+ interface ExecutionDecisionCommon {
79
+ /** The coordinator's internal call identifier (see `ToolCallState.internalId`). */
80
+ readonly internalId: string;
81
+ readonly toolCallId?: string;
82
+ readonly toolIndex?: number;
83
+ readonly name?: string;
84
+ /**
85
+ * Whatever was safely committed for this call, complete or not - present
86
+ * for both executable and non-executable decisions so a caller can see
87
+ * *what part* of a rejected/retried call was genuinely received (e.g. a
88
+ * `path` field that arrived before a `content` field got cut off).
89
+ * Never the source of truth for whether it's safe to act on - that's
90
+ * `action`/`executable`. Absent only when nothing was ever committed.
91
+ */
92
+ readonly stableValue?: JsonValue;
93
+ /** This call's own parser diagnostics, verbatim (`ToolCallState.parser.diagnostics`). */
94
+ readonly parserDiagnostics: readonly Diagnostic[];
95
+ /** Coordinator-level diagnostics attributable to this call, verbatim. */
96
+ readonly coordinatorDiagnostics: readonly CoordinatorDiagnostic[];
97
+ /**
98
+ * Why this decision came out the way it did. See `DecisionEvidence` -
99
+ * always present, purely observational, never a second source of truth
100
+ * for `action`/`executable`/`reason`.
101
+ */
102
+ readonly evidence: DecisionEvidence;
103
+ }
104
+ /**
105
+ * The one and only shape a decision can have when `action === "execute"`.
106
+ * `value` is a real, present `JsonValue` here - never `undefined`, never
107
+ * optional - because this is the single positive case: everything else in
108
+ * the gate exists to rule this out unless it's genuinely earned.
109
+ */
110
+ export interface ExecuteDecision extends ExecutionDecisionCommon {
111
+ readonly action: "execute";
112
+ readonly executable: true;
113
+ readonly reason: "complete";
114
+ readonly value: JsonValue;
115
+ /**
116
+ * Narrowed to required here (unlike the inherited `name?: string`):
117
+ * the coordinator only ever transitions a call to `status: "complete"`
118
+ * when `name` is defined (see `DefaultToolCallStreamCoordinator.finishCall`
119
+ * - a call with no name is forced to `"invalid"` instead), so every
120
+ * `ExecuteDecision` genuinely has one. Encoding that here means
121
+ * `tools[decision.name](decision.value)` type-checks directly after
122
+ * narrowing on `action === "execute"`, with no non-null assertion needed.
123
+ */
124
+ readonly name: string;
125
+ }
126
+ /**
127
+ * Every other outcome. `value` does not exist on this type at all (not
128
+ * `undefined` - absent) - TypeScript itself refuses code that reads a
129
+ * "final executable value" off a call the gate did not clear for execution.
130
+ */
131
+ export interface NonExecutableDecision extends ExecutionDecisionCommon {
132
+ readonly action: "retry" | "reject";
133
+ readonly executable: false;
134
+ readonly reason: Exclude<ExecutionReason, "complete">;
135
+ }
136
+ /**
137
+ * `ExecuteDecision | NonExecutableDecision` - a discriminated union on
138
+ * `action` (and redundantly on `executable`, for callers who prefer that
139
+ * check). Narrowing on either field gives you the right shape:
140
+ *
141
+ * ```ts
142
+ * if (decision.action === "execute") {
143
+ * await tools[decision.name](decision.value); // JsonValue, not JsonValue|undefined
144
+ * }
145
+ * ```
146
+ */
147
+ export type ExecutionDecision = ExecuteDecision | NonExecutableDecision;
148
+ export interface ToolCallExecutionGateFinalResult {
149
+ /** One decision per tool call the coordinator ever created. */
150
+ readonly decisions: readonly ExecutionDecision[];
151
+ /**
152
+ * The full, unfiltered coordinator diagnostics list (same as
153
+ * `coordinator.snapshot().diagnostics`) - includes diagnostics with no
154
+ * associated call, e.g. `E_COORDINATOR_LIMIT_CALLS` fires for a call that
155
+ * hit the concurrent-call limit before a `ToolCallState` could even be
156
+ * created for it, so it can never appear in `decisions`.
157
+ */
158
+ readonly diagnostics: readonly CoordinatorDiagnostic[];
159
+ }
160
+ /**
161
+ * High-level fail-closed execution decision layer built on top of
162
+ * `ToolCallStreamCoordinator`. Answers one question per tool call: is it
163
+ * safe to execute right now? Callers never need to touch parser lexical
164
+ * state, coordinator event mechanics, or JSON Pointer paths - push provider
165
+ * events in, read `ExecutionDecision`s out.
166
+ */
167
+ export interface ToolCallExecutionGate {
168
+ push(event: NormalizedToolStreamEvent): CoordinatorPushResult;
169
+ /**
170
+ * In-flight view. Every decision here is `"retry"` or `"reject"` -
171
+ * `"execute"` is only ever returned once the stream has genuinely
172
+ * finished (see `finish()`), since schema validity and prefix-safety are
173
+ * both only meaningful once a call has settled.
174
+ */
175
+ snapshot(): readonly ExecutionDecision[];
176
+ /** Drains the underlying coordinator's raw event queue, for advanced/UI consumers. */
177
+ drainEvents(): readonly ToolCallCoordinatorEvent[];
178
+ finish(meta?: {
179
+ reason?: StreamEndReason;
180
+ providerReason?: string;
181
+ }): ToolCallExecutionGateFinalResult;
182
+ }
183
+ export {};
184
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/gate/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,wBAAwB,EACzB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,yBAAyB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAEtG;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,eAAe,GAAG,SAAS,GAAG,OAAO,GAAG,QAAQ,CAAC;AAE7D;;;GAGG;AACH,MAAM,MAAM,eAAe,GACvB,UAAU,GACV,WAAW,GACX,mBAAmB,GACnB,gBAAgB,GAChB,WAAW,GACX,gBAAgB,GAChB,gBAAgB,GAChB,kBAAkB,GAClB,wBAAwB,GACxB,SAAS,CAAC;AAEd;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAEhC;;;;;;OAMG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAEjC,4EAA4E;IAC5E,QA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ACpE,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,CAAC;IACpC,QAAQ,CAAC,UAAU,EAAE,KAAK,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,eAAe,EAAE,UAAU,CAAC,CAAC;CACvD;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAAG,eAAe,GAAG,qBAAqB,CAAC;AAExE,MAAM,WAAW,gCAAgC;IAC/C,+DAA+D;IAC/D,QAAQ,CAAC,SAAS,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAEjD;;;;;;OAMG;IACH,QAAQ,CAAC,WAAW,EAAE,SAAS,qBAAqB,EAAE,CAAC;CACxD;AAED;;;;;;GAMG;AACH,MAAM,WAAW,qBAAqB;IACpC,IAAI,CAAC,KAAK,EAAE,yBAAyB,GAAG,qBAAqB,CAAC;IAE9D;;;;;OAKG;IACH,QAAQ,IAAI,SAAS,iBAAiB,EAAE,CAAC;IAEzC,sFAAsF;IACtF,WAAW,IAAI,SAAS,wBAAwB,EAAE,CAAC;IAEnD,MAAM,CAAC,IAAI,CAAC,EAAE;QACZ,MAAM,CAAC,EAAE,eAAe,CAAC;QACzB,cAAc,CAAC,EAAE,MAAM,CAAC;KACzB,GAAG,gCAAgC,CAAC;CACtC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/gate/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Expectation states for object parsing.
3
+ */
4
+ export type ObjectExpectation = "first_key_or_end" | "key_after_comma" | "colon" | "value" | "comma_or_end";
5
+ /**
6
+ * Expectation states for array parsing.
7
+ */
8
+ export type ArrayExpectation = "first_value_or_end" | "value_after_comma" | "comma_or_end";
9
+ /**
10
+ * A frame on the grammar stack representing a JSON container.
11
+ */
12
+ export interface GrammarFrame {
13
+ /** The type of container. */
14
+ containerType: "object" | "array";
15
+ /**
16
+ * The JSON Pointer path up to this container.
17
+ * Backed by a lazily-computed, memoized getter (see attachLazyPath) —
18
+ * reads exactly like a plain string field everywhere else in the codebase.
19
+ */
20
+ path: string;
21
+ /** Current expectation for object parsing. */
22
+ objectExpectation?: ObjectExpectation;
23
+ /** Current key being processed. */
24
+ currentKey?: string;
25
+ /** Set of keys already seen (for duplicate detection). */
26
+ seenKeys?: Set<string>;
27
+ /** Current expectation for array parsing. */
28
+ arrayExpectation?: ArrayExpectation;
29
+ /** Index of the next element. */
30
+ nextArrayIndex: number;
31
+ /** Byte offset where this container started. */
32
+ byteStart: number;
33
+ /**
34
+ * @internal Lazy-path bookkeeping. Do not read directly — use `.path`.
35
+ * A frame's own path never changes after creation (only descendants'
36
+ * currentKey/nextArrayIndex mutate), so it's safe to resolve on demand.
37
+ */
38
+ _parent?: GrammarFrame | null;
39
+ /** @internal The key/index linking `_parent` to this frame, captured at creation time. */
40
+ _segment?: string | number | null;
41
+ /** @internal Memoized resolved path, set the first time `.path` is read. */
42
+ _cachedPath?: string;
43
+ }
44
+ /**
45
+ * Create a new object frame.
46
+ * `parent` is the frame this one is nested inside (or null at the root);
47
+ * `segment` is the key/index leading from parent to this frame (or null at
48
+ * the root) — the same value `GrammarStack.currentValuePath()` would have
49
+ * used, captured eagerly since it reflects the parent's mutable state at
50
+ * this exact moment. Only the (expensive, O(depth)) string flattening is
51
+ * deferred.
52
+ */
53
+ export declare function createObjectFrame(parent: GrammarFrame | null, segment: string | number | null, byteStart: number): GrammarFrame;
54
+ /**
55
+ * Create a new array frame. See createObjectFrame for `parent`/`segment`.
56
+ */
57
+ export declare function createArrayFrame(parent: GrammarFrame | null, segment: string | number | null, byteStart: number): GrammarFrame;
58
+ //# sourceMappingURL=frame.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame.d.ts","sourceRoot":"","sources":["../../src/grammar/frame.ts"],"names":[],"mappings":"AAMA;;GAEG;AACH,MAAM,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ar stack frame — tracks state of a JSON container
3
+ // ---------------------------------------------------------------------------
4
+ import { appendPointer } from "./pointer.js";
5
+ /**
6
+ * Resolve (and memoize) a frame's full JSON Pointer path.
7
+ *
8
+ * Iterative, not recursive: walks up `_parent` references collecting frames
9
+ * until it finds one whose path is already cached (or the root), then walks
10
+ * back down building and caching each frame's path exactly once. This keeps
11
+ * per-frame cost amortized O(1) regardless of nesting depth, and avoids
12
+ * both the call-stack growth a recursive walk would have and the O(depth)
13
+ * eager string concatenation this replaces (which made opening N nested
14
+ * containers cost O(N^2) total, regardless of whether any value inside them
15
+ * was ever committed).
16
+ */
17
+ function resolveFramePath(frame) {
18
+ if (frame._cachedPath !== undefined)
19
+ return frame._cachedPath;
20
+ const chain = [];
21
+ let cur = frame;
22
+ while (cur !== null && cur._cachedPath === undefined) {
23
+ chain.push(cur);
24
+ cur = cur._parent === undefined ? null : cur._parent;
25
+ }
26
+ let basePath = cur !== null ? cur._cachedPath : "";
27
+ // chain[0] is always `frame` itself (pushed in the first loop iteration),
28
+ // and this loop runs in reverse, so the last iteration (i === 0) sets
29
+ // basePath to frame's own resolved path — returning it directly avoids
30
+ // re-reading frame._cachedPath, which TS can't prove was set here since
31
+ // the mutation happens through the aliased `f` reference.
32
+ for (let i = chain.length - 1; i >= 0; i--) {
33
+ const f = chain[i];
34
+ const seg = f._segment;
35
+ basePath =
36
+ seg === null || seg === undefined ? basePath : appendPointer(basePath, seg);
37
+ f._cachedPath = basePath;
38
+ }
39
+ return basePath;
40
+ }
41
+ function attachLazyPath(frame, parent, segment) {
42
+ frame._parent = parent;
43
+ frame._segment = segment;
44
+ Object.defineProperty(frame, "path", {
45
+ enumerable: true,
46
+ configurable: true,
47
+ get() {
48
+ return resolveFramePath(frame);
49
+ },
50
+ });
51
+ }
52
+ /**
53
+ * Create a new object frame.
54
+ * `parent` is the frame this one is nested inside (or null at the root);
55
+ * `segment` is the key/index leading from parent to this frame (or null at
56
+ * the root) — the same value `GrammarStack.currentValuePath()` would have
57
+ * used, captured eagerly since it reflects the parent's mutable state at
58
+ * this exact moment. Only the (expensive, O(depth)) string flattening is
59
+ * deferred.
60
+ */
61
+ export function createObjectFrame(parent, segment, byteStart) {
62
+ const frame = {
63
+ containerType: "object",
64
+ path: "",
65
+ objectExpectation: "first_key_or_end",
66
+ seenKeys: new Set(),
67
+ nextArrayIndex: 0,
68
+ byteStart,
69
+ };
70
+ attachLazyPath(frame, parent, segment);
71
+ return frame;
72
+ }
73
+ /**
74
+ * Create a new array frame. See createObjectFrame for `parent`/`segment`.
75
+ */
76
+ export function createArrayFrame(parent, segment, byteStart) {
77
+ const frame = {
78
+ containerType: "array",
79
+ path: "",
80
+ arrayExpectation: "first_value_or_end",
81
+ nextArrayIndex: 0,
82
+ byteStart,
83
+ };
84
+ attachLazyPath(frame, parent, segment);
85
+ return frame;
86
+ }
87
+ //# sourceMappingURL=frame.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame.js","sourceRoot":"","sources":["../../src/grammar/frame.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,yDAAyD;AACzD,8EAA8E;AAE9E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAkE7C;;;;;;;;;;;GAWG;AACH,SAAS,gBAAgB,CAAC,KAAmB;IAC3C,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,WAAW,CAAC;IAE9D,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,IAAI,GAAG,GAAwB,KAAK,CAAC;IACrC,OAAO,GAAG,KAAK,IAAI,IAAI,GAAG,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;QACrD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChB,GAAG,GAAG,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC;IACvD,CAAC;IAED,IAAI,QAAQ,GAAG,GAAG,KAA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ACF,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAC9B,MAA2B,EAC3B,OAA+B,EAC/B,SAAiB;IAEjB,MAAM,KAAK,GAAiB;QAC1B,aAAa,EAAE,OAAO;QACtB,IAAI,EAAE,EAAE;QACR,gBAAgB,EAAE,oBAAoB;QACtC,cAAc,EAAE,CAAC;QACjB,SAAS;KACV,CAAC;IACF,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Escape a JSON Pointer reference token per RFC 6901.
3
+ * ~ → ~0, / → ~1
4
+ */
5
+ export declare function escapePointerToken(token: string): string;
6
+ /**
7
+ * Build a JSON Pointer path from parent path and a key or index.
8
+ */
9
+ export declare function appendPointer(parent: string, token: string | number): string;
10
+ //# sourceMappingURL=pointer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pointer.d.ts","sourceRoot":"","sources":["../../src/grammar/pointer.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAExD;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAK5E"}
@@ -0,0 +1,20 @@
1
+ // ---------------------------------------------------------------------------
2
+ // JSON Pointer utilities (RFC 6901)
3
+ // ---------------------------------------------------------------------------
4
+ /**
5
+ * Escape a JSON Pointer reference token per RFC 6901.
6
+ * ~ → ~0, / → ~1
7
+ */
8
+ export function escapePointerToken(token) {
9
+ return token.replace(/~/g, "~0").replace(/\//g, "~1");
10
+ }
11
+ /**
12
+ * Build a JSON Pointer path from parent path and a key or index.
13
+ */
14
+ export function appendPointer(parent, token) {
15
+ if (typeof token === "number") {
16
+ return `${parent}/${token}`;
17
+ }
18
+ return `${parent}/${escapePointerToken(token)}`;
19
+ }
20
+ //# sourceMappingURL=pointer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pointer.js","sourceRoot":"","sources":["../../src/grammar/pointer.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,oCAAoC;AACpC,8EAA8E;AAE9E;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC9C,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACxD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc,EAAE,KAAsB;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC;IAC9B,CAAC;IACD,OAAO,GAAG,MAAM,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;AAClD,CAAC"}
@@ -0,0 +1,73 @@
1
+ import type { GrammarFrame } from "./frame.js";
2
+ import type { Diagnostic } from "../types.js";
3
+ /**
4
+ * Manages the stack of open JSON containers.
5
+ * Handles object/array nesting, expectations, and duplicate key detection.
6
+ */
7
+ export declare class GrammarStack {
8
+ private stack;
9
+ private diagnostics;
10
+ private hasDuplicateKey;
11
+ private maxDepth;
12
+ constructor(maxDepth: number);
13
+ /** Current depth (number of open containers). */
14
+ get depth(): number;
15
+ /** Whether any duplicate key has been seen. */
16
+ get hasDuplicate(): boolean;
17
+ /** Get the current (top) frame, or undefined if empty. */
18
+ get current(): GrammarFrame | undefined;
19
+ /**
20
+ * Push a new object container.
21
+ * Returns the frame, or null if depth limit exceeded.
22
+ */
23
+ pushObject(byteStart: number): GrammarFrame | null;
24
+ /**
25
+ * Push a new array container.
26
+ * Returns the frame, or null if depth limit exceeded.
27
+ */
28
+ pushArray(byteStart: number): GrammarFrame | null;
29
+ /**
30
+ * Pop the current container.
31
+ * Returns the popped frame.
32
+ */
33
+ pop(): GrammarFrame | undefined;
34
+ /**
35
+ * Register an object key. Returns true if the key is new.
36
+ * If duplicate, emits diagnostic and returns false.
37
+ */
38
+ registerObjectKey(key: string, byteOffset: number): boolean;
39
+ /**
40
+ * Get the JSON Pointer path for where the next value will go.
41
+ */
42
+ currentValuePath(): string;
43
+ /**
44
+ * The key/index that would lead from the current frame to its next child,
45
+ * without flattening it into a full path string. Same underlying value
46
+ * currentValuePath() uses; kept as a raw segment so a newly-pushed child
47
+ * frame can capture it in O(1) and defer the expensive path-string join
48
+ * (see grammar/frame.ts) until something actually reads `.path`.
49
+ */
50
+ private currentSegment;
51
+ /**
52
+ * Advance the array index after an element value is committed.
53
+ */
54
+ advanceArrayIndex(): void;
55
+ /**
56
+ * Take accumulated diagnostics and clear.
57
+ */
58
+ takeDiagnostics(): Diagnostic[];
59
+ /**
60
+ * Check if the stack is empty (no open containers).
61
+ */
62
+ isEmpty(): boolean;
63
+ /**
64
+ * Get all frames (for snapshot/pending info).
65
+ */
66
+ getFrames(): readonly GrammarFrame[];
67
+ /**
68
+ * Determine if all open containers can be safely closed by just appending '}' or ']'.
69
+ * This is true if no container is waiting for a colon or a value.
70
+ */
71
+ canSafelyCloseAll(): boolean;
72
+ }
73
+ //# sourceMappingURL=stack.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stack.d.ts","sourceRoot":"","sources":["../../src/grammar/stack.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAI9C;;;GAGG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,KAAK,CAAsB;IACnC,OAAO,CAAC,WAAW,CAAoB;IACvC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAS;gBAEb,QAAQ,EAAE,MAAM;IAI5B,iDAAiD;IACjD,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,+CAA+C;IAC/C,IAAI,YAAY,IAAI,OAAO,CAE1B;IAED,0DAA0D;IAC1D,IAAI,OAAO,IAAI,YAAY,GAAG,SAAS,CAEtC;IAED;;;OAGG;IACH,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI;IAmBlD;;;OAGG;IACH,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI;IAmBjD;;;OAGG;IACH,GAAG,IAAI,YAAY,GAAG,SAAS;IAI/B;;;OAGG;IACH,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IA0B3D;;OAEG;IACH,gBAAgB,IAAI,MAAM;IAc1B;;;;;;OAMG;IACH,OAAO,CAAC,cAAc;IAUtB;;OAEG;IACH,iBAAiB,IAAI,IAAI;IAOzB;;OAEG;IACH,eAAe,IAAI,UAAU,EAAE;IAM/B;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,SAAS,IAAI,SAAS,YAAY,EAAE;IAIpC;;;OAGG;IACH,iBAAiB,IAAI,OAAO;CAkB7B"}