autotel-genai 0.3.4 → 0.3.6
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.
- package/LICENSE +191 -21
- package/README.md +1 -1
- package/dist/guard.cjs.map +1 -1
- package/dist/guard.js.map +1 -1
- package/dist/observer-BoQNdbkg.cjs.map +1 -1
- package/dist/observer-Ckha9xGv.js.map +1 -1
- package/package.json +10 -10
package/LICENSE
CHANGED
|
@@ -1,21 +1,191 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
10
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the
|
|
13
|
+
copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other
|
|
16
|
+
entities that control, are controlled by, or are under common control with
|
|
17
|
+
that entity. For the purposes of this definition, "control" means (i) the
|
|
18
|
+
power, direct or indirect, to cause the direction or management of such
|
|
19
|
+
entity, whether by contract or otherwise, or (ii) ownership of fifty
|
|
20
|
+
percent (50%) or more of the outstanding shares, or (iii) beneficial
|
|
21
|
+
ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
24
|
+
permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation source,
|
|
28
|
+
and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical transformation
|
|
31
|
+
or translation of a Source form, including but not limited to compiled
|
|
32
|
+
object code, generated documentation, and conversions to other media types.
|
|
33
|
+
|
|
34
|
+
"Work" shall mean the work of authorship, whether in Source or Object form,
|
|
35
|
+
made available under the License, as indicated by a copyright notice that
|
|
36
|
+
is included in or attached to the work (an example is provided in the
|
|
37
|
+
Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object form,
|
|
40
|
+
that is based on (or derived from) the Work and for which the editorial
|
|
41
|
+
revisions, annotations, elaborations, or other modifications represent, as
|
|
42
|
+
a whole, an original work of authorship. For the purposes of this License,
|
|
43
|
+
Derivative Works shall not include works that remain separable from, or
|
|
44
|
+
merely link (or bind by name) to the interfaces of, the Work and Derivative
|
|
45
|
+
Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean any work of authorship, including the original
|
|
48
|
+
version of the Work and any modifications or additions to that Work or
|
|
49
|
+
Derivative Works thereof, that is intentionally submitted to Licensor for
|
|
50
|
+
inclusion in the Work by the copyright owner or by an individual or Legal
|
|
51
|
+
Entity authorized to submit on behalf of the copyright owner. For the
|
|
52
|
+
purposes of this definition, "submitted" means any form of electronic,
|
|
53
|
+
verbal, or written communication sent to the Licensor or its
|
|
54
|
+
representatives, including but not limited to communication on electronic
|
|
55
|
+
mailing lists, source code control systems, and issue tracking systems that
|
|
56
|
+
are managed by, or on behalf of, the Licensor for the purpose of discussing
|
|
57
|
+
and improving the Work, but excluding communication that is conspicuously
|
|
58
|
+
marked or otherwise designated in writing by the copyright owner as "Not a
|
|
59
|
+
Contribution."
|
|
60
|
+
|
|
61
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on
|
|
62
|
+
behalf of whom a Contribution has been received by Licensor and
|
|
63
|
+
subsequently incorporated within the Work.
|
|
64
|
+
|
|
65
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this
|
|
66
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
67
|
+
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
|
68
|
+
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
|
69
|
+
sublicense, and distribute the Work and such Derivative Works in Source or
|
|
70
|
+
Object form.
|
|
71
|
+
|
|
72
|
+
3. Grant of Patent License. Subject to the terms and conditions of this
|
|
73
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
74
|
+
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
|
|
75
|
+
this section) patent license to make, have made, use, offer to sell, sell,
|
|
76
|
+
import, and otherwise transfer the Work, where such license applies only to
|
|
77
|
+
those patent claims licensable by such Contributor that are necessarily
|
|
78
|
+
infringed by their Contribution(s) alone or by combination of their
|
|
79
|
+
Contribution(s) with the Work to which such Contribution(s) was submitted.
|
|
80
|
+
If You institute patent litigation against any entity (including a
|
|
81
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
82
|
+
Contribution incorporated within the Work constitutes direct or
|
|
83
|
+
contributory patent infringement, then any patent licenses granted to You
|
|
84
|
+
under this License for that Work shall terminate as of the date such
|
|
85
|
+
litigation is filed.
|
|
86
|
+
|
|
87
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or
|
|
88
|
+
Derivative Works thereof in any medium, with or without modifications, and
|
|
89
|
+
in Source or Object form, provided that You meet the following conditions:
|
|
90
|
+
|
|
91
|
+
(a) You must give any other recipients of the Work or Derivative Works
|
|
92
|
+
a copy of this License; and
|
|
93
|
+
|
|
94
|
+
(b) You must cause any modified files to carry prominent notices
|
|
95
|
+
stating that You changed the files; and
|
|
96
|
+
|
|
97
|
+
(c) You must retain, in the Source form of any Derivative Works that
|
|
98
|
+
You distribute, all copyright, patent, trademark, and attribution notices
|
|
99
|
+
from the Source form of the Work, excluding those notices that do not
|
|
100
|
+
pertain to any part of the Derivative Works; and
|
|
101
|
+
|
|
102
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
+
distribution, then any Derivative Works that You distribute must include a
|
|
104
|
+
readable copy of the attribution notices contained within such NOTICE file,
|
|
105
|
+
excluding those notices that do not pertain to any part of the Derivative
|
|
106
|
+
Works, in at least one of the following places: within a NOTICE text file
|
|
107
|
+
distributed as part of the Derivative Works; within the Source form or
|
|
108
|
+
documentation, if provided along with the Derivative Works; or, within a
|
|
109
|
+
display generated by the Derivative Works, if and wherever such third-party
|
|
110
|
+
notices normally appear. The contents of the NOTICE file are for
|
|
111
|
+
informational purposes only and do not modify the License. You may add Your
|
|
112
|
+
own attribution notices within Derivative Works that You distribute,
|
|
113
|
+
alongside or as an addendum to the NOTICE text from the Work, provided that
|
|
114
|
+
such additional attribution notices cannot be construed as modifying the
|
|
115
|
+
License.
|
|
116
|
+
|
|
117
|
+
You may add Your own copyright statement to Your modifications and may
|
|
118
|
+
provide additional or different license terms and conditions for use,
|
|
119
|
+
reproduction, or distribution of Your modifications, or for any such
|
|
120
|
+
Derivative Works as a whole, provided Your use, reproduction, and
|
|
121
|
+
distribution of the Work otherwise complies with the conditions stated in
|
|
122
|
+
this License.
|
|
123
|
+
|
|
124
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
|
125
|
+
Contribution intentionally submitted for inclusion in the Work by You to
|
|
126
|
+
the Licensor shall be under the terms and conditions of this License,
|
|
127
|
+
without any additional terms or conditions. Notwithstanding the above,
|
|
128
|
+
nothing herein shall supersede or modify the terms of any separate license
|
|
129
|
+
agreement you may have executed with Licensor regarding such Contributions.
|
|
130
|
+
|
|
131
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
132
|
+
names, trademarks, service marks, or product names of the Licensor, except
|
|
133
|
+
as required for reasonable and customary use in describing the origin of
|
|
134
|
+
the Work and reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
|
|
137
|
+
in writing, Licensor provides the Work (and each Contributor provides its
|
|
138
|
+
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
139
|
+
KIND, either express or implied, including, without limitation, any
|
|
140
|
+
warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
|
|
141
|
+
FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for
|
|
142
|
+
determining the appropriateness of using or redistributing the Work and
|
|
143
|
+
assume any risks associated with Your exercise of permissions under this
|
|
144
|
+
License.
|
|
145
|
+
|
|
146
|
+
8. Limitation of Liability. In no event and under no legal theory, whether
|
|
147
|
+
in tort (including negligence), contract, or otherwise, unless required by
|
|
148
|
+
applicable law (such as deliberate and grossly negligent acts) or agreed to
|
|
149
|
+
in writing, shall any Contributor be liable to You for damages, including
|
|
150
|
+
any direct, indirect, special, incidental, or consequential damages of any
|
|
151
|
+
character arising as a result of this License or out of the use or
|
|
152
|
+
inability to use the Work (including but not limited to damages for loss of
|
|
153
|
+
goodwill, work stoppage, computer failure or malfunction, or any and all
|
|
154
|
+
other commercial damages or losses), even if such Contributor has been
|
|
155
|
+
advised of the possibility of such damages.
|
|
156
|
+
|
|
157
|
+
9. Accepting Warranty or Additional Liability. While redistributing the
|
|
158
|
+
Work or Derivative Works thereof, You may choose to offer, and charge a fee
|
|
159
|
+
for, acceptance of support, warranty, indemnity, or other liability
|
|
160
|
+
obligations and/or rights consistent with this License. However, in
|
|
161
|
+
accepting such obligations, You may act only on Your own behalf and on Your
|
|
162
|
+
sole responsibility, not on behalf of any other Contributor, and only if
|
|
163
|
+
You agree to indemnify, defend, and hold each Contributor harmless for any
|
|
164
|
+
liability incurred by, or claims asserted against, such Contributor by
|
|
165
|
+
reason of your accepting any such warranty or additional liability.
|
|
166
|
+
|
|
167
|
+
END OF TERMS AND CONDITIONS
|
|
168
|
+
|
|
169
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
170
|
+
|
|
171
|
+
To apply the Apache License to your work, attach the following boilerplate
|
|
172
|
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
|
173
|
+
identifying information. (Don't include the brackets!) The text should be
|
|
174
|
+
enclosed in the appropriate comment syntax for the file format. We also
|
|
175
|
+
recommend that a file or class name and description of purpose be included
|
|
176
|
+
on the same "printed page" as the copyright notice for easier
|
|
177
|
+
identification within third-party archives.
|
|
178
|
+
|
|
179
|
+
Copyright [yyyy] [name of copyright owner]
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
package/README.md
CHANGED
package/dist/guard.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guard.cjs","names":["GEN_AI","GEN_AI_GUARD_EVENT"],"sources":["../src/guard.ts"],"sourcesContent":["/**\n * GenAI guard / budget runtime — an in-process kill-switch for agent runs.\n *\n * Most tracing tells you what an agent _did_, after the fact. A guard runs\n * _during_ the run: you feed it each step (an LLM call, a tool call, a\n * delegation), it accumulates cost / tokens / loop state, and evaluates a set\n * of rules. When a rule crosses its threshold the guard either records a\n * warning and lets the run continue, or stops the run — aborting an\n * {@link AbortSignal} and (by default) throwing a structured error so the agent\n * loop unwinds. No prompt, no retry, no runaway bill.\n *\n * This is the inline, OpenTelemetry-native analogue of a `watch` kill-switch:\n * cost ceilings, token ceilings, max tool calls, wall-clock timeouts, and\n * spin-loop / error-loop detection — all pure, deterministic logic with no LLM\n * in the loop.\n *\n * @example Budget ceiling that halts a runaway agent\n * ```typescript\n * import { createGenAiBudget } from 'autotel-genai/guard';\n * import { estimateLLMCost } from 'autotel-genai/cost';\n *\n * const budget = createGenAiBudget({ maxCostUsd: 5, warnAtUsd: 4 });\n *\n * for (const task of tasks) {\n * if (budget.stopped) break;\n * const res = await model.chat(task);\n * budget.record(\n * {\n * kind: 'llm',\n * usage: {\n * costUsd: estimateLLMCost('gpt-4o', {\n * inputTokens: res.usage.input,\n * outputTokens: res.usage.output,\n * }),\n * },\n * },\n * ctx, // optional TraceContext — records gen_ai.guard.* telemetry\n * ); // throws GEN_AI_GUARD_STOP once total cost > $5\n * }\n * ```\n *\n * @example Loop detection from a shorthand rule string\n * ```typescript\n * import { createGenAiGuard, parseGuardRules } from 'autotel-genai/guard';\n *\n * const guard = createGenAiGuard({\n * rules: parseGuardRules('budget:$2,loop:3/10,max-tools:50,timeout:5m'),\n * });\n *\n * guard.record({ kind: 'tool', name: 'search', signature: JSON.stringify(args) });\n * ```\n */\n\nimport { createStructuredError, type TraceContext } from 'autotel';\nimport { securityEvent } from 'autotel-audit';\nimport { GEN_AI, GEN_AI_GUARD_EVENT } from './semconv.js';\n\n/** What a rule does when it crosses its threshold. */\nexport type GuardAction = 'warn' | 'stop';\n\n/** Usage contribution for a single step. */\nexport interface GuardUsage {\n /**\n * Estimated USD cost for this step. Pair with\n * {@link import('./cost.js').estimateLLMCost} to compute it from token usage.\n */\n costUsd?: number;\n /** Input (prompt) tokens for this step. */\n inputTokens?: number;\n /** Output (completion) tokens for this step. */\n outputTokens?: number;\n}\n\n/** A single supervised step: an LLM call, a tool call, a delegation, … */\nexport interface GenAiGuardStep {\n /**\n * Step kind. `tool` increments the tool-call counter; any value is allowed.\n */\n kind?: 'llm' | 'tool' | 'agent' | 'workflow' | (string & {});\n /** Operation or tool name — used together with {@link signature} for loops. */\n name?: string;\n /**\n * Stable signature of the call inputs (e.g. `JSON.stringify(args)`). Two\n * steps with the same `name` + `signature` count as identical for spin-loop\n * detection. Hash or truncate it yourself if the raw args are large.\n */\n signature?: string;\n /** Whether this step failed. Drives error-loop detection. */\n error?: boolean;\n /** Cost / token contribution to the running totals. */\n usage?: GuardUsage;\n}\n\n/** Read-only snapshot of the accumulated session state. */\nexport interface GuardState {\n /** Epoch ms when the guard was created. */\n readonly startedAt: number;\n /** Epoch ms at evaluation time. */\n readonly now: number;\n /** Wall-clock ms since {@link startedAt}. */\n readonly elapsedMs: number;\n /** Accumulated estimated cost in USD. */\n readonly costUsd: number;\n /** Accumulated input tokens. */\n readonly inputTokens: number;\n /** Accumulated output tokens. */\n readonly outputTokens: number;\n /** Total steps recorded. */\n readonly stepCount: number;\n /** Steps with `kind === 'tool'`. */\n readonly toolCallCount: number;\n /** Steps with `error === true`. */\n readonly errorCount: number;\n /** Bounded recent history (newest last) for loop detection. */\n readonly history: ReadonlyArray<{ key: string | undefined; error: boolean }>;\n}\n\n/** A fired rule. */\nexport interface GuardViolation {\n /** Rule name, e.g. `cost-ceiling:$5`. */\n rule: string;\n /** Whether the run continued (`warn`) or was halted (`stop`). */\n action: GuardAction;\n /** Human-readable explanation. */\n message: string;\n /** The observed value that crossed the threshold. */\n observed: number;\n /** The configured threshold. */\n limit: number;\n}\n\n/** A guard rule: inspect the state after a step and optionally fire. */\nexport interface GenAiGuardRule {\n /** Stable identifier, surfaced on {@link GuardViolation.rule}. */\n name: string;\n /** Default {@link GuardAction} when the rule fires. Defaults to `stop`. */\n action?: GuardAction;\n /**\n * Evaluate against the post-step state and the step just recorded (absent on\n * a bare {@link GenAiGuard.check}). Return a partial violation to fire, or\n * `undefined` to pass.\n */\n evaluate: (\n state: GuardState,\n step: GenAiGuardStep | undefined,\n ) => { message: string; observed: number; limit: number } | undefined;\n}\n\n/** Minimal telemetry sink — the subset of {@link TraceContext} the guard uses. */\nexport type GuardSink = Pick<TraceContext, 'setAttributes' | 'track'>;\n\n/** What happens when a `stop` rule fires. */\nexport type GuardStopBehavior =\n /** Abort the signal and throw a structured error (default). */\n | 'throw'\n /** Abort the signal but do not throw — inspect `guard.stopped` yourself. */\n | 'abort'\n /** Record the violation only; neither abort nor throw. */\n | 'silent';\n\nexport interface GenAiGuardOptions {\n /** Rules to evaluate after each step. */\n rules: GenAiGuardRule[];\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /**\n * Max recent steps retained for loop detection. Defaults to 256; raise it if\n * a spin-loop rule uses a larger window.\n */\n historyLimit?: number;\n /** Clock injection point, for tests. Defaults to {@link Date.now}. */\n now?: () => number;\n}\n\n/** A live guard supervising an agent run. */\nexport interface GenAiGuard {\n /**\n * Record a step, accumulate its usage, and evaluate every rule. Returns the\n * violations that fired _this call_ (each rule fires at most once). When a\n * `stop` rule fires, aborts {@link signal} and — unless `onStop` is `abort` /\n * `silent` — throws a structured `GEN_AI_GUARD_STOP` error.\n */\n record(step: GenAiGuardStep, ctx?: GuardSink): GuardViolation[];\n /**\n * Re-evaluate the rules without recording a step. Useful for time-based\n * rules (e.g. a timeout) between LLM calls.\n */\n check(ctx?: GuardSink): GuardViolation[];\n /** Current accumulated state. */\n readonly state: GuardState;\n /** Fires once a `stop` rule has crossed its threshold. */\n readonly signal: AbortSignal;\n /** `true` after a `stop` rule has fired. */\n readonly stopped: boolean;\n /** Every violation fired so far, in order. */\n readonly violations: ReadonlyArray<GuardViolation>;\n}\n\n// --- Rule factories --------------------------------------------------------\n\nfunction round(n: number): number {\n return Math.round(n * 1e6) / 1e6;\n}\n\n/** Stop / warn when accumulated cost exceeds `limitUsd`. */\nexport function costCeiling(\n limitUsd: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `cost-ceiling:$${limitUsd}`,\n action,\n evaluate: (s) =>\n s.costUsd > limitUsd\n ? {\n message: `session cost $${round(s.costUsd)} exceeds $${limitUsd}`,\n observed: round(s.costUsd),\n limit: limitUsd,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when accumulated input + output tokens exceed `limit`. */\nexport function tokenCeiling(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `token-ceiling:${limit}`,\n action,\n evaluate: (s) => {\n const total = s.inputTokens + s.outputTokens;\n return total > limit\n ? {\n message: `session tokens ${total} exceed ${limit}`,\n observed: total,\n limit,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn when the number of tool calls exceeds `limit`. */\nexport function maxToolCalls(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-tool-calls:${limit}`,\n action,\n evaluate: (s) =>\n s.toolCallCount > limit\n ? {\n message: `tool calls ${s.toolCallCount} exceed ${limit}`,\n observed: s.toolCallCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when the total number of steps exceeds `limit`. */\nexport function maxSteps(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-steps:${limit}`,\n action,\n evaluate: (s) =>\n s.stepCount > limit\n ? {\n message: `steps ${s.stepCount} exceed ${limit}`,\n observed: s.stepCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when wall-clock time since start exceeds `limitMs`. */\nexport function maxDuration(\n limitMs: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-duration:${limitMs}ms`,\n action,\n evaluate: (s) =>\n s.elapsedMs > limitMs\n ? {\n message: `elapsed ${s.elapsedMs}ms exceeds ${limitMs}ms`,\n observed: s.elapsedMs,\n limit: limitMs,\n }\n : undefined,\n };\n}\n\n/**\n * Stop / warn on a spin loop: the same step (`name` + `signature`) repeated\n * `count` or more times within the last `window` steps. Steps without a `name`\n * are ignored (no identity to compare).\n */\nexport function spinLoop(\n options: { count: number; window: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count, window } = options;\n return {\n name: `spin-loop:${count}/${window}`,\n action,\n evaluate: (s, step) => {\n const key = stepKey(step);\n if (key === undefined) return undefined;\n const recent = s.history.slice(-window);\n let occurrences = 0;\n for (const h of recent) if (h.key === key) occurrences++;\n return occurrences >= count\n ? {\n message: `step \"${step?.name}\" repeated ${occurrences}× in last ${window}`,\n observed: occurrences,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn on `count` or more consecutive failing steps. */\nexport function errorLoop(\n options: { count: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count } = options;\n return {\n name: `error-loop:${count}`,\n action,\n evaluate: (s) => {\n let streak = 0;\n for (let i = s.history.length - 1; i >= 0; i--) {\n if (s.history[i].error) streak++;\n else break;\n }\n return streak >= count\n ? {\n message: `${streak} consecutive errors`,\n observed: streak,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/**\n * Approximate context-window sizes (in input tokens) for common models.\n * Matched exactly first, then by longest key prefix. Override via the `limit`\n * option on {@link contextBudget}.\n */\nexport const CONTEXT_LIMITS: Record<string, number> = {\n 'gpt-4o': 128_000,\n 'gpt-4.1': 1_047_576,\n 'gpt-4': 8192,\n 'o3-mini': 200_000,\n 'claude-opus-4': 200_000,\n 'claude-sonnet-4': 200_000,\n 'claude-3-5-sonnet': 200_000,\n 'claude-3-5-haiku': 200_000,\n 'claude-3': 200_000,\n 'gemini-1.5-pro': 2_097_152,\n 'gemini-1.5-flash': 1_048_576,\n 'gemini-2.0-flash': 1_048_576,\n};\n\nfunction resolveContextLimit(model: string): number | undefined {\n const exact = CONTEXT_LIMITS[model];\n if (exact) return exact;\n let best: number | undefined;\n let bestLength = 0;\n for (const key of Object.keys(CONTEXT_LIMITS)) {\n if (model.startsWith(key) && key.length > bestLength) {\n best = CONTEXT_LIMITS[key];\n bestLength = key.length;\n }\n }\n return best;\n}\n\n/**\n * Stop / warn when cumulative input tokens reach `threshold` (default 0.9) of\n * the model's context window. Provide an explicit `limit`, or a `model` to look\n * one up from {@link CONTEXT_LIMITS}.\n */\nexport function contextBudget(\n options: { model?: string; limit?: number; threshold?: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const threshold = options.threshold ?? 0.9;\n const limit =\n options.limit ?? (options.model ? resolveContextLimit(options.model) : undefined);\n return {\n name: `context-budget:${Math.round(threshold * 100)}%`,\n action,\n evaluate: (s) => {\n if (!limit) return undefined;\n const ratio = s.inputTokens / limit;\n return ratio >= threshold\n ? {\n message: `context ${Math.round(ratio * 100)}% full (${s.inputTokens}/${limit})`,\n observed: round(ratio),\n limit: threshold,\n }\n : undefined;\n },\n };\n}\n\nfunction stepKey(step: GenAiGuardStep | undefined): string | undefined {\n if (!step || step.name === undefined) return undefined;\n return `${step.name}\u0000${step.signature ?? ''}`;\n}\n\n// --- Shorthand rule parser -------------------------------------------------\n\nfunction parseScaledNumber(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([kmb])?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid number: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const scale = { k: 1e3, m: 1e6, b: 1e9 }[m[2]?.toLowerCase() ?? ''] ?? 1;\n return value * scale;\n}\n\nfunction parseDurationMs(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid duration: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const unit = (m[2] ?? 's').toLowerCase();\n const scale = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[unit] ?? 1000;\n return value * scale;\n}\n\n/**\n * Parse a comma-separated shorthand rule string into {@link GenAiGuardRule}s.\n * All parsed rules default to the `stop` action — pass `defaultAction: 'warn'`\n * to warn instead, or build typed rules directly for per-rule actions.\n *\n * Supported tokens:\n * - `budget:$5` / `cost:$5` — {@link costCeiling}\n * - `tokens:100k` — {@link tokenCeiling} (`k`/`m`/`b` suffixes)\n * - `loop:3/10` — {@link spinLoop} (count / window)\n * - `errors:3` — {@link errorLoop}\n * - `max-tools:50` — {@link maxToolCalls}\n * - `max-steps:100` — {@link maxSteps}\n * - `timeout:30m` — {@link maxDuration} (`ms`/`s`/`m`/`h`, default seconds)\n * - `context:0.9` / `context:0.9@gpt-4o` — {@link contextBudget}\n */\nexport function parseGuardRules(\n shorthand: string,\n options?: { defaultAction?: GuardAction },\n): GenAiGuardRule[] {\n const action = options?.defaultAction ?? 'stop';\n const rules: GenAiGuardRule[] = [];\n for (const token of shorthand.split(',')) {\n const trimmed = token.trim();\n if (!trimmed) continue;\n const sep = trimmed.indexOf(':');\n if (sep === -1) throw new Error(`invalid guard rule: \"${trimmed}\"`);\n const key = trimmed.slice(0, sep).trim().toLowerCase();\n const value = trimmed.slice(sep + 1).trim();\n\n switch (key) {\n case 'budget':\n case 'cost': {\n rules.push(costCeiling(parseScaledNumber(value.replace(/^\\$/, '')), action));\n break;\n }\n case 'tokens': {\n rules.push(tokenCeiling(parseScaledNumber(value), action));\n break;\n }\n case 'loop': {\n const [count, window] = value.split('/');\n rules.push(\n spinLoop(\n { count: parseScaledNumber(count), window: parseScaledNumber(window) },\n action,\n ),\n );\n break;\n }\n case 'errors': {\n rules.push(errorLoop({ count: parseScaledNumber(value) }, action));\n break;\n }\n case 'max-tools': {\n rules.push(maxToolCalls(parseScaledNumber(value), action));\n break;\n }\n case 'max-steps': {\n rules.push(maxSteps(parseScaledNumber(value), action));\n break;\n }\n case 'timeout': {\n rules.push(maxDuration(parseDurationMs(value), action));\n break;\n }\n case 'context': {\n const [thr, model] = value.split('@');\n rules.push(\n contextBudget(\n { threshold: Number.parseFloat(thr), model: model?.trim() || undefined },\n action,\n ),\n );\n break;\n }\n default: {\n throw new Error(`unknown guard rule: \"${key}\"`);\n }\n }\n }\n return rules;\n}\n\n// --- Guard implementation --------------------------------------------------\n\nfunction recordTelemetry(\n ctx: GuardSink,\n state: GuardState,\n newViolations: GuardViolation[],\n stopped: boolean,\n): void {\n ctx.setAttributes({\n [GEN_AI.SESSION_COST_USD]: round(state.costUsd),\n [GEN_AI.SESSION_INPUT_TOKENS]: state.inputTokens,\n [GEN_AI.SESSION_OUTPUT_TOKENS]: state.outputTokens,\n [GEN_AI.SESSION_STEP_COUNT]: state.stepCount,\n [GEN_AI.SESSION_TOOL_CALL_COUNT]: state.toolCallCount,\n [GEN_AI.SESSION_ERROR_COUNT]: state.errorCount,\n });\n if (newViolations.length === 0) return;\n if (stopped) ctx.setAttributes({ [GEN_AI.GUARD_STOPPED]: true });\n for (const violation of newViolations) {\n ctx.track(\n violation.action === 'stop'\n ? GEN_AI_GUARD_EVENT.STOP\n : GEN_AI_GUARD_EVENT.WARNING,\n {\n [GEN_AI.GUARD_RULE]: violation.rule,\n [GEN_AI.GUARD_ACTION]: violation.action,\n [GEN_AI.GUARD_MESSAGE]: violation.message,\n [GEN_AI.GUARD_OBSERVED]: violation.observed,\n [GEN_AI.GUARD_LIMIT]: violation.limit,\n },\n );\n if (violation.action === 'stop') {\n securityEvent(\n {\n name: 'llm.guard.triggered',\n category: 'llm',\n outcome: 'blocked',\n severity: 'error',\n reason: violation.rule,\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n },\n { onMissingContext: 'warn' },\n );\n }\n }\n}\n\n/**\n * Create a guard that supervises an in-process agent run against `rules`.\n */\nexport function createGenAiGuard(options: GenAiGuardOptions): GenAiGuard {\n const { rules } = options;\n const onStop = options.onStop ?? 'throw';\n const historyLimit = options.historyLimit ?? 256;\n const now = options.now ?? Date.now;\n const startedAt = now();\n\n const controller = new AbortController();\n const history: { key: string | undefined; error: boolean }[] = [];\n const fired = new Set<string>();\n const violations: GuardViolation[] = [];\n\n let costUsd = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let stepCount = 0;\n let toolCallCount = 0;\n let errorCount = 0;\n let stopped = false;\n\n function snapshot(): GuardState {\n const at = now();\n return {\n startedAt,\n now: at,\n elapsedMs: at - startedAt,\n costUsd,\n inputTokens,\n outputTokens,\n stepCount,\n toolCallCount,\n errorCount,\n history,\n };\n }\n\n function evaluate(\n step: GenAiGuardStep | undefined,\n ctx: GuardSink | undefined,\n ): GuardViolation[] {\n const state = snapshot();\n const newViolations: GuardViolation[] = [];\n\n for (const rule of rules) {\n if (fired.has(rule.name)) continue;\n const hit = rule.evaluate(state, step);\n if (!hit) continue;\n fired.add(rule.name);\n const violation: GuardViolation = {\n rule: rule.name,\n action: rule.action ?? 'stop',\n message: hit.message,\n observed: hit.observed,\n limit: hit.limit,\n };\n violations.push(violation);\n newViolations.push(violation);\n }\n\n const stopViolation = newViolations.find((v) => v.action === 'stop');\n if (stopViolation && !stopped) {\n stopped = true;\n if (onStop !== 'silent') controller.abort(toStopError(stopViolation, state));\n }\n\n if (ctx) recordTelemetry(ctx, state, newViolations, stopped);\n\n if (stopViolation && onStop === 'throw') {\n throw toStopError(stopViolation, snapshot());\n }\n return newViolations;\n }\n\n return {\n record(step, ctx) {\n stepCount++;\n if (step.kind === 'tool') toolCallCount++;\n if (step.error) errorCount++;\n if (step.usage) {\n costUsd += step.usage.costUsd ?? 0;\n inputTokens += step.usage.inputTokens ?? 0;\n outputTokens += step.usage.outputTokens ?? 0;\n }\n history.push({ key: stepKey(step), error: step.error === true });\n if (history.length > historyLimit) history.shift();\n return evaluate(step, ctx);\n },\n check(ctx) {\n return evaluate(undefined, ctx);\n },\n get state() {\n return snapshot();\n },\n get signal() {\n return controller.signal;\n },\n get stopped() {\n return stopped;\n },\n get violations() {\n return violations;\n },\n };\n}\n\nfunction toStopError(violation: GuardViolation, state: GuardState): Error {\n return createStructuredError({\n name: 'GenAiGuardStop',\n code: 'GEN_AI_GUARD_STOP',\n status: 429,\n message: `Guard rule \"${violation.rule}\" halted the run: ${violation.message}`,\n why: 'A stop-action guard rule crossed its threshold during the agent run.',\n fix: 'Raise the limit, fix the loop, or handle GEN_AI_GUARD_STOP to wind the run down cleanly.',\n details: {\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n costUsd: round(state.costUsd),\n stepCount: state.stepCount,\n },\n });\n}\n\n// --- Budget preset ---------------------------------------------------------\n\nexport interface GenAiBudgetOptions {\n /** Hard cost ceiling in USD — a `stop` rule. */\n maxCostUsd?: number;\n /** Soft cost threshold in USD — a `warn` rule. */\n warnAtUsd?: number;\n /** Hard token ceiling (input + output) — a `stop` rule. */\n maxTokens?: number;\n /** Hard tool-call ceiling — a `stop` rule. */\n maxToolCalls?: number;\n /** Hard wall-clock ceiling in ms — a `stop` rule. */\n maxDurationMs?: number;\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /** Clock injection point, for tests. */\n now?: () => number;\n}\n\n/**\n * Convenience preset that wires the common cost / token / tool-call / duration\n * ceilings into a {@link createGenAiGuard}. Returns the same {@link GenAiGuard}.\n */\nexport function createGenAiBudget(options: GenAiBudgetOptions): GenAiGuard {\n const rules: GenAiGuardRule[] = [];\n if (options.warnAtUsd !== undefined) {\n rules.push(costCeiling(options.warnAtUsd, 'warn'));\n }\n if (options.maxCostUsd !== undefined) {\n rules.push(costCeiling(options.maxCostUsd, 'stop'));\n }\n if (options.maxTokens !== undefined) {\n rules.push(tokenCeiling(options.maxTokens, 'stop'));\n }\n if (options.maxToolCalls !== undefined) {\n rules.push(maxToolCalls(options.maxToolCalls, 'stop'));\n }\n if (options.maxDurationMs !== undefined) {\n rules.push(maxDuration(options.maxDurationMs, 'stop'));\n }\n return createGenAiGuard({\n rules,\n onStop: options.onStop,\n now: options.now,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwMA,SAAS,MAAM,GAAmB;CAChC,OAAO,KAAK,MAAM,IAAI,GAAG,IAAI;AAC/B;;AAGA,SAAgB,YACd,UACA,SAAsB,QACN;CAChB,OAAO;EACL,MAAM,iBAAiB;EACvB;EACA,WAAW,MACT,EAAE,UAAU,WACR;GACE,SAAS,iBAAiB,MAAM,EAAE,OAAO,EAAE,YAAY;GACvD,UAAU,MAAM,EAAE,OAAO;GACzB,OAAO;EACT,IACA;CACR;AACF;;AAGA,SAAgB,aACd,OACA,SAAsB,QACN;CAChB,OAAO;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AI,aAAa;GACf,OAAO;EACT;CACF;AACF;AAEA,SAAS,YAAY,WAA2B,OAA0B;CACxE,0CAA6B;EAC3B,MAAM;EACN,MAAM;EACN,QAAQ;EACR,SAAS,eAAe,UAAU,KAAK,oBAAoB,UAAU;EACrE,KAAK;EACL,KAAK;EACL,SAAS;GACP,MAAM,UAAU;GAChB,UAAU,UAAU;GACpB,OAAO,UAAU;GACjB,SAAS,MAAM,MAAM,OAAO;GAC5B,WAAW,MAAM;EACnB;CACF,CAAC;AACH;;;;;AAyBA,SAAgB,kBAAkB,SAAyC;CACzE,MAAM,QAA0B,CAAC;CACjC,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,YAAY,QAAQ,WAAW,MAAM,CAAC;CACnD;CACA,IAAI,QAAQ,eAAe,WAAW;EACpC,MAAM,KAAK,YAAY,QAAQ,YAAY,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,aAAa,QAAQ,WAAW,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,iBAAiB,WAAW;EACtC,MAAM,KAAK,aAAa,QAAQ,cAAc,MAAM,CAAC;CACvD;CACA,IAAI,QAAQ,kBAAkB,WAAW;EACvC,MAAM,KAAK,YAAY,QAAQ,eAAe,MAAM,CAAC;CACvD;CACA,OAAO,iBAAiB;EACtB;EACA,QAAQ,QAAQ;EAChB,KAAK,QAAQ;CACf,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"guard.cjs","names":["GEN_AI","GEN_AI_GUARD_EVENT"],"sources":["../src/guard.ts"],"sourcesContent":["/**\n * GenAI guard / budget runtime — an in-process kill-switch for agent runs.\n *\n * Most tracing tells you what an agent _did_, after the fact. A guard runs\n * _during_ the run: you feed it each step (an LLM call, a tool call, a\n * delegation), it accumulates cost / tokens / loop state, and evaluates a set\n * of rules. When a rule crosses its threshold the guard either records a\n * warning and lets the run continue, or stops the run — aborting an\n * {@link AbortSignal} and (by default) throwing a structured error so the agent\n * loop unwinds. No prompt, no retry, no runaway bill.\n *\n * This is the inline, OpenTelemetry-native analogue of a `watch` kill-switch:\n * cost ceilings, token ceilings, max tool calls, wall-clock timeouts, and\n * spin-loop / error-loop detection — all pure, deterministic logic with no LLM\n * in the loop.\n *\n * @example Budget ceiling that halts a runaway agent\n * ```typescript\n * import { createGenAiBudget } from 'autotel-genai/guard';\n * import { estimateLLMCost } from 'autotel-genai/cost';\n *\n * const budget = createGenAiBudget({ maxCostUsd: 5, warnAtUsd: 4 });\n *\n * for (const task of tasks) {\n * if (budget.stopped) break;\n * const res = await model.chat(task);\n * budget.record(\n * {\n * kind: 'llm',\n * usage: {\n * costUsd: estimateLLMCost('gpt-4o', {\n * inputTokens: res.usage.input,\n * outputTokens: res.usage.output,\n * }),\n * },\n * },\n * ctx, // optional TraceContext — records gen_ai.guard.* telemetry\n * ); // throws GEN_AI_GUARD_STOP once total cost > $5\n * }\n * ```\n *\n * @example Loop detection from a shorthand rule string\n * ```typescript\n * import { createGenAiGuard, parseGuardRules } from 'autotel-genai/guard';\n *\n * const guard = createGenAiGuard({\n * rules: parseGuardRules('budget:$2,loop:3/10,max-tools:50,timeout:5m'),\n * });\n *\n * guard.record({ kind: 'tool', name: 'search', signature: JSON.stringify(args) });\n * ```\n */\n\nimport { createStructuredError, type TraceContext } from 'autotel';\nimport { securityEvent } from 'autotel-audit';\nimport { GEN_AI, GEN_AI_GUARD_EVENT } from './semconv.js';\n\n/** What a rule does when it crosses its threshold. */\nexport type GuardAction = 'warn' | 'stop';\n\n/** Usage contribution for a single step. */\nexport interface GuardUsage {\n /**\n * Estimated USD cost for this step. Pair with\n * {@link import('./cost.js').estimateLLMCost} to compute it from token usage.\n */\n costUsd?: number;\n /** Input (prompt) tokens for this step. */\n inputTokens?: number;\n /** Output (completion) tokens for this step. */\n outputTokens?: number;\n}\n\n/** A single supervised step: an LLM call, a tool call, a delegation, … */\nexport interface GenAiGuardStep {\n /**\n * Step kind. `tool` increments the tool-call counter; any value is allowed.\n */\n kind?: 'llm' | 'tool' | 'agent' | 'workflow' | (string & {});\n /** Operation or tool name — used together with {@link signature} for loops. */\n name?: string;\n /**\n * Stable signature of the call inputs (e.g. `JSON.stringify(args)`). Two\n * steps with the same `name` + `signature` count as identical for spin-loop\n * detection. Hash or truncate it yourself if the raw args are large.\n */\n signature?: string;\n /** Whether this step failed. Drives error-loop detection. */\n error?: boolean;\n /** Cost / token contribution to the running totals. */\n usage?: GuardUsage;\n}\n\n/** Read-only snapshot of the accumulated session state. */\nexport interface GuardState {\n /** Epoch ms when the guard was created. */\n readonly startedAt: number;\n /** Epoch ms at evaluation time. */\n readonly now: number;\n /** Wall-clock ms since {@link startedAt}. */\n readonly elapsedMs: number;\n /** Accumulated estimated cost in USD. */\n readonly costUsd: number;\n /** Accumulated input tokens. */\n readonly inputTokens: number;\n /** Accumulated output tokens. */\n readonly outputTokens: number;\n /** Total steps recorded. */\n readonly stepCount: number;\n /** Steps with `kind === 'tool'`. */\n readonly toolCallCount: number;\n /** Steps with `error === true`. */\n readonly errorCount: number;\n /** Bounded recent history (newest last) for loop detection. */\n readonly history: ReadonlyArray<{ key: string | undefined; error: boolean }>;\n}\n\n/** A fired rule. */\nexport interface GuardViolation {\n /** Rule name, e.g. `cost-ceiling:$5`. */\n rule: string;\n /** Whether the run continued (`warn`) or was halted (`stop`). */\n action: GuardAction;\n /** Human-readable explanation. */\n message: string;\n /** The observed value that crossed the threshold. */\n observed: number;\n /** The configured threshold. */\n limit: number;\n}\n\n/** A guard rule: inspect the state after a step and optionally fire. */\nexport interface GenAiGuardRule {\n /** Stable identifier, surfaced on {@link GuardViolation.rule}. */\n name: string;\n /** Default {@link GuardAction} when the rule fires. Defaults to `stop`. */\n action?: GuardAction;\n /**\n * Evaluate against the post-step state and the step just recorded (absent on\n * a bare {@link GenAiGuard.check}). Return a partial violation to fire, or\n * `undefined` to pass.\n */\n evaluate: (\n state: GuardState,\n step: GenAiGuardStep | undefined,\n ) => { message: string; observed: number; limit: number } | undefined;\n}\n\n/** Minimal telemetry sink — the subset of {@link TraceContext} the guard uses. */\nexport type GuardSink = Pick<TraceContext, 'setAttributes' | 'track'>;\n\n/** What happens when a `stop` rule fires. */\nexport type GuardStopBehavior =\n /** Abort the signal and throw a structured error (default). */\n | 'throw'\n /** Abort the signal but do not throw — inspect `guard.stopped` yourself. */\n | 'abort'\n /** Record the violation only; neither abort nor throw. */\n | 'silent';\n\nexport interface GenAiGuardOptions {\n /** Rules to evaluate after each step. */\n rules: GenAiGuardRule[];\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /**\n * Max recent steps retained for loop detection. Defaults to 256; raise it if\n * a spin-loop rule uses a larger window.\n */\n historyLimit?: number;\n /** Clock injection point, for tests. Defaults to {@link Date.now}. */\n now?: () => number;\n}\n\n/** A live guard supervising an agent run. */\nexport interface GenAiGuard {\n /**\n * Record a step, accumulate its usage, and evaluate every rule. Returns the\n * violations that fired _this call_ (each rule fires at most once). When a\n * `stop` rule fires, aborts {@link signal} and — unless `onStop` is `abort` /\n * `silent` — throws a structured `GEN_AI_GUARD_STOP` error.\n */\n record(step: GenAiGuardStep, ctx?: GuardSink): GuardViolation[];\n /**\n * Re-evaluate the rules without recording a step. Useful for time-based\n * rules (e.g. a timeout) between LLM calls.\n */\n check(ctx?: GuardSink): GuardViolation[];\n /** Current accumulated state. */\n readonly state: GuardState;\n /** Fires once a `stop` rule has crossed its threshold. */\n readonly signal: AbortSignal;\n /** `true` after a `stop` rule has fired. */\n readonly stopped: boolean;\n /** Every violation fired so far, in order. */\n readonly violations: ReadonlyArray<GuardViolation>;\n}\n\n// --- Rule factories --------------------------------------------------------\n\nfunction round(n: number): number {\n return Math.round(n * 1e6) / 1e6;\n}\n\n/** Stop / warn when accumulated cost exceeds `limitUsd`. */\nexport function costCeiling(\n limitUsd: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `cost-ceiling:$${limitUsd}`,\n action,\n evaluate: (s) =>\n s.costUsd > limitUsd\n ? {\n message: `session cost $${round(s.costUsd)} exceeds $${limitUsd}`,\n observed: round(s.costUsd),\n limit: limitUsd,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when accumulated input + output tokens exceed `limit`. */\nexport function tokenCeiling(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `token-ceiling:${limit}`,\n action,\n evaluate: (s) => {\n const total = s.inputTokens + s.outputTokens;\n return total > limit\n ? {\n message: `session tokens ${total} exceed ${limit}`,\n observed: total,\n limit,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn when the number of tool calls exceeds `limit`. */\nexport function maxToolCalls(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-tool-calls:${limit}`,\n action,\n evaluate: (s) =>\n s.toolCallCount > limit\n ? {\n message: `tool calls ${s.toolCallCount} exceed ${limit}`,\n observed: s.toolCallCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when the total number of steps exceeds `limit`. */\nexport function maxSteps(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-steps:${limit}`,\n action,\n evaluate: (s) =>\n s.stepCount > limit\n ? {\n message: `steps ${s.stepCount} exceed ${limit}`,\n observed: s.stepCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when wall-clock time since start exceeds `limitMs`. */\nexport function maxDuration(\n limitMs: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-duration:${limitMs}ms`,\n action,\n evaluate: (s) =>\n s.elapsedMs > limitMs\n ? {\n message: `elapsed ${s.elapsedMs}ms exceeds ${limitMs}ms`,\n observed: s.elapsedMs,\n limit: limitMs,\n }\n : undefined,\n };\n}\n\n/**\n * Stop / warn on a spin loop: the same step (`name` + `signature`) repeated\n * `count` or more times within the last `window` steps. Steps without a `name`\n * are ignored (no identity to compare).\n */\nexport function spinLoop(\n options: { count: number; window: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count, window } = options;\n return {\n name: `spin-loop:${count}/${window}`,\n action,\n evaluate: (s, step) => {\n const key = stepKey(step);\n if (key === undefined) return undefined;\n const recent = s.history.slice(-window);\n let occurrences = 0;\n for (const h of recent) if (h.key === key) occurrences++;\n return occurrences >= count\n ? {\n message: `step \"${step?.name}\" repeated ${occurrences}× in last ${window}`,\n observed: occurrences,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn on `count` or more consecutive failing steps. */\nexport function errorLoop(\n options: { count: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count } = options;\n return {\n name: `error-loop:${count}`,\n action,\n evaluate: (s) => {\n let streak = 0;\n for (let i = s.history.length - 1; i >= 0; i--) {\n if (s.history[i].error) streak++;\n else break;\n }\n return streak >= count\n ? {\n message: `${streak} consecutive errors`,\n observed: streak,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/**\n * Approximate context-window sizes (in input tokens) for common models.\n * Matched exactly first, then by longest key prefix. Override via the `limit`\n * option on {@link contextBudget}.\n */\nexport const CONTEXT_LIMITS: Record<string, number> = {\n 'gpt-4o': 128_000,\n 'gpt-4.1': 1_047_576,\n 'gpt-4': 8192,\n 'o3-mini': 200_000,\n 'claude-opus-4': 200_000,\n 'claude-sonnet-4': 200_000,\n 'claude-3-5-sonnet': 200_000,\n 'claude-3-5-haiku': 200_000,\n 'claude-3': 200_000,\n 'gemini-1.5-pro': 2_097_152,\n 'gemini-1.5-flash': 1_048_576,\n 'gemini-2.0-flash': 1_048_576,\n};\n\nfunction resolveContextLimit(model: string): number | undefined {\n const exact = CONTEXT_LIMITS[model];\n if (exact) return exact;\n let best: number | undefined;\n let bestLength = 0;\n for (const key of Object.keys(CONTEXT_LIMITS)) {\n if (model.startsWith(key) && key.length > bestLength) {\n best = CONTEXT_LIMITS[key];\n bestLength = key.length;\n }\n }\n return best;\n}\n\n/**\n * Stop / warn when cumulative input tokens reach `threshold` (default 0.9) of\n * the model's context window. Provide an explicit `limit`, or a `model` to look\n * one up from {@link CONTEXT_LIMITS}.\n */\nexport function contextBudget(\n options: { model?: string; limit?: number; threshold?: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const threshold = options.threshold ?? 0.9;\n const limit =\n options.limit ?? (options.model ? resolveContextLimit(options.model) : undefined);\n return {\n name: `context-budget:${Math.round(threshold * 100)}%`,\n action,\n evaluate: (s) => {\n if (!limit) return undefined;\n const ratio = s.inputTokens / limit;\n return ratio >= threshold\n ? {\n message: `context ${Math.round(ratio * 100)}% full (${s.inputTokens}/${limit})`,\n observed: round(ratio),\n limit: threshold,\n }\n : undefined;\n },\n };\n}\n\nfunction stepKey(step: GenAiGuardStep | undefined): string | undefined {\n if (!step || step.name === undefined) return undefined;\n return `${step.name}\u0000${step.signature ?? ''}`;\n}\n\n// --- Shorthand rule parser -------------------------------------------------\n\nfunction parseScaledNumber(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([kmb])?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid number: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const scale = { k: 1e3, m: 1e6, b: 1e9 }[m[2]?.toLowerCase() ?? ''] ?? 1;\n return value * scale;\n}\n\nfunction parseDurationMs(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid duration: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const unit = (m[2] ?? 's').toLowerCase();\n const scale = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[unit] ?? 1000;\n return value * scale;\n}\n\n/**\n * Parse a comma-separated shorthand rule string into {@link GenAiGuardRule}s.\n * All parsed rules default to the `stop` action — pass `defaultAction: 'warn'`\n * to warn instead, or build typed rules directly for per-rule actions.\n *\n * Supported tokens:\n * - `budget:$5` / `cost:$5` — {@link costCeiling}\n * - `tokens:100k` — {@link tokenCeiling} (`k`/`m`/`b` suffixes)\n * - `loop:3/10` — {@link spinLoop} (count / window)\n * - `errors:3` — {@link errorLoop}\n * - `max-tools:50` — {@link maxToolCalls}\n * - `max-steps:100` — {@link maxSteps}\n * - `timeout:30m` — {@link maxDuration} (`ms`/`s`/`m`/`h`, default seconds)\n * - `context:0.9` / `context:0.9@gpt-4o` — {@link contextBudget}\n */\nexport function parseGuardRules(\n shorthand: string,\n options?: { defaultAction?: GuardAction },\n): GenAiGuardRule[] {\n const action = options?.defaultAction ?? 'stop';\n const rules: GenAiGuardRule[] = [];\n for (const token of shorthand.split(',')) {\n const trimmed = token.trim();\n if (!trimmed) continue;\n const sep = trimmed.indexOf(':');\n if (sep === -1) throw new Error(`invalid guard rule: \"${trimmed}\"`);\n const key = trimmed.slice(0, sep).trim().toLowerCase();\n const value = trimmed.slice(sep + 1).trim();\n\n switch (key) {\n case 'budget':\n case 'cost': {\n rules.push(costCeiling(parseScaledNumber(value.replace(/^\\$/, '')), action));\n break;\n }\n case 'tokens': {\n rules.push(tokenCeiling(parseScaledNumber(value), action));\n break;\n }\n case 'loop': {\n const [count, window] = value.split('/');\n rules.push(\n spinLoop(\n { count: parseScaledNumber(count), window: parseScaledNumber(window) },\n action,\n ),\n );\n break;\n }\n case 'errors': {\n rules.push(errorLoop({ count: parseScaledNumber(value) }, action));\n break;\n }\n case 'max-tools': {\n rules.push(maxToolCalls(parseScaledNumber(value), action));\n break;\n }\n case 'max-steps': {\n rules.push(maxSteps(parseScaledNumber(value), action));\n break;\n }\n case 'timeout': {\n rules.push(maxDuration(parseDurationMs(value), action));\n break;\n }\n case 'context': {\n const [thr, model] = value.split('@');\n rules.push(\n contextBudget(\n { threshold: Number.parseFloat(thr), model: model?.trim() || undefined },\n action,\n ),\n );\n break;\n }\n default: {\n throw new Error(`unknown guard rule: \"${key}\"`);\n }\n }\n }\n return rules;\n}\n\n// --- Guard implementation --------------------------------------------------\n\nfunction recordTelemetry(\n ctx: GuardSink,\n state: GuardState,\n newViolations: GuardViolation[],\n stopped: boolean,\n): void {\n ctx.setAttributes({\n [GEN_AI.SESSION_COST_USD]: round(state.costUsd),\n [GEN_AI.SESSION_INPUT_TOKENS]: state.inputTokens,\n [GEN_AI.SESSION_OUTPUT_TOKENS]: state.outputTokens,\n [GEN_AI.SESSION_STEP_COUNT]: state.stepCount,\n [GEN_AI.SESSION_TOOL_CALL_COUNT]: state.toolCallCount,\n [GEN_AI.SESSION_ERROR_COUNT]: state.errorCount,\n });\n if (newViolations.length === 0) return;\n if (stopped) ctx.setAttributes({ [GEN_AI.GUARD_STOPPED]: true });\n for (const violation of newViolations) {\n ctx.track(\n violation.action === 'stop'\n ? GEN_AI_GUARD_EVENT.STOP\n : GEN_AI_GUARD_EVENT.WARNING,\n {\n [GEN_AI.GUARD_RULE]: violation.rule,\n [GEN_AI.GUARD_ACTION]: violation.action,\n [GEN_AI.GUARD_MESSAGE]: violation.message,\n [GEN_AI.GUARD_OBSERVED]: violation.observed,\n [GEN_AI.GUARD_LIMIT]: violation.limit,\n },\n );\n if (violation.action === 'stop') {\n securityEvent(\n {\n name: 'llm.guard.triggered',\n category: 'llm',\n outcome: 'blocked',\n severity: 'error',\n reason: violation.rule,\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n },\n { onMissingContext: 'warn' },\n );\n }\n }\n}\n\n/**\n * Create a guard that supervises an in-process agent run against `rules`.\n */\nexport function createGenAiGuard(options: GenAiGuardOptions): GenAiGuard {\n const { rules } = options;\n const onStop = options.onStop ?? 'throw';\n const historyLimit = options.historyLimit ?? 256;\n const now = options.now ?? Date.now;\n const startedAt = now();\n\n const controller = new AbortController();\n const history: { key: string | undefined; error: boolean }[] = [];\n const fired = new Set<string>();\n const violations: GuardViolation[] = [];\n\n let costUsd = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let stepCount = 0;\n let toolCallCount = 0;\n let errorCount = 0;\n let stopped = false;\n\n function snapshot(): GuardState {\n const at = now();\n return {\n startedAt,\n now: at,\n elapsedMs: at - startedAt,\n costUsd,\n inputTokens,\n outputTokens,\n stepCount,\n toolCallCount,\n errorCount,\n history,\n };\n }\n\n function evaluate(\n step: GenAiGuardStep | undefined,\n ctx: GuardSink | undefined,\n ): GuardViolation[] {\n const state = snapshot();\n const newViolations: GuardViolation[] = [];\n\n for (const rule of rules) {\n if (fired.has(rule.name)) continue;\n const hit = rule.evaluate(state, step);\n if (!hit) continue;\n fired.add(rule.name);\n const violation: GuardViolation = {\n rule: rule.name,\n action: rule.action ?? 'stop',\n message: hit.message,\n observed: hit.observed,\n limit: hit.limit,\n };\n violations.push(violation);\n newViolations.push(violation);\n }\n\n const stopViolation = newViolations.find((v) => v.action === 'stop');\n if (stopViolation && !stopped) {\n stopped = true;\n if (onStop !== 'silent') controller.abort(toStopError(stopViolation, state));\n }\n\n if (ctx) recordTelemetry(ctx, state, newViolations, stopped);\n\n if (stopViolation && onStop === 'throw') {\n throw toStopError(stopViolation, snapshot());\n }\n return newViolations;\n }\n\n return {\n record(step, ctx) {\n stepCount++;\n if (step.kind === 'tool') toolCallCount++;\n if (step.error) errorCount++;\n if (step.usage) {\n costUsd += step.usage.costUsd ?? 0;\n inputTokens += step.usage.inputTokens ?? 0;\n outputTokens += step.usage.outputTokens ?? 0;\n }\n history.push({ key: stepKey(step), error: step.error === true });\n if (history.length > historyLimit) history.shift();\n return evaluate(step, ctx);\n },\n check(ctx) {\n return evaluate(undefined, ctx);\n },\n get state() {\n return snapshot();\n },\n get signal() {\n return controller.signal;\n },\n get stopped() {\n return stopped;\n },\n get violations() {\n return violations;\n },\n };\n}\n\nfunction toStopError(violation: GuardViolation, state: GuardState): Error {\n return createStructuredError({\n name: 'GenAiGuardStop',\n code: 'GEN_AI_GUARD_STOP',\n status: 429,\n message: `Guard rule \"${violation.rule}\" halted the run: ${violation.message}`,\n why: 'A stop-action guard rule crossed its threshold during the agent run.',\n fix: 'Raise the limit, fix the loop, or handle GEN_AI_GUARD_STOP to wind the run down cleanly.',\n details: {\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n costUsd: round(state.costUsd),\n stepCount: state.stepCount,\n },\n });\n}\n\n// --- Budget preset ---------------------------------------------------------\n\nexport interface GenAiBudgetOptions {\n /** Hard cost ceiling in USD — a `stop` rule. */\n maxCostUsd?: number;\n /** Soft cost threshold in USD — a `warn` rule. */\n warnAtUsd?: number;\n /** Hard token ceiling (input + output) — a `stop` rule. */\n maxTokens?: number;\n /** Hard tool-call ceiling — a `stop` rule. */\n maxToolCalls?: number;\n /** Hard wall-clock ceiling in ms — a `stop` rule. */\n maxDurationMs?: number;\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /** Clock injection point, for tests. */\n now?: () => number;\n}\n\n/**\n * Convenience preset that wires the common cost / token / tool-call / duration\n * ceilings into a {@link createGenAiGuard}. Returns the same {@link GenAiGuard}.\n */\nexport function createGenAiBudget(options: GenAiBudgetOptions): GenAiGuard {\n const rules: GenAiGuardRule[] = [];\n if (options.warnAtUsd !== undefined) {\n rules.push(costCeiling(options.warnAtUsd, 'warn'));\n }\n if (options.maxCostUsd !== undefined) {\n rules.push(costCeiling(options.maxCostUsd, 'stop'));\n }\n if (options.maxTokens !== undefined) {\n rules.push(tokenCeiling(options.maxTokens, 'stop'));\n }\n if (options.maxToolCalls !== undefined) {\n rules.push(maxToolCalls(options.maxToolCalls, 'stop'));\n }\n if (options.maxDurationMs !== undefined) {\n rules.push(maxDuration(options.maxDurationMs, 'stop'));\n }\n return createGenAiGuard({\n rules,\n onStop: options.onStop,\n now: options.now,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwMA,SAAS,MAAM,GAAmB;CAChC,OAAO,KAAK,MAAM,IAAI,GAAG,IAAI;AAC/B;;AAGA,SAAgB,YACd,UACA,SAAsB,QACN;CAChB,OAAO;EACL,MAAM,iBAAiB;EACvB;EACA,WAAW,MACT,EAAE,UAAU,WACR;GACE,SAAS,iBAAiB,MAA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G;EAChC;EACA,IAAI,QAAQ;GACV,OAAO,SAAS;EAClB;EACA,IAAI,SAAS;GACX,OAAO,WAAW;EACpB;EACA,IAAI,UAAU;GACZ,OAAO;EACT;EACA,IAAI,aAAa;GACf,OAAO;EACT;CACF;AACF;AAEA,SAAS,YAAY,WAA2B,OAA0B;CACxE,0CAA6B;EAC3B,MAAM;EACN,MAAM;EACN,QAAQ;EACR,SAAS,eAAe,UAAU,KAAK,oBAAoB,UAAU;EACrE,KAAK;EACL,KAAK;EACL,SAAS;GACP,MAAM,UAAU;GAChB,UAAU,UAAU;GACpB,OAAO,UAAU;GACjB,SAAS,MAAM,MAAM,OAAO;GAC5B,WAAW,MAAM;EACnB;CACF,CAAC;AACH;;;;;AAyBA,SAAgB,kBAAkB,SAAyC;CACzE,MAAM,QAA0B,CAAC;CACjC,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,YAAY,QAAQ,WAAW,MAAM,CAAC;CACnD;CACA,IAAI,QAAQ,eAAe,WAAW;EACpC,MAAM,KAAK,YAAY,QAAQ,YAAY,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,aAAa,QAAQ,WAAW,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,iBAAiB,WAAW;EACtC,MAAM,KAAK,aAAa,QAAQ,cAAc,MAAM,CAAC;CACvD;CACA,IAAI,QAAQ,kBAAkB,WAAW;EACvC,MAAM,KAAK,YAAY,QAAQ,eAAe,MAAM,CAAC;CACvD;CACA,OAAO,iBAAiB;EACtB;EACA,QAAQ,QAAQ;EAChB,KAAK,QAAQ;CACf,CAAC;AACH"}
|
package/dist/guard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guard.js","names":[],"sources":["../src/guard.ts"],"sourcesContent":["/**\n * GenAI guard / budget runtime — an in-process kill-switch for agent runs.\n *\n * Most tracing tells you what an agent _did_, after the fact. A guard runs\n * _during_ the run: you feed it each step (an LLM call, a tool call, a\n * delegation), it accumulates cost / tokens / loop state, and evaluates a set\n * of rules. When a rule crosses its threshold the guard either records a\n * warning and lets the run continue, or stops the run — aborting an\n * {@link AbortSignal} and (by default) throwing a structured error so the agent\n * loop unwinds. No prompt, no retry, no runaway bill.\n *\n * This is the inline, OpenTelemetry-native analogue of a `watch` kill-switch:\n * cost ceilings, token ceilings, max tool calls, wall-clock timeouts, and\n * spin-loop / error-loop detection — all pure, deterministic logic with no LLM\n * in the loop.\n *\n * @example Budget ceiling that halts a runaway agent\n * ```typescript\n * import { createGenAiBudget } from 'autotel-genai/guard';\n * import { estimateLLMCost } from 'autotel-genai/cost';\n *\n * const budget = createGenAiBudget({ maxCostUsd: 5, warnAtUsd: 4 });\n *\n * for (const task of tasks) {\n * if (budget.stopped) break;\n * const res = await model.chat(task);\n * budget.record(\n * {\n * kind: 'llm',\n * usage: {\n * costUsd: estimateLLMCost('gpt-4o', {\n * inputTokens: res.usage.input,\n * outputTokens: res.usage.output,\n * }),\n * },\n * },\n * ctx, // optional TraceContext — records gen_ai.guard.* telemetry\n * ); // throws GEN_AI_GUARD_STOP once total cost > $5\n * }\n * ```\n *\n * @example Loop detection from a shorthand rule string\n * ```typescript\n * import { createGenAiGuard, parseGuardRules } from 'autotel-genai/guard';\n *\n * const guard = createGenAiGuard({\n * rules: parseGuardRules('budget:$2,loop:3/10,max-tools:50,timeout:5m'),\n * });\n *\n * guard.record({ kind: 'tool', name: 'search', signature: JSON.stringify(args) });\n * ```\n */\n\nimport { createStructuredError, type TraceContext } from 'autotel';\nimport { securityEvent } from 'autotel-audit';\nimport { GEN_AI, GEN_AI_GUARD_EVENT } from './semconv.js';\n\n/** What a rule does when it crosses its threshold. */\nexport type GuardAction = 'warn' | 'stop';\n\n/** Usage contribution for a single step. */\nexport interface GuardUsage {\n /**\n * Estimated USD cost for this step. Pair with\n * {@link import('./cost.js').estimateLLMCost} to compute it from token usage.\n */\n costUsd?: number;\n /** Input (prompt) tokens for this step. */\n inputTokens?: number;\n /** Output (completion) tokens for this step. */\n outputTokens?: number;\n}\n\n/** A single supervised step: an LLM call, a tool call, a delegation, … */\nexport interface GenAiGuardStep {\n /**\n * Step kind. `tool` increments the tool-call counter; any value is allowed.\n */\n kind?: 'llm' | 'tool' | 'agent' | 'workflow' | (string & {});\n /** Operation or tool name — used together with {@link signature} for loops. */\n name?: string;\n /**\n * Stable signature of the call inputs (e.g. `JSON.stringify(args)`). Two\n * steps with the same `name` + `signature` count as identical for spin-loop\n * detection. Hash or truncate it yourself if the raw args are large.\n */\n signature?: string;\n /** Whether this step failed. Drives error-loop detection. */\n error?: boolean;\n /** Cost / token contribution to the running totals. */\n usage?: GuardUsage;\n}\n\n/** Read-only snapshot of the accumulated session state. */\nexport interface GuardState {\n /** Epoch ms when the guard was created. */\n readonly startedAt: number;\n /** Epoch ms at evaluation time. */\n readonly now: number;\n /** Wall-clock ms since {@link startedAt}. */\n readonly elapsedMs: number;\n /** Accumulated estimated cost in USD. */\n readonly costUsd: number;\n /** Accumulated input tokens. */\n readonly inputTokens: number;\n /** Accumulated output tokens. */\n readonly outputTokens: number;\n /** Total steps recorded. */\n readonly stepCount: number;\n /** Steps with `kind === 'tool'`. */\n readonly toolCallCount: number;\n /** Steps with `error === true`. */\n readonly errorCount: number;\n /** Bounded recent history (newest last) for loop detection. */\n readonly history: ReadonlyArray<{ key: string | undefined; error: boolean }>;\n}\n\n/** A fired rule. */\nexport interface GuardViolation {\n /** Rule name, e.g. `cost-ceiling:$5`. */\n rule: string;\n /** Whether the run continued (`warn`) or was halted (`stop`). */\n action: GuardAction;\n /** Human-readable explanation. */\n message: string;\n /** The observed value that crossed the threshold. */\n observed: number;\n /** The configured threshold. */\n limit: number;\n}\n\n/** A guard rule: inspect the state after a step and optionally fire. */\nexport interface GenAiGuardRule {\n /** Stable identifier, surfaced on {@link GuardViolation.rule}. */\n name: string;\n /** Default {@link GuardAction} when the rule fires. Defaults to `stop`. */\n action?: GuardAction;\n /**\n * Evaluate against the post-step state and the step just recorded (absent on\n * a bare {@link GenAiGuard.check}). Return a partial violation to fire, or\n * `undefined` to pass.\n */\n evaluate: (\n state: GuardState,\n step: GenAiGuardStep | undefined,\n ) => { message: string; observed: number; limit: number } | undefined;\n}\n\n/** Minimal telemetry sink — the subset of {@link TraceContext} the guard uses. */\nexport type GuardSink = Pick<TraceContext, 'setAttributes' | 'track'>;\n\n/** What happens when a `stop` rule fires. */\nexport type GuardStopBehavior =\n /** Abort the signal and throw a structured error (default). */\n | 'throw'\n /** Abort the signal but do not throw — inspect `guard.stopped` yourself. */\n | 'abort'\n /** Record the violation only; neither abort nor throw. */\n | 'silent';\n\nexport interface GenAiGuardOptions {\n /** Rules to evaluate after each step. */\n rules: GenAiGuardRule[];\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /**\n * Max recent steps retained for loop detection. Defaults to 256; raise it if\n * a spin-loop rule uses a larger window.\n */\n historyLimit?: number;\n /** Clock injection point, for tests. Defaults to {@link Date.now}. */\n now?: () => number;\n}\n\n/** A live guard supervising an agent run. */\nexport interface GenAiGuard {\n /**\n * Record a step, accumulate its usage, and evaluate every rule. Returns the\n * violations that fired _this call_ (each rule fires at most once). When a\n * `stop` rule fires, aborts {@link signal} and — unless `onStop` is `abort` /\n * `silent` — throws a structured `GEN_AI_GUARD_STOP` error.\n */\n record(step: GenAiGuardStep, ctx?: GuardSink): GuardViolation[];\n /**\n * Re-evaluate the rules without recording a step. Useful for time-based\n * rules (e.g. a timeout) between LLM calls.\n */\n check(ctx?: GuardSink): GuardViolation[];\n /** Current accumulated state. */\n readonly state: GuardState;\n /** Fires once a `stop` rule has crossed its threshold. */\n readonly signal: AbortSignal;\n /** `true` after a `stop` rule has fired. */\n readonly stopped: boolean;\n /** Every violation fired so far, in order. */\n readonly violations: ReadonlyArray<GuardViolation>;\n}\n\n// --- Rule factories --------------------------------------------------------\n\nfunction round(n: number): number {\n return Math.round(n * 1e6) / 1e6;\n}\n\n/** Stop / warn when accumulated cost exceeds `limitUsd`. */\nexport function costCeiling(\n limitUsd: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `cost-ceiling:$${limitUsd}`,\n action,\n evaluate: (s) =>\n s.costUsd > limitUsd\n ? {\n message: `session cost $${round(s.costUsd)} exceeds $${limitUsd}`,\n observed: round(s.costUsd),\n limit: limitUsd,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when accumulated input + output tokens exceed `limit`. */\nexport function tokenCeiling(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `token-ceiling:${limit}`,\n action,\n evaluate: (s) => {\n const total = s.inputTokens + s.outputTokens;\n return total > limit\n ? {\n message: `session tokens ${total} exceed ${limit}`,\n observed: total,\n limit,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn when the number of tool calls exceeds `limit`. */\nexport function maxToolCalls(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-tool-calls:${limit}`,\n action,\n evaluate: (s) =>\n s.toolCallCount > limit\n ? {\n message: `tool calls ${s.toolCallCount} exceed ${limit}`,\n observed: s.toolCallCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when the total number of steps exceeds `limit`. */\nexport function maxSteps(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-steps:${limit}`,\n action,\n evaluate: (s) =>\n s.stepCount > limit\n ? {\n message: `steps ${s.stepCount} exceed ${limit}`,\n observed: s.stepCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when wall-clock time since start exceeds `limitMs`. */\nexport function maxDuration(\n limitMs: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-duration:${limitMs}ms`,\n action,\n evaluate: (s) =>\n s.elapsedMs > limitMs\n ? {\n message: `elapsed ${s.elapsedMs}ms exceeds ${limitMs}ms`,\n observed: s.elapsedMs,\n limit: limitMs,\n }\n : undefined,\n };\n}\n\n/**\n * Stop / warn on a spin loop: the same step (`name` + `signature`) repeated\n * `count` or more times within the last `window` steps. Steps without a `name`\n * are ignored (no identity to compare).\n */\nexport function spinLoop(\n options: { count: number; window: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count, window } = options;\n return {\n name: `spin-loop:${count}/${window}`,\n action,\n evaluate: (s, step) => {\n const key = stepKey(step);\n if (key === undefined) return undefined;\n const recent = s.history.slice(-window);\n let occurrences = 0;\n for (const h of recent) if (h.key === key) occurrences++;\n return occurrences >= count\n ? {\n message: `step \"${step?.name}\" repeated ${occurrences}× in last ${window}`,\n observed: occurrences,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn on `count` or more consecutive failing steps. */\nexport function errorLoop(\n options: { count: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count } = options;\n return {\n name: `error-loop:${count}`,\n action,\n evaluate: (s) => {\n let streak = 0;\n for (let i = s.history.length - 1; i >= 0; i--) {\n if (s.history[i].error) streak++;\n else break;\n }\n return streak >= count\n ? {\n message: `${streak} consecutive errors`,\n observed: streak,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/**\n * Approximate context-window sizes (in input tokens) for common models.\n * Matched exactly first, then by longest key prefix. Override via the `limit`\n * option on {@link contextBudget}.\n */\nexport const CONTEXT_LIMITS: Record<string, number> = {\n 'gpt-4o': 128_000,\n 'gpt-4.1': 1_047_576,\n 'gpt-4': 8192,\n 'o3-mini': 200_000,\n 'claude-opus-4': 200_000,\n 'claude-sonnet-4': 200_000,\n 'claude-3-5-sonnet': 200_000,\n 'claude-3-5-haiku': 200_000,\n 'claude-3': 200_000,\n 'gemini-1.5-pro': 2_097_152,\n 'gemini-1.5-flash': 1_048_576,\n 'gemini-2.0-flash': 1_048_576,\n};\n\nfunction resolveContextLimit(model: string): number | undefined {\n const exact = CONTEXT_LIMITS[model];\n if (exact) return exact;\n let best: number | undefined;\n let bestLength = 0;\n for (const key of Object.keys(CONTEXT_LIMITS)) {\n if (model.startsWith(key) && key.length > bestLength) {\n best = CONTEXT_LIMITS[key];\n bestLength = key.length;\n }\n }\n return best;\n}\n\n/**\n * Stop / warn when cumulative input tokens reach `threshold` (default 0.9) of\n * the model's context window. Provide an explicit `limit`, or a `model` to look\n * one up from {@link CONTEXT_LIMITS}.\n */\nexport function contextBudget(\n options: { model?: string; limit?: number; threshold?: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const threshold = options.threshold ?? 0.9;\n const limit =\n options.limit ?? (options.model ? resolveContextLimit(options.model) : undefined);\n return {\n name: `context-budget:${Math.round(threshold * 100)}%`,\n action,\n evaluate: (s) => {\n if (!limit) return undefined;\n const ratio = s.inputTokens / limit;\n return ratio >= threshold\n ? {\n message: `context ${Math.round(ratio * 100)}% full (${s.inputTokens}/${limit})`,\n observed: round(ratio),\n limit: threshold,\n }\n : undefined;\n },\n };\n}\n\nfunction stepKey(step: GenAiGuardStep | undefined): string | undefined {\n if (!step || step.name === undefined) return undefined;\n return `${step.name}\u0000${step.signature ?? ''}`;\n}\n\n// --- Shorthand rule parser -------------------------------------------------\n\nfunction parseScaledNumber(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([kmb])?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid number: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const scale = { k: 1e3, m: 1e6, b: 1e9 }[m[2]?.toLowerCase() ?? ''] ?? 1;\n return value * scale;\n}\n\nfunction parseDurationMs(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid duration: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const unit = (m[2] ?? 's').toLowerCase();\n const scale = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[unit] ?? 1000;\n return value * scale;\n}\n\n/**\n * Parse a comma-separated shorthand rule string into {@link GenAiGuardRule}s.\n * All parsed rules default to the `stop` action — pass `defaultAction: 'warn'`\n * to warn instead, or build typed rules directly for per-rule actions.\n *\n * Supported tokens:\n * - `budget:$5` / `cost:$5` — {@link costCeiling}\n * - `tokens:100k` — {@link tokenCeiling} (`k`/`m`/`b` suffixes)\n * - `loop:3/10` — {@link spinLoop} (count / window)\n * - `errors:3` — {@link errorLoop}\n * - `max-tools:50` — {@link maxToolCalls}\n * - `max-steps:100` — {@link maxSteps}\n * - `timeout:30m` — {@link maxDuration} (`ms`/`s`/`m`/`h`, default seconds)\n * - `context:0.9` / `context:0.9@gpt-4o` — {@link contextBudget}\n */\nexport function parseGuardRules(\n shorthand: string,\n options?: { defaultAction?: GuardAction },\n): GenAiGuardRule[] {\n const action = options?.defaultAction ?? 'stop';\n const rules: GenAiGuardRule[] = [];\n for (const token of shorthand.split(',')) {\n const trimmed = token.trim();\n if (!trimmed) continue;\n const sep = trimmed.indexOf(':');\n if (sep === -1) throw new Error(`invalid guard rule: \"${trimmed}\"`);\n const key = trimmed.slice(0, sep).trim().toLowerCase();\n const value = trimmed.slice(sep + 1).trim();\n\n switch (key) {\n case 'budget':\n case 'cost': {\n rules.push(costCeiling(parseScaledNumber(value.replace(/^\\$/, '')), action));\n break;\n }\n case 'tokens': {\n rules.push(tokenCeiling(parseScaledNumber(value), action));\n break;\n }\n case 'loop': {\n const [count, window] = value.split('/');\n rules.push(\n spinLoop(\n { count: parseScaledNumber(count), window: parseScaledNumber(window) },\n action,\n ),\n );\n break;\n }\n case 'errors': {\n rules.push(errorLoop({ count: parseScaledNumber(value) }, action));\n break;\n }\n case 'max-tools': {\n rules.push(maxToolCalls(parseScaledNumber(value), action));\n break;\n }\n case 'max-steps': {\n rules.push(maxSteps(parseScaledNumber(value), action));\n break;\n }\n case 'timeout': {\n rules.push(maxDuration(parseDurationMs(value), action));\n break;\n }\n case 'context': {\n const [thr, model] = value.split('@');\n rules.push(\n contextBudget(\n { threshold: Number.parseFloat(thr), model: model?.trim() || undefined },\n action,\n ),\n );\n break;\n }\n default: {\n throw new Error(`unknown guard rule: \"${key}\"`);\n }\n }\n }\n return rules;\n}\n\n// --- Guard implementation --------------------------------------------------\n\nfunction recordTelemetry(\n ctx: GuardSink,\n state: GuardState,\n newViolations: GuardViolation[],\n stopped: boolean,\n): void {\n ctx.setAttributes({\n [GEN_AI.SESSION_COST_USD]: round(state.costUsd),\n [GEN_AI.SESSION_INPUT_TOKENS]: state.inputTokens,\n [GEN_AI.SESSION_OUTPUT_TOKENS]: state.outputTokens,\n [GEN_AI.SESSION_STEP_COUNT]: state.stepCount,\n [GEN_AI.SESSION_TOOL_CALL_COUNT]: state.toolCallCount,\n [GEN_AI.SESSION_ERROR_COUNT]: state.errorCount,\n });\n if (newViolations.length === 0) return;\n if (stopped) ctx.setAttributes({ [GEN_AI.GUARD_STOPPED]: true });\n for (const violation of newViolations) {\n ctx.track(\n violation.action === 'stop'\n ? GEN_AI_GUARD_EVENT.STOP\n : GEN_AI_GUARD_EVENT.WARNING,\n {\n [GEN_AI.GUARD_RULE]: violation.rule,\n [GEN_AI.GUARD_ACTION]: violation.action,\n [GEN_AI.GUARD_MESSAGE]: violation.message,\n [GEN_AI.GUARD_OBSERVED]: violation.observed,\n [GEN_AI.GUARD_LIMIT]: violation.limit,\n },\n );\n if (violation.action === 'stop') {\n securityEvent(\n {\n name: 'llm.guard.triggered',\n category: 'llm',\n outcome: 'blocked',\n severity: 'error',\n reason: violation.rule,\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n },\n { onMissingContext: 'warn' },\n );\n }\n }\n}\n\n/**\n * Create a guard that supervises an in-process agent run against `rules`.\n */\nexport function createGenAiGuard(options: GenAiGuardOptions): GenAiGuard {\n const { rules } = options;\n const onStop = options.onStop ?? 'throw';\n const historyLimit = options.historyLimit ?? 256;\n const now = options.now ?? Date.now;\n const startedAt = now();\n\n const controller = new AbortController();\n const history: { key: string | undefined; error: boolean }[] = [];\n const fired = new Set<string>();\n const violations: GuardViolation[] = [];\n\n let costUsd = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let stepCount = 0;\n let toolCallCount = 0;\n let errorCount = 0;\n let stopped = false;\n\n function snapshot(): GuardState {\n const at = now();\n return {\n startedAt,\n now: at,\n elapsedMs: at - startedAt,\n costUsd,\n inputTokens,\n outputTokens,\n stepCount,\n toolCallCount,\n errorCount,\n history,\n };\n }\n\n function evaluate(\n step: GenAiGuardStep | undefined,\n ctx: GuardSink | undefined,\n ): GuardViolation[] {\n const state = snapshot();\n const newViolations: GuardViolation[] = [];\n\n for (const rule of rules) {\n if (fired.has(rule.name)) continue;\n const hit = rule.evaluate(state, step);\n if (!hit) continue;\n fired.add(rule.name);\n const violation: GuardViolation = {\n rule: rule.name,\n action: rule.action ?? 'stop',\n message: hit.message,\n observed: hit.observed,\n limit: hit.limit,\n };\n violations.push(violation);\n newViolations.push(violation);\n }\n\n const stopViolation = newViolations.find((v) => v.action === 'stop');\n if (stopViolation && !stopped) {\n stopped = true;\n if (onStop !== 'silent') controller.abort(toStopError(stopViolation, state));\n }\n\n if (ctx) recordTelemetry(ctx, state, newViolations, stopped);\n\n if (stopViolation && onStop === 'throw') {\n throw toStopError(stopViolation, snapshot());\n }\n return newViolations;\n }\n\n return {\n record(step, ctx) {\n stepCount++;\n if (step.kind === 'tool') toolCallCount++;\n if (step.error) errorCount++;\n if (step.usage) {\n costUsd += step.usage.costUsd ?? 0;\n inputTokens += step.usage.inputTokens ?? 0;\n outputTokens += step.usage.outputTokens ?? 0;\n }\n history.push({ key: stepKey(step), error: step.error === true });\n if (history.length > historyLimit) history.shift();\n return evaluate(step, ctx);\n },\n check(ctx) {\n return evaluate(undefined, ctx);\n },\n get state() {\n return snapshot();\n },\n get signal() {\n return controller.signal;\n },\n get stopped() {\n return stopped;\n },\n get violations() {\n return violations;\n },\n };\n}\n\nfunction toStopError(violation: GuardViolation, state: GuardState): Error {\n return createStructuredError({\n name: 'GenAiGuardStop',\n code: 'GEN_AI_GUARD_STOP',\n status: 429,\n message: `Guard rule \"${violation.rule}\" halted the run: ${violation.message}`,\n why: 'A stop-action guard rule crossed its threshold during the agent run.',\n fix: 'Raise the limit, fix the loop, or handle GEN_AI_GUARD_STOP to wind the run down cleanly.',\n details: {\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n costUsd: round(state.costUsd),\n stepCount: state.stepCount,\n },\n });\n}\n\n// --- Budget preset ---------------------------------------------------------\n\nexport interface GenAiBudgetOptions {\n /** Hard cost ceiling in USD — a `stop` rule. */\n maxCostUsd?: number;\n /** Soft cost threshold in USD — a `warn` rule. */\n warnAtUsd?: number;\n /** Hard token ceiling (input + output) — a `stop` rule. */\n maxTokens?: number;\n /** Hard tool-call ceiling — a `stop` rule. */\n maxToolCalls?: number;\n /** Hard wall-clock ceiling in ms — a `stop` rule. */\n maxDurationMs?: number;\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /** Clock injection point, for tests. */\n now?: () => number;\n}\n\n/**\n * Convenience preset that wires the common cost / token / tool-call / duration\n * ceilings into a {@link createGenAiGuard}. Returns the same {@link GenAiGuard}.\n */\nexport function createGenAiBudget(options: GenAiBudgetOptions): GenAiGuard {\n const rules: GenAiGuardRule[] = [];\n if (options.warnAtUsd !== undefined) {\n rules.push(costCeiling(options.warnAtUsd, 'warn'));\n }\n if (options.maxCostUsd !== undefined) {\n rules.push(costCeiling(options.maxCostUsd, 'stop'));\n }\n if (options.maxTokens !== undefined) {\n rules.push(tokenCeiling(options.maxTokens, 'stop'));\n }\n if (options.maxToolCalls !== undefined) {\n rules.push(maxToolCalls(options.maxToolCalls, 'stop'));\n }\n if (options.maxDurationMs !== undefined) {\n rules.push(maxDuration(options.maxDurationMs, 'stop'));\n }\n return createGenAiGuard({\n rules,\n onStop: options.onStop,\n now: options.now,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwMA,SAAS,MAAM,GAAmB;CAChC,OAAO,KAAK,MAAM,IAAI,GAAG,I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,QAAQ,SAAS,cAAc,QAAQ,MAAM;GACjD,OAAO,SAAS,MAAM,GAAG;EAC3B;EACA,MAAM,KAAK;GACT,OAAO,SAAS,WAAW,GAAG;EAChC;EACA,IAAI,QAAQ;GACV,OAAO,SAAS;EAClB;EACA,IAAI,SAAS;GACX,OAAO,WAAW;EACpB;EACA,IAAI,UAAU;GACZ,OAAO;EACT;EACA,IAAI,aAAa;GACf,OAAO;EACT;CACF;AACF;AAEA,SAAS,YAAY,WAA2B,OAA0B;CACxE,OAAO,sBAAsB;EAC3B,MAAM;EACN,MAAM;EACN,QAAQ;EACR,SAAS,eAAe,UAAU,KAAK,oBAAoB,UAAU;EACrE,KAAK;EACL,KAAK;EACL,SAAS;GACP,MAAM,UAAU;GAChB,UAAU,UAAU;GACpB,OAAO,UAAU;GACjB,SAAS,MAAM,MAAM,OAAO;GAC5B,WAAW,MAAM;EACnB;CACF,CAAC;AACH;;;;;AAyBA,SAAgB,kBAAkB,SAAyC;CACzE,MAAM,QAA0B,CAAC;CACjC,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,YAAY,QAAQ,WAAW,MAAM,CAAC;CACnD;CACA,IAAI,QAAQ,eAAe,WAAW;EACpC,MAAM,KAAK,YAAY,QAAQ,YAAY,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,cAAc,WAAW;EACnC,MAAM,KAAK,aAAa,QAAQ,WAAW,MAAM,CAAC;CACpD;CACA,IAAI,QAAQ,iBAAiB,WAAW;EACtC,MAAM,KAAK,aAAa,QAAQ,cAAc,MAAM,CAAC;CACvD;CACA,IAAI,QAAQ,kBAAkB,WAAW;EACvC,MAAM,KAAK,YAAY,QAAQ,eAAe,MAAM,CAAC;CACvD;CACA,OAAO,iBAAiB;EACtB;EACA,QAAQ,QAAQ;EAChB,KAAK,QAAQ;CACf,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"guard.js","names":[],"sources":["../src/guard.ts"],"sourcesContent":["/**\n * GenAI guard / budget runtime — an in-process kill-switch for agent runs.\n *\n * Most tracing tells you what an agent _did_, after the fact. A guard runs\n * _during_ the run: you feed it each step (an LLM call, a tool call, a\n * delegation), it accumulates cost / tokens / loop state, and evaluates a set\n * of rules. When a rule crosses its threshold the guard either records a\n * warning and lets the run continue, or stops the run — aborting an\n * {@link AbortSignal} and (by default) throwing a structured error so the agent\n * loop unwinds. No prompt, no retry, no runaway bill.\n *\n * This is the inline, OpenTelemetry-native analogue of a `watch` kill-switch:\n * cost ceilings, token ceilings, max tool calls, wall-clock timeouts, and\n * spin-loop / error-loop detection — all pure, deterministic logic with no LLM\n * in the loop.\n *\n * @example Budget ceiling that halts a runaway agent\n * ```typescript\n * import { createGenAiBudget } from 'autotel-genai/guard';\n * import { estimateLLMCost } from 'autotel-genai/cost';\n *\n * const budget = createGenAiBudget({ maxCostUsd: 5, warnAtUsd: 4 });\n *\n * for (const task of tasks) {\n * if (budget.stopped) break;\n * const res = await model.chat(task);\n * budget.record(\n * {\n * kind: 'llm',\n * usage: {\n * costUsd: estimateLLMCost('gpt-4o', {\n * inputTokens: res.usage.input,\n * outputTokens: res.usage.output,\n * }),\n * },\n * },\n * ctx, // optional TraceContext — records gen_ai.guard.* telemetry\n * ); // throws GEN_AI_GUARD_STOP once total cost > $5\n * }\n * ```\n *\n * @example Loop detection from a shorthand rule string\n * ```typescript\n * import { createGenAiGuard, parseGuardRules } from 'autotel-genai/guard';\n *\n * const guard = createGenAiGuard({\n * rules: parseGuardRules('budget:$2,loop:3/10,max-tools:50,timeout:5m'),\n * });\n *\n * guard.record({ kind: 'tool', name: 'search', signature: JSON.stringify(args) });\n * ```\n */\n\nimport { createStructuredError, type TraceContext } from 'autotel';\nimport { securityEvent } from 'autotel-audit';\nimport { GEN_AI, GEN_AI_GUARD_EVENT } from './semconv.js';\n\n/** What a rule does when it crosses its threshold. */\nexport type GuardAction = 'warn' | 'stop';\n\n/** Usage contribution for a single step. */\nexport interface GuardUsage {\n /**\n * Estimated USD cost for this step. Pair with\n * {@link import('./cost.js').estimateLLMCost} to compute it from token usage.\n */\n costUsd?: number;\n /** Input (prompt) tokens for this step. */\n inputTokens?: number;\n /** Output (completion) tokens for this step. */\n outputTokens?: number;\n}\n\n/** A single supervised step: an LLM call, a tool call, a delegation, … */\nexport interface GenAiGuardStep {\n /**\n * Step kind. `tool` increments the tool-call counter; any value is allowed.\n */\n kind?: 'llm' | 'tool' | 'agent' | 'workflow' | (string & {});\n /** Operation or tool name — used together with {@link signature} for loops. */\n name?: string;\n /**\n * Stable signature of the call inputs (e.g. `JSON.stringify(args)`). Two\n * steps with the same `name` + `signature` count as identical for spin-loop\n * detection. Hash or truncate it yourself if the raw args are large.\n */\n signature?: string;\n /** Whether this step failed. Drives error-loop detection. */\n error?: boolean;\n /** Cost / token contribution to the running totals. */\n usage?: GuardUsage;\n}\n\n/** Read-only snapshot of the accumulated session state. */\nexport interface GuardState {\n /** Epoch ms when the guard was created. */\n readonly startedAt: number;\n /** Epoch ms at evaluation time. */\n readonly now: number;\n /** Wall-clock ms since {@link startedAt}. */\n readonly elapsedMs: number;\n /** Accumulated estimated cost in USD. */\n readonly costUsd: number;\n /** Accumulated input tokens. */\n readonly inputTokens: number;\n /** Accumulated output tokens. */\n readonly outputTokens: number;\n /** Total steps recorded. */\n readonly stepCount: number;\n /** Steps with `kind === 'tool'`. */\n readonly toolCallCount: number;\n /** Steps with `error === true`. */\n readonly errorCount: number;\n /** Bounded recent history (newest last) for loop detection. */\n readonly history: ReadonlyArray<{ key: string | undefined; error: boolean }>;\n}\n\n/** A fired rule. */\nexport interface GuardViolation {\n /** Rule name, e.g. `cost-ceiling:$5`. */\n rule: string;\n /** Whether the run continued (`warn`) or was halted (`stop`). */\n action: GuardAction;\n /** Human-readable explanation. */\n message: string;\n /** The observed value that crossed the threshold. */\n observed: number;\n /** The configured threshold. */\n limit: number;\n}\n\n/** A guard rule: inspect the state after a step and optionally fire. */\nexport interface GenAiGuardRule {\n /** Stable identifier, surfaced on {@link GuardViolation.rule}. */\n name: string;\n /** Default {@link GuardAction} when the rule fires. Defaults to `stop`. */\n action?: GuardAction;\n /**\n * Evaluate against the post-step state and the step just recorded (absent on\n * a bare {@link GenAiGuard.check}). Return a partial violation to fire, or\n * `undefined` to pass.\n */\n evaluate: (\n state: GuardState,\n step: GenAiGuardStep | undefined,\n ) => { message: string; observed: number; limit: number } | undefined;\n}\n\n/** Minimal telemetry sink — the subset of {@link TraceContext} the guard uses. */\nexport type GuardSink = Pick<TraceContext, 'setAttributes' | 'track'>;\n\n/** What happens when a `stop` rule fires. */\nexport type GuardStopBehavior =\n /** Abort the signal and throw a structured error (default). */\n | 'throw'\n /** Abort the signal but do not throw — inspect `guard.stopped` yourself. */\n | 'abort'\n /** Record the violation only; neither abort nor throw. */\n | 'silent';\n\nexport interface GenAiGuardOptions {\n /** Rules to evaluate after each step. */\n rules: GenAiGuardRule[];\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /**\n * Max recent steps retained for loop detection. Defaults to 256; raise it if\n * a spin-loop rule uses a larger window.\n */\n historyLimit?: number;\n /** Clock injection point, for tests. Defaults to {@link Date.now}. */\n now?: () => number;\n}\n\n/** A live guard supervising an agent run. */\nexport interface GenAiGuard {\n /**\n * Record a step, accumulate its usage, and evaluate every rule. Returns the\n * violations that fired _this call_ (each rule fires at most once). When a\n * `stop` rule fires, aborts {@link signal} and — unless `onStop` is `abort` /\n * `silent` — throws a structured `GEN_AI_GUARD_STOP` error.\n */\n record(step: GenAiGuardStep, ctx?: GuardSink): GuardViolation[];\n /**\n * Re-evaluate the rules without recording a step. Useful for time-based\n * rules (e.g. a timeout) between LLM calls.\n */\n check(ctx?: GuardSink): GuardViolation[];\n /** Current accumulated state. */\n readonly state: GuardState;\n /** Fires once a `stop` rule has crossed its threshold. */\n readonly signal: AbortSignal;\n /** `true` after a `stop` rule has fired. */\n readonly stopped: boolean;\n /** Every violation fired so far, in order. */\n readonly violations: ReadonlyArray<GuardViolation>;\n}\n\n// --- Rule factories --------------------------------------------------------\n\nfunction round(n: number): number {\n return Math.round(n * 1e6) / 1e6;\n}\n\n/** Stop / warn when accumulated cost exceeds `limitUsd`. */\nexport function costCeiling(\n limitUsd: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `cost-ceiling:$${limitUsd}`,\n action,\n evaluate: (s) =>\n s.costUsd > limitUsd\n ? {\n message: `session cost $${round(s.costUsd)} exceeds $${limitUsd}`,\n observed: round(s.costUsd),\n limit: limitUsd,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when accumulated input + output tokens exceed `limit`. */\nexport function tokenCeiling(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `token-ceiling:${limit}`,\n action,\n evaluate: (s) => {\n const total = s.inputTokens + s.outputTokens;\n return total > limit\n ? {\n message: `session tokens ${total} exceed ${limit}`,\n observed: total,\n limit,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn when the number of tool calls exceeds `limit`. */\nexport function maxToolCalls(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-tool-calls:${limit}`,\n action,\n evaluate: (s) =>\n s.toolCallCount > limit\n ? {\n message: `tool calls ${s.toolCallCount} exceed ${limit}`,\n observed: s.toolCallCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when the total number of steps exceeds `limit`. */\nexport function maxSteps(\n limit: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-steps:${limit}`,\n action,\n evaluate: (s) =>\n s.stepCount > limit\n ? {\n message: `steps ${s.stepCount} exceed ${limit}`,\n observed: s.stepCount,\n limit,\n }\n : undefined,\n };\n}\n\n/** Stop / warn when wall-clock time since start exceeds `limitMs`. */\nexport function maxDuration(\n limitMs: number,\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n return {\n name: `max-duration:${limitMs}ms`,\n action,\n evaluate: (s) =>\n s.elapsedMs > limitMs\n ? {\n message: `elapsed ${s.elapsedMs}ms exceeds ${limitMs}ms`,\n observed: s.elapsedMs,\n limit: limitMs,\n }\n : undefined,\n };\n}\n\n/**\n * Stop / warn on a spin loop: the same step (`name` + `signature`) repeated\n * `count` or more times within the last `window` steps. Steps without a `name`\n * are ignored (no identity to compare).\n */\nexport function spinLoop(\n options: { count: number; window: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count, window } = options;\n return {\n name: `spin-loop:${count}/${window}`,\n action,\n evaluate: (s, step) => {\n const key = stepKey(step);\n if (key === undefined) return undefined;\n const recent = s.history.slice(-window);\n let occurrences = 0;\n for (const h of recent) if (h.key === key) occurrences++;\n return occurrences >= count\n ? {\n message: `step \"${step?.name}\" repeated ${occurrences}× in last ${window}`,\n observed: occurrences,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/** Stop / warn on `count` or more consecutive failing steps. */\nexport function errorLoop(\n options: { count: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const { count } = options;\n return {\n name: `error-loop:${count}`,\n action,\n evaluate: (s) => {\n let streak = 0;\n for (let i = s.history.length - 1; i >= 0; i--) {\n if (s.history[i].error) streak++;\n else break;\n }\n return streak >= count\n ? {\n message: `${streak} consecutive errors`,\n observed: streak,\n limit: count,\n }\n : undefined;\n },\n };\n}\n\n/**\n * Approximate context-window sizes (in input tokens) for common models.\n * Matched exactly first, then by longest key prefix. Override via the `limit`\n * option on {@link contextBudget}.\n */\nexport const CONTEXT_LIMITS: Record<string, number> = {\n 'gpt-4o': 128_000,\n 'gpt-4.1': 1_047_576,\n 'gpt-4': 8192,\n 'o3-mini': 200_000,\n 'claude-opus-4': 200_000,\n 'claude-sonnet-4': 200_000,\n 'claude-3-5-sonnet': 200_000,\n 'claude-3-5-haiku': 200_000,\n 'claude-3': 200_000,\n 'gemini-1.5-pro': 2_097_152,\n 'gemini-1.5-flash': 1_048_576,\n 'gemini-2.0-flash': 1_048_576,\n};\n\nfunction resolveContextLimit(model: string): number | undefined {\n const exact = CONTEXT_LIMITS[model];\n if (exact) return exact;\n let best: number | undefined;\n let bestLength = 0;\n for (const key of Object.keys(CONTEXT_LIMITS)) {\n if (model.startsWith(key) && key.length > bestLength) {\n best = CONTEXT_LIMITS[key];\n bestLength = key.length;\n }\n }\n return best;\n}\n\n/**\n * Stop / warn when cumulative input tokens reach `threshold` (default 0.9) of\n * the model's context window. Provide an explicit `limit`, or a `model` to look\n * one up from {@link CONTEXT_LIMITS}.\n */\nexport function contextBudget(\n options: { model?: string; limit?: number; threshold?: number },\n action: GuardAction = 'stop',\n): GenAiGuardRule {\n const threshold = options.threshold ?? 0.9;\n const limit =\n options.limit ?? (options.model ? resolveContextLimit(options.model) : undefined);\n return {\n name: `context-budget:${Math.round(threshold * 100)}%`,\n action,\n evaluate: (s) => {\n if (!limit) return undefined;\n const ratio = s.inputTokens / limit;\n return ratio >= threshold\n ? {\n message: `context ${Math.round(ratio * 100)}% full (${s.inputTokens}/${limit})`,\n observed: round(ratio),\n limit: threshold,\n }\n : undefined;\n },\n };\n}\n\nfunction stepKey(step: GenAiGuardStep | undefined): string | undefined {\n if (!step || step.name === undefined) return undefined;\n return `${step.name}\u0000${step.signature ?? ''}`;\n}\n\n// --- Shorthand rule parser -------------------------------------------------\n\nfunction parseScaledNumber(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([kmb])?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid number: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const scale = { k: 1e3, m: 1e6, b: 1e9 }[m[2]?.toLowerCase() ?? ''] ?? 1;\n return value * scale;\n}\n\nfunction parseDurationMs(raw: string): number {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/i.exec(raw.trim());\n if (!m) throw new Error(`invalid duration: \"${raw}\"`);\n const value = Number.parseFloat(m[1]);\n const unit = (m[2] ?? 's').toLowerCase();\n const scale = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 }[unit] ?? 1000;\n return value * scale;\n}\n\n/**\n * Parse a comma-separated shorthand rule string into {@link GenAiGuardRule}s.\n * All parsed rules default to the `stop` action — pass `defaultAction: 'warn'`\n * to warn instead, or build typed rules directly for per-rule actions.\n *\n * Supported tokens:\n * - `budget:$5` / `cost:$5` — {@link costCeiling}\n * - `tokens:100k` — {@link tokenCeiling} (`k`/`m`/`b` suffixes)\n * - `loop:3/10` — {@link spinLoop} (count / window)\n * - `errors:3` — {@link errorLoop}\n * - `max-tools:50` — {@link maxToolCalls}\n * - `max-steps:100` — {@link maxSteps}\n * - `timeout:30m` — {@link maxDuration} (`ms`/`s`/`m`/`h`, default seconds)\n * - `context:0.9` / `context:0.9@gpt-4o` — {@link contextBudget}\n */\nexport function parseGuardRules(\n shorthand: string,\n options?: { defaultAction?: GuardAction },\n): GenAiGuardRule[] {\n const action = options?.defaultAction ?? 'stop';\n const rules: GenAiGuardRule[] = [];\n for (const token of shorthand.split(',')) {\n const trimmed = token.trim();\n if (!trimmed) continue;\n const sep = trimmed.indexOf(':');\n if (sep === -1) throw new Error(`invalid guard rule: \"${trimmed}\"`);\n const key = trimmed.slice(0, sep).trim().toLowerCase();\n const value = trimmed.slice(sep + 1).trim();\n\n switch (key) {\n case 'budget':\n case 'cost': {\n rules.push(costCeiling(parseScaledNumber(value.replace(/^\\$/, '')), action));\n break;\n }\n case 'tokens': {\n rules.push(tokenCeiling(parseScaledNumber(value), action));\n break;\n }\n case 'loop': {\n const [count, window] = value.split('/');\n rules.push(\n spinLoop(\n { count: parseScaledNumber(count), window: parseScaledNumber(window) },\n action,\n ),\n );\n break;\n }\n case 'errors': {\n rules.push(errorLoop({ count: parseScaledNumber(value) }, action));\n break;\n }\n case 'max-tools': {\n rules.push(maxToolCalls(parseScaledNumber(value), action));\n break;\n }\n case 'max-steps': {\n rules.push(maxSteps(parseScaledNumber(value), action));\n break;\n }\n case 'timeout': {\n rules.push(maxDuration(parseDurationMs(value), action));\n break;\n }\n case 'context': {\n const [thr, model] = value.split('@');\n rules.push(\n contextBudget(\n { threshold: Number.parseFloat(thr), model: model?.trim() || undefined },\n action,\n ),\n );\n break;\n }\n default: {\n throw new Error(`unknown guard rule: \"${key}\"`);\n }\n }\n }\n return rules;\n}\n\n// --- Guard implementation --------------------------------------------------\n\nfunction recordTelemetry(\n ctx: GuardSink,\n state: GuardState,\n newViolations: GuardViolation[],\n stopped: boolean,\n): void {\n ctx.setAttributes({\n [GEN_AI.SESSION_COST_USD]: round(state.costUsd),\n [GEN_AI.SESSION_INPUT_TOKENS]: state.inputTokens,\n [GEN_AI.SESSION_OUTPUT_TOKENS]: state.outputTokens,\n [GEN_AI.SESSION_STEP_COUNT]: state.stepCount,\n [GEN_AI.SESSION_TOOL_CALL_COUNT]: state.toolCallCount,\n [GEN_AI.SESSION_ERROR_COUNT]: state.errorCount,\n });\n if (newViolations.length === 0) return;\n if (stopped) ctx.setAttributes({ [GEN_AI.GUARD_STOPPED]: true });\n for (const violation of newViolations) {\n ctx.track(\n violation.action === 'stop'\n ? GEN_AI_GUARD_EVENT.STOP\n : GEN_AI_GUARD_EVENT.WARNING,\n {\n [GEN_AI.GUARD_RULE]: violation.rule,\n [GEN_AI.GUARD_ACTION]: violation.action,\n [GEN_AI.GUARD_MESSAGE]: violation.message,\n [GEN_AI.GUARD_OBSERVED]: violation.observed,\n [GEN_AI.GUARD_LIMIT]: violation.limit,\n },\n );\n if (violation.action === 'stop') {\n securityEvent(\n {\n name: 'llm.guard.triggered',\n category: 'llm',\n outcome: 'blocked',\n severity: 'error',\n reason: violation.rule,\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n },\n { onMissingContext: 'warn' },\n );\n }\n }\n}\n\n/**\n * Create a guard that supervises an in-process agent run against `rules`.\n */\nexport function createGenAiGuard(options: GenAiGuardOptions): GenAiGuard {\n const { rules } = options;\n const onStop = options.onStop ?? 'throw';\n const historyLimit = options.historyLimit ?? 256;\n const now = options.now ?? Date.now;\n const startedAt = now();\n\n const controller = new AbortController();\n const history: { key: string | undefined; error: boolean }[] = [];\n const fired = new Set<string>();\n const violations: GuardViolation[] = [];\n\n let costUsd = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let stepCount = 0;\n let toolCallCount = 0;\n let errorCount = 0;\n let stopped = false;\n\n function snapshot(): GuardState {\n const at = now();\n return {\n startedAt,\n now: at,\n elapsedMs: at - startedAt,\n costUsd,\n inputTokens,\n outputTokens,\n stepCount,\n toolCallCount,\n errorCount,\n history,\n };\n }\n\n function evaluate(\n step: GenAiGuardStep | undefined,\n ctx: GuardSink | undefined,\n ): GuardViolation[] {\n const state = snapshot();\n const newViolations: GuardViolation[] = [];\n\n for (const rule of rules) {\n if (fired.has(rule.name)) continue;\n const hit = rule.evaluate(state, step);\n if (!hit) continue;\n fired.add(rule.name);\n const violation: GuardViolation = {\n rule: rule.name,\n action: rule.action ?? 'stop',\n message: hit.message,\n observed: hit.observed,\n limit: hit.limit,\n };\n violations.push(violation);\n newViolations.push(violation);\n }\n\n const stopViolation = newViolations.find((v) => v.action === 'stop');\n if (stopViolation && !stopped) {\n stopped = true;\n if (onStop !== 'silent') controller.abort(toStopError(stopViolation, state));\n }\n\n if (ctx) recordTelemetry(ctx, state, newViolations, stopped);\n\n if (stopViolation && onStop === 'throw') {\n throw toStopError(stopViolation, snapshot());\n }\n return newViolations;\n }\n\n return {\n record(step, ctx) {\n stepCount++;\n if (step.kind === 'tool') toolCallCount++;\n if (step.error) errorCount++;\n if (step.usage) {\n costUsd += step.usage.costUsd ?? 0;\n inputTokens += step.usage.inputTokens ?? 0;\n outputTokens += step.usage.outputTokens ?? 0;\n }\n history.push({ key: stepKey(step), error: step.error === true });\n if (history.length > historyLimit) history.shift();\n return evaluate(step, ctx);\n },\n check(ctx) {\n return evaluate(undefined, ctx);\n },\n get state() {\n return snapshot();\n },\n get signal() {\n return controller.signal;\n },\n get stopped() {\n return stopped;\n },\n get violations() {\n return violations;\n },\n };\n}\n\nfunction toStopError(violation: GuardViolation, state: GuardState): Error {\n return createStructuredError({\n name: 'GenAiGuardStop',\n code: 'GEN_AI_GUARD_STOP',\n status: 429,\n message: `Guard rule \"${violation.rule}\" halted the run: ${violation.message}`,\n why: 'A stop-action guard rule crossed its threshold during the agent run.',\n fix: 'Raise the limit, fix the loop, or handle GEN_AI_GUARD_STOP to wind the run down cleanly.',\n details: {\n rule: violation.rule,\n observed: violation.observed,\n limit: violation.limit,\n costUsd: round(state.costUsd),\n stepCount: state.stepCount,\n },\n });\n}\n\n// --- Budget preset ---------------------------------------------------------\n\nexport interface GenAiBudgetOptions {\n /** Hard cost ceiling in USD — a `stop` rule. */\n maxCostUsd?: number;\n /** Soft cost threshold in USD — a `warn` rule. */\n warnAtUsd?: number;\n /** Hard token ceiling (input + output) — a `stop` rule. */\n maxTokens?: number;\n /** Hard tool-call ceiling — a `stop` rule. */\n maxToolCalls?: number;\n /** Hard wall-clock ceiling in ms — a `stop` rule. */\n maxDurationMs?: number;\n /** What to do when a `stop` rule fires. Defaults to `throw`. */\n onStop?: GuardStopBehavior;\n /** Clock injection point, for tests. */\n now?: () => number;\n}\n\n/**\n * Convenience preset that wires the common cost / token / tool-call / duration\n * ceilings into a {@link createGenAiGuard}. Returns the same {@link GenAiGuard}.\n */\nexport function createGenAiBudget(options: GenAiBudgetOptions): GenAiGuard {\n const rules: GenAiGuardRule[] = [];\n if (options.warnAtUsd !== undefined) {\n rules.push(costCeiling(options.warnAtUsd, 'warn'));\n }\n if (options.maxCostUsd !== undefined) {\n rules.push(costCeiling(options.maxCostUsd, 'stop'));\n }\n if (options.maxTokens !== undefined) {\n rules.push(tokenCeiling(options.maxTokens, 'stop'));\n }\n if (options.maxToolCalls !== undefined) {\n rules.push(maxToolCalls(options.maxToolCalls, 'stop'));\n }\n if (options.maxDurationMs !== undefined) {\n rules.push(maxDuration(options.maxDurationMs, 'stop'));\n }\n return createGenAiGuard({\n rules,\n onStop: options.onStop,\n now: options.now,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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