@directive-run/ai 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/anthropic.cjs +1 -1
  2. package/dist/anthropic.d.cts +1 -1
  3. package/dist/anthropic.d.ts +1 -1
  4. package/dist/anthropic.js +1 -1
  5. package/dist/anthropic.js.map +1 -1
  6. package/dist/{chunk-XV2QSBBE.cjs → chunk-2TD4ZSGZ.cjs} +7 -7
  7. package/dist/{chunk-XV2QSBBE.cjs.map → chunk-2TD4ZSGZ.cjs.map} +1 -1
  8. package/dist/chunk-3WO4MWJM.cjs +3 -0
  9. package/dist/chunk-3WO4MWJM.cjs.map +1 -0
  10. package/dist/chunk-5JQ2A3JK.js +2 -0
  11. package/dist/chunk-5JQ2A3JK.js.map +1 -0
  12. package/dist/chunk-A22KLB23.cjs +67 -0
  13. package/dist/chunk-A22KLB23.cjs.map +1 -0
  14. package/dist/chunk-A5K77UDX.cjs +4 -0
  15. package/dist/chunk-A5K77UDX.cjs.map +1 -0
  16. package/dist/chunk-DN5NAJM6.js +6 -0
  17. package/dist/chunk-DN5NAJM6.js.map +1 -0
  18. package/dist/chunk-FABDFT74.cjs +6 -0
  19. package/dist/chunk-FABDFT74.cjs.map +1 -0
  20. package/dist/chunk-FBT73WFY.js +2 -0
  21. package/dist/chunk-FBT73WFY.js.map +1 -0
  22. package/dist/chunk-FFRWQNK7.cjs +7 -0
  23. package/dist/chunk-FFRWQNK7.cjs.map +1 -0
  24. package/dist/chunk-IR3IHBVQ.cjs +2 -0
  25. package/dist/chunk-IR3IHBVQ.cjs.map +1 -0
  26. package/dist/chunk-IUGSMTBE.js +16 -0
  27. package/dist/{chunk-Q3PQLWBR.js.map → chunk-IUGSMTBE.js.map} +1 -1
  28. package/dist/chunk-J2Q5KKPN.js +37 -0
  29. package/dist/chunk-J2Q5KKPN.js.map +1 -0
  30. package/dist/chunk-K64WKZ22.cjs +2 -0
  31. package/dist/chunk-K64WKZ22.cjs.map +1 -0
  32. package/dist/chunk-LKY4K5TV.cjs +11 -0
  33. package/dist/chunk-LKY4K5TV.cjs.map +1 -0
  34. package/dist/chunk-LXUMJKGJ.js +67 -0
  35. package/dist/chunk-LXUMJKGJ.js.map +1 -0
  36. package/dist/chunk-NNAQ4ZH2.js +11 -0
  37. package/dist/chunk-NNAQ4ZH2.js.map +1 -0
  38. package/dist/chunk-PD772MSE.cjs +30 -0
  39. package/dist/chunk-PD772MSE.cjs.map +1 -0
  40. package/dist/chunk-POBEEJR6.js +30 -0
  41. package/dist/chunk-POBEEJR6.js.map +1 -0
  42. package/dist/chunk-QRXWLD6H.js +4 -0
  43. package/dist/chunk-QRXWLD6H.js.map +1 -0
  44. package/dist/chunk-UR4ZGO7V.js +7 -0
  45. package/dist/chunk-UR4ZGO7V.js.map +1 -0
  46. package/dist/chunk-UR5BMWEN.js +2 -0
  47. package/dist/chunk-UR5BMWEN.js.map +1 -0
  48. package/dist/chunk-WOFIBIPW.cjs +2 -0
  49. package/dist/chunk-WOFIBIPW.cjs.map +1 -0
  50. package/dist/chunk-XN5LUOVS.cjs +37 -0
  51. package/dist/chunk-XN5LUOVS.cjs.map +1 -0
  52. package/dist/chunk-ZFLHWJ56.js +3 -0
  53. package/dist/chunk-ZFLHWJ56.js.map +1 -0
  54. package/dist/debug-timeline-DpnRMnLU.d.cts +87 -0
  55. package/dist/debug-timeline-L13P-U2I.d.ts +87 -0
  56. package/dist/devtools.cjs +2 -0
  57. package/dist/devtools.cjs.map +1 -0
  58. package/dist/devtools.d.cts +354 -0
  59. package/dist/devtools.d.ts +354 -0
  60. package/dist/devtools.js +2 -0
  61. package/dist/devtools.js.map +1 -0
  62. package/dist/evals.cjs +2 -0
  63. package/dist/evals.cjs.map +1 -0
  64. package/dist/evals.d.cts +361 -0
  65. package/dist/evals.d.ts +361 -0
  66. package/dist/evals.js +2 -0
  67. package/dist/evals.js.map +1 -0
  68. package/dist/gemini.cjs +1 -1
  69. package/dist/gemini.d.cts +1 -1
  70. package/dist/gemini.d.ts +1 -1
  71. package/dist/gemini.js +1 -1
  72. package/dist/gemini.js.map +1 -1
  73. package/dist/guardrails.cjs +2 -0
  74. package/dist/guardrails.cjs.map +1 -0
  75. package/dist/guardrails.d.cts +618 -0
  76. package/dist/guardrails.d.ts +618 -0
  77. package/dist/guardrails.js +2 -0
  78. package/dist/guardrails.js.map +1 -0
  79. package/dist/health-monitor-C6xoXrQz.d.cts +55 -0
  80. package/dist/health-monitor-qL9RNMH3.d.ts +55 -0
  81. package/dist/index.cjs +21 -99
  82. package/dist/index.cjs.map +1 -1
  83. package/dist/index.d.cts +1202 -4542
  84. package/dist/index.d.ts +1202 -4542
  85. package/dist/index.js +21 -99
  86. package/dist/index.js.map +1 -1
  87. package/dist/mcp.cjs +2 -0
  88. package/dist/mcp.cjs.map +1 -0
  89. package/dist/mcp.d.cts +450 -0
  90. package/dist/mcp.d.ts +450 -0
  91. package/dist/mcp.js +2 -0
  92. package/dist/mcp.js.map +1 -0
  93. package/dist/multi-agent-orchestrator-QWWQKKGX.js +2 -0
  94. package/dist/{multi-agent-orchestrator-4PXNYRHB.js.map → multi-agent-orchestrator-QWWQKKGX.js.map} +1 -1
  95. package/dist/multi-agent-orchestrator-Y5U4JCFO.cjs +2 -0
  96. package/dist/{multi-agent-orchestrator-KFGTEGE5.cjs.map → multi-agent-orchestrator-Y5U4JCFO.cjs.map} +1 -1
  97. package/dist/multi-agent.cjs +2 -0
  98. package/dist/multi-agent.cjs.map +1 -0
  99. package/dist/multi-agent.d.cts +1429 -0
  100. package/dist/multi-agent.d.ts +1429 -0
  101. package/dist/multi-agent.js +2 -0
  102. package/dist/multi-agent.js.map +1 -0
  103. package/dist/ollama.cjs +1 -1
  104. package/dist/ollama.d.cts +1 -1
  105. package/dist/ollama.d.ts +1 -1
  106. package/dist/ollama.js +2 -2
  107. package/dist/ollama.js.map +1 -1
  108. package/dist/openai.cjs +1 -1
  109. package/dist/openai.d.cts +2 -2
  110. package/dist/openai.d.ts +2 -2
  111. package/dist/openai.js +1 -1
  112. package/dist/openai.js.map +1 -1
  113. package/dist/{orchestrator-types-CTfIKk0W.d.ts → orchestrator-types-DGBhL6mc.d.ts} +5 -138
  114. package/dist/{orchestrator-types-Bh8r3_Sq.d.cts → orchestrator-types-DeIMRLR7.d.cts} +5 -138
  115. package/dist/predicate.cjs +2 -0
  116. package/dist/predicate.cjs.map +1 -0
  117. package/dist/predicate.d.cts +371 -0
  118. package/dist/predicate.d.ts +371 -0
  119. package/dist/predicate.js +2 -0
  120. package/dist/predicate.js.map +1 -0
  121. package/dist/{semantic-cache-nBpQqILc.d.cts → semantic-cache-DM7ev7NQ.d.cts} +1 -1
  122. package/dist/{semantic-cache-nBpQqILc.d.ts → semantic-cache-DM7ev7NQ.d.ts} +1 -1
  123. package/dist/testing.cjs +1 -1
  124. package/dist/testing.cjs.map +1 -1
  125. package/dist/testing.d.cts +4 -2
  126. package/dist/testing.d.ts +4 -2
  127. package/dist/testing.js +1 -1
  128. package/dist/testing.js.map +1 -1
  129. package/dist/{types-CRmwFnVk.d.cts → types-DJ09LjZX.d.cts} +1 -1
  130. package/dist/{types-CRmwFnVk.d.ts → types-DJ09LjZX.d.ts} +1 -1
  131. package/package.json +32 -2
  132. package/dist/chunk-Q3PQLWBR.js +0 -16
  133. package/dist/chunk-RW4R3O5P.js +0 -72
  134. package/dist/chunk-RW4R3O5P.js.map +0 -1
  135. package/dist/chunk-W6MVJKWN.cjs +0 -3
  136. package/dist/chunk-W6MVJKWN.cjs.map +0 -1
  137. package/dist/chunk-W6WZBQER.js +0 -3
  138. package/dist/chunk-W6WZBQER.js.map +0 -1
  139. package/dist/chunk-X3VQ5F7D.cjs +0 -72
  140. package/dist/chunk-X3VQ5F7D.cjs.map +0 -1
  141. package/dist/multi-agent-orchestrator-4PXNYRHB.js +0 -2
  142. package/dist/multi-agent-orchestrator-KFGTEGE5.cjs +0 -2
@@ -0,0 +1,361 @@
1
+ import { D as DebugTimeline } from './debug-timeline-L13P-U2I.js';
2
+ import { q as RunResult, b as AgentLike, c as AgentRunner, R as RunOptions } from './types-DJ09LjZX.js';
3
+ import '@directive-run/core';
4
+
5
+ /**
6
+ * Evaluation Framework — Constraint-driven agent evaluation.
7
+ *
8
+ * Define eval criteria as composable functions. Run agents against datasets
9
+ * and score their outputs across multiple dimensions. Results integrate with
10
+ * the debug timeline for DevTools visualization.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * const suite = createEvalSuite({
15
+ * criteria: {
16
+ * safe: evalSafety({ categories: ["pii"] }),
17
+ * costEfficient: evalCost({ maxTokensPerRun: 5000 }),
18
+ * fast: evalLatency({ maxMs: 3000 }),
19
+ * },
20
+ * agents: [researchAgent, writerAgent],
21
+ * runner: myRunner,
22
+ * dataset: [
23
+ * { id: "case-1", input: "What is AI?", expected: "explanation about AI" },
24
+ * ],
25
+ * });
26
+ *
27
+ * const results = await suite.run();
28
+ * // results.summary — pass/fail per criterion per agent
29
+ * // results.details — per-case breakdown
30
+ * ```
31
+ *
32
+ * @module
33
+ */
34
+
35
+ /** Single test case in the eval dataset */
36
+ interface EvalCase {
37
+ /** Unique identifier for tracking across runs */
38
+ id?: string;
39
+ /** Input to feed the agent */
40
+ input: string;
41
+ /** Expected output or reference answer (for comparison-based criteria) */
42
+ expected?: string;
43
+ /** Reference context for faithfulness evaluation */
44
+ context?: string;
45
+ /** Tags for filtering and grouping results */
46
+ tags?: string[];
47
+ /** Additional context passed to criteria */
48
+ metadata?: Record<string, unknown>;
49
+ }
50
+ /** Result of evaluating a single criterion on a single case */
51
+ interface EvalScore {
52
+ /** Score from 0.0 to 1.0 */
53
+ score: number;
54
+ /** Whether this score passes the criterion threshold */
55
+ passed: boolean;
56
+ /** Reason for the score */
57
+ reason?: string;
58
+ /** Duration of evaluation (ms) */
59
+ durationMs: number;
60
+ }
61
+ /** Context passed to eval criterion functions */
62
+ interface EvalContext {
63
+ /** The agent being evaluated */
64
+ agent: AgentLike;
65
+ /** The test case */
66
+ testCase: EvalCase;
67
+ /** The agent's run result */
68
+ result: RunResult<unknown>;
69
+ /** Duration of the agent run (ms) */
70
+ runDurationMs: number;
71
+ }
72
+ /** Eval criterion function — scores an agent's output */
73
+ type EvalCriterionFn = (context: EvalContext) => EvalScore | Promise<EvalScore>;
74
+ /** Named eval criterion */
75
+ interface EvalCriterion {
76
+ name: string;
77
+ fn: EvalCriterionFn;
78
+ /** Score threshold for passing. Default: 0.5 */
79
+ threshold?: number;
80
+ /** Weight for aggregation. Default: 1.0 */
81
+ weight?: number;
82
+ }
83
+ /** Per-case detail result */
84
+ interface EvalCaseResult {
85
+ /** Test case that was evaluated */
86
+ testCase: EvalCase;
87
+ /** Agent that was evaluated */
88
+ agentName: string;
89
+ /** Agent run result */
90
+ runResult: RunResult<unknown>;
91
+ /** Score per criterion */
92
+ scores: Record<string, EvalScore>;
93
+ /** Overall weighted score (0.0-1.0) */
94
+ overallScore: number;
95
+ /** Whether all criteria passed */
96
+ allPassed: boolean;
97
+ /** Agent run duration (ms) */
98
+ runDurationMs: number;
99
+ }
100
+ /** Per-agent summary */
101
+ interface EvalAgentSummary {
102
+ agentName: string;
103
+ /** Average score per criterion */
104
+ criterionAverages: Record<string, number>;
105
+ /** Pass rate per criterion (0.0-1.0) */
106
+ criterionPassRates: Record<string, number>;
107
+ /** Overall weighted average score */
108
+ overallScore: number;
109
+ /** Overall pass rate */
110
+ passRate: number;
111
+ /** Total tokens consumed */
112
+ totalTokens: number;
113
+ /** Average latency per run (ms) */
114
+ avgLatencyMs: number;
115
+ /** Total cases evaluated */
116
+ totalCases: number;
117
+ /** Cases that passed all criteria */
118
+ passedCases: number;
119
+ }
120
+ /** Complete eval suite results */
121
+ interface EvalResults {
122
+ /** Summary per agent */
123
+ summary: Record<string, EvalAgentSummary>;
124
+ /** Detailed per-case results */
125
+ details: EvalCaseResult[];
126
+ /** Total duration (ms) */
127
+ durationMs: number;
128
+ /** Total tokens consumed across all agents and cases */
129
+ totalTokens: number;
130
+ /** Timestamp when the eval started */
131
+ startedAt: number;
132
+ /** Timestamp when the eval completed */
133
+ completedAt: number;
134
+ }
135
+ /** Configuration for createEvalSuite */
136
+ interface EvalSuiteConfig {
137
+ /** Named criteria to evaluate */
138
+ criteria: Record<string, EvalCriterionFn | EvalCriterion>;
139
+ /** Agents to evaluate */
140
+ agents: AgentLike[];
141
+ /** Agent runner function */
142
+ runner: AgentRunner;
143
+ /** Dataset of test cases */
144
+ dataset: EvalCase[];
145
+ /** Run options passed to the runner */
146
+ runOptions?: Omit<RunOptions, "signal">;
147
+ /** Maximum concurrent agent runs. Default: 5 */
148
+ concurrency?: number;
149
+ /** Optional debug timeline for recording eval events */
150
+ timeline?: DebugTimeline;
151
+ /** Callback fired on each case completion */
152
+ onCaseComplete?: (result: EvalCaseResult) => void;
153
+ /** Callback fired on each agent completion */
154
+ onAgentComplete?: (summary: EvalAgentSummary) => void;
155
+ /** Abort signal */
156
+ signal?: AbortSignal;
157
+ }
158
+ /** Eval suite instance */
159
+ interface EvalSuite {
160
+ /** Run the full evaluation */
161
+ run(): Promise<EvalResults>;
162
+ /** Run evaluation for a specific agent only */
163
+ runAgent(agentName: string): Promise<EvalAgentSummary>;
164
+ /** Get the list of agents being evaluated */
165
+ getAgents(): AgentLike[];
166
+ /** Get the list of criteria */
167
+ getCriteria(): string[];
168
+ /** Get the dataset */
169
+ getDataset(): EvalCase[];
170
+ }
171
+ /** Options for cost evaluation */
172
+ interface EvalCostOptions {
173
+ /** Maximum tokens per run */
174
+ maxTokensPerRun: number;
175
+ }
176
+ /**
177
+ * Evaluate cost efficiency — scores based on token usage relative to a budget.
178
+ *
179
+ * Score = 1.0 when tokens \<= maxTokensPerRun * 0.5,
180
+ * Score = 0.0 when tokens \>= maxTokensPerRun * 2.
181
+ * Linear interpolation between.
182
+ *
183
+ * @param options - Cost evaluation options including `maxTokensPerRun`.
184
+ * @returns An eval criterion that scores token usage against the budget.
185
+ */
186
+ declare function evalCost(options: EvalCostOptions): EvalCriterion;
187
+ /** Options for latency evaluation */
188
+ interface EvalLatencyOptions {
189
+ /** Maximum acceptable latency (ms) */
190
+ maxMs: number;
191
+ }
192
+ /**
193
+ * Evaluate latency — scores based on agent run duration.
194
+ *
195
+ * Score = 1.0 when duration \<= maxMs * 0.5,
196
+ * Score = 0.0 when duration \>= maxMs * 2.
197
+ * Linear interpolation between.
198
+ *
199
+ * @param options - Latency evaluation options including `maxMs`.
200
+ * @returns An eval criterion that scores run duration against the limit.
201
+ */
202
+ declare function evalLatency(options: EvalLatencyOptions): EvalCriterion;
203
+ /** Options for output length evaluation */
204
+ interface EvalOutputLengthOptions {
205
+ /** Minimum output length (chars) */
206
+ minLength?: number;
207
+ /** Maximum output length (chars) */
208
+ maxLength?: number;
209
+ }
210
+ /**
211
+ * Evaluate output length — ensures output is within an acceptable range.
212
+ */
213
+ declare function evalOutputLength(options: EvalOutputLengthOptions): EvalCriterion;
214
+ /** Options for safety evaluation */
215
+ interface EvalSafetyOptions {
216
+ /** Patterns to check for in output (overrides categories) */
217
+ blockedPatterns?: RegExp[];
218
+ /** Categories of content to check: "pii", "violence", "self_harm", "illegal" */
219
+ categories?: Array<"pii" | "violence" | "self_harm" | "illegal">;
220
+ }
221
+ /**
222
+ * Evaluate safety — checks output for blocked patterns or category-based content.
223
+ *
224
+ * When `categories` is provided, uses built-in pattern sets for each category.
225
+ * When `blockedPatterns` is provided, uses those directly (overrides categories).
226
+ * When neither is provided, defaults to all safety categories.
227
+ *
228
+ * Score = 1.0 when no blocked patterns found.
229
+ * Score = 0.0 when any blocked pattern matches.
230
+ */
231
+ declare function evalSafety(options?: EvalSafetyOptions): EvalCriterion;
232
+ /** Options for output structure evaluation */
233
+ interface EvalStructureOptions {
234
+ /** Expected output type */
235
+ type?: "json" | "string";
236
+ /** Required keys if type is "json" */
237
+ requiredKeys?: string[];
238
+ }
239
+ /**
240
+ * Evaluate output structure — checks that output matches an expected format.
241
+ */
242
+ declare function evalStructure(options: EvalStructureOptions): EvalCriterion;
243
+ /**
244
+ * Evaluate with a custom LLM judge — uses a runner to grade the output.
245
+ *
246
+ * The judge agent receives the input, output, and expected answer, and
247
+ * returns a JSON score.
248
+ */
249
+ interface EvalJudgeOptions {
250
+ /** Runner to use for the judge */
251
+ runner: AgentRunner;
252
+ /** Judge agent */
253
+ judge: AgentLike;
254
+ /** Custom grading prompt template. {{input}}, {{output}}, {{expected}} are replaced. */
255
+ promptTemplate?: string;
256
+ /** Optional abort signal */
257
+ signal?: AbortSignal;
258
+ /** Timeout for the judge call in ms. Default: 30_000 */
259
+ timeoutMs?: number;
260
+ }
261
+ /**
262
+ * Evaluate output quality by delegating to a judge agent that scores from 0.0 to 1.0.
263
+ *
264
+ * @param options - Judge evaluation options including `runner`, `judge` agent, and optional `promptTemplate`.
265
+ * @returns An eval criterion that runs a judge agent and returns its score.
266
+ */
267
+ declare function evalJudge(options: EvalJudgeOptions): EvalCriterion;
268
+ /**
269
+ * Evaluate exact or substring match against expected output.
270
+ */
271
+ interface EvalMatchOptions {
272
+ /** Match mode. Default: "contains" */
273
+ mode?: "exact" | "contains" | "regex";
274
+ /** Case-insensitive matching. Default: true */
275
+ caseInsensitive?: boolean;
276
+ }
277
+ /**
278
+ * Evaluate exact or substring match against expected output.
279
+ *
280
+ * @param options - Match evaluation options including `mode` and `caseInsensitive`.
281
+ * @returns An eval criterion that checks output against the expected value.
282
+ */
283
+ declare function evalMatch(options?: EvalMatchOptions): EvalCriterion;
284
+ /** Options for LLM-based semantic evaluation criteria */
285
+ interface EvalSemanticOptions {
286
+ /** Runner to use for the judge LLM */
287
+ runner: AgentRunner;
288
+ /** Judge agent (model to use for evaluation) */
289
+ judge: AgentLike;
290
+ /** Optional abort signal */
291
+ signal?: AbortSignal;
292
+ /** Timeout for the judge call in ms. Default: 30_000 */
293
+ timeoutMs?: number;
294
+ }
295
+ /**
296
+ * Evaluate faithfulness — whether the output is grounded in the provided context.
297
+ *
298
+ * Requires `context` field on the EvalCase. Uses an LLM judge internally
299
+ * to extract and verify claims against the reference context.
300
+ */
301
+ declare function evalFaithfulness(options: EvalSemanticOptions): EvalCriterion;
302
+ /**
303
+ * Evaluate relevance — whether the output directly addresses the input question.
304
+ *
305
+ * Uses an LLM judge to assess how well the agent's output answers
306
+ * the original question.
307
+ */
308
+ declare function evalRelevance(options: EvalSemanticOptions): EvalCriterion;
309
+ /**
310
+ * Evaluate coherence — whether the output is logically consistent and well-structured.
311
+ *
312
+ * Uses an LLM judge to assess the internal coherence, logical flow,
313
+ * and consistency of the output.
314
+ */
315
+ declare function evalCoherence(options: EvalSemanticOptions): EvalCriterion;
316
+ /**
317
+ * Create an evaluation suite for testing agents against a dataset.
318
+ *
319
+ * @example
320
+ * ```typescript
321
+ * const suite = createEvalSuite({
322
+ * criteria: {
323
+ * fast: evalLatency({ maxMs: 3000 }),
324
+ * cheap: evalCost({ maxTokensPerRun: 5000 }),
325
+ * },
326
+ * agents: [researchAgent, writerAgent],
327
+ * runner: myRunner,
328
+ * dataset: [{ input: "What is AI?" }],
329
+ * });
330
+ *
331
+ * const results = await suite.run();
332
+ * ```
333
+ */
334
+ declare function createEvalSuite(config: EvalSuiteConfig): EvalSuite;
335
+ /** Options for eval assertions in CI */
336
+ interface EvalAssertOptions {
337
+ /** Minimum weighted overall score required (0.0-1.0) */
338
+ minScore?: number;
339
+ /** Minimum pass rate required (0.0-1.0) */
340
+ minPassRate?: number;
341
+ /** Criteria that must achieve 100% pass rate */
342
+ failOn?: string[];
343
+ }
344
+ /**
345
+ * Assert eval results meet requirements — designed for CI pipelines.
346
+ *
347
+ * Throws an error with details if any assertion fails.
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * const results = await suite.run();
352
+ * evalAssert(results, {
353
+ * minScore: 0.8,
354
+ * minPassRate: 0.9,
355
+ * failOn: ["safety"],
356
+ * });
357
+ * ```
358
+ */
359
+ declare function evalAssert(results: EvalResults, options: EvalAssertOptions): void;
360
+
361
+ export { type EvalAgentSummary, type EvalAssertOptions, type EvalCase, type EvalCaseResult, type EvalContext, type EvalCostOptions, type EvalCriterion, type EvalCriterionFn, type EvalJudgeOptions, type EvalLatencyOptions, type EvalMatchOptions, type EvalOutputLengthOptions, type EvalResults, type EvalSafetyOptions, type EvalScore, type EvalSemanticOptions, type EvalStructureOptions, type EvalSuite, type EvalSuiteConfig, createEvalSuite, evalAssert, evalCoherence, evalCost, evalFaithfulness, evalJudge, evalLatency, evalMatch, evalOutputLength, evalRelevance, evalSafety, evalStructure };
package/dist/evals.js ADDED
@@ -0,0 +1,2 @@
1
+ export{k as createEvalSuite,l as evalAssert,j as evalCoherence,a as evalCost,h as evalFaithfulness,f as evalJudge,b as evalLatency,g as evalMatch,c as evalOutputLength,i as evalRelevance,d as evalSafety,e as evalStructure}from'./chunk-J2Q5KKPN.js';import'./chunk-ZFLHWJ56.js';//# sourceMappingURL=evals.js.map
2
+ //# sourceMappingURL=evals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"evals.js"}
package/dist/gemini.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunkW6MVJKWN_cjs=require('./chunk-W6MVJKWN.cjs');var $={"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.025,output:.1}};function v(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,timeoutMs:i,hooks:g,temperature:c,topP:l,stopSequences:n}=h;chunkW6MVJKWN_cjs.d(m),chunkKP3G32S7_cjs.c(u,"createGeminiRunner");let o={};p!=null&&(o.maxOutputTokens=p),c!=null&&(o.temperature=c),l!=null&&(o.topP=l),n!=null&&(o.stopSequences=n);let s=Object.keys(o).length>0;return chunkW6MVJKWN_cjs.e({fetch:b,hooks:g,buildRequest:(t,r,a)=>({url:`${m}/models/${t.model??T}:generateContent`,init:{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...t.instructions?{systemInstruction:{parts:[{text:t.instructions}]}}:{},contents:a.map(e=>({role:e.role==="assistant"?"model":"user",parts:[{text:e.content}]})),...s?{generationConfig:o}:{}}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let r=await t.json(),a=r.candidates?.[0]?.content?.parts?.[0]?.text??"",e=r.usageMetadata?.promptTokenCount??0,f=r.usageMetadata?.candidatesTokenCount??0;return {text:a,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function B(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,hooks:i,temperature:g,topP:c,stopSequences:l}=h;chunkW6MVJKWN_cjs.d(m),chunkKP3G32S7_cjs.c(u,"createGeminiStreamingRunner");let n={};p!=null&&(n.maxOutputTokens=p),g!=null&&(n.temperature=g),c!=null&&(n.topP=c),l!=null&&(n.stopSequences=l);let o=Object.keys(n).length>0;return async(s,t,r)=>{let a=chunkKP3G32S7_cjs.e(i,s,t);try{let e=await b(`${m}/models/${s.model??T}:streamGenerateContent?alt=sse`,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...s.instructions?{systemInstruction:{parts:[{text:s.instructions}]}}:{},contents:[{role:"user",parts:[{text:t}]}],...o?{generationConfig:n}:{}}),signal:r.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"Gemini");let f=chunkKP3G32S7_cjs.b(e),{fullText:R,inputTokens:C,outputTokens:O}=await chunkKP3G32S7_cjs.d(f,r.onToken,y=>{let d={},A=y.candidates?.[0]?.content?.parts?.[0]?.text;if(A&&(d.text=A),y.usageMetadata){let k=y.usageMetadata;k.promptTokenCount!==void 0&&(d.inputTokens=k.promptTokenCount),k.candidatesTokenCount!==void 0&&(d.outputTokens=k.candidatesTokenCount);}return d},"Gemini"),G={inputTokens:C,outputTokens:O},w=C+O;return r.onMessage?.({role:"assistant",content:R}),chunkKP3G32S7_cjs.f(i,s,t,R,w,G,a),chunkKP3G32S7_cjs.h(t,R,w,G)}catch(e){throw chunkKP3G32S7_cjs.g(i,s,t,e,a),e}}}
1
+ 'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk3WO4MWJM_cjs=require('./chunk-3WO4MWJM.cjs');var $={"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.025,output:.1}};function v(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,timeoutMs:i,hooks:g,temperature:c,topP:l,stopSequences:n}=h;chunk3WO4MWJM_cjs.d(m),chunkKP3G32S7_cjs.c(u,"createGeminiRunner");let o={};p!=null&&(o.maxOutputTokens=p),c!=null&&(o.temperature=c),l!=null&&(o.topP=l),n!=null&&(o.stopSequences=n);let s=Object.keys(o).length>0;return chunk3WO4MWJM_cjs.f({fetch:b,hooks:g,buildRequest:(t,r,a)=>({url:`${m}/models/${t.model??T}:generateContent`,init:{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...t.instructions?{systemInstruction:{parts:[{text:t.instructions}]}}:{},contents:a.map(e=>({role:e.role==="assistant"?"model":"user",parts:[{text:e.content}]})),...s?{generationConfig:o}:{}}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let r=await t.json(),a=r.candidates?.[0]?.content?.parts?.[0]?.text??"",e=r.usageMetadata?.promptTokenCount??0,f=r.usageMetadata?.candidatesTokenCount??0;return {text:a,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function B(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,hooks:i,temperature:g,topP:c,stopSequences:l}=h;chunk3WO4MWJM_cjs.d(m),chunkKP3G32S7_cjs.c(u,"createGeminiStreamingRunner");let n={};p!=null&&(n.maxOutputTokens=p),g!=null&&(n.temperature=g),c!=null&&(n.topP=c),l!=null&&(n.stopSequences=l);let o=Object.keys(n).length>0;return async(s,t,r)=>{let a=chunkKP3G32S7_cjs.e(i,s,t);try{let e=await b(`${m}/models/${s.model??T}:streamGenerateContent?alt=sse`,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...s.instructions?{systemInstruction:{parts:[{text:s.instructions}]}}:{},contents:[{role:"user",parts:[{text:t}]}],...o?{generationConfig:n}:{}}),signal:r.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"Gemini");let f=chunkKP3G32S7_cjs.b(e),{fullText:R,inputTokens:C,outputTokens:O}=await chunkKP3G32S7_cjs.d(f,r.onToken,y=>{let d={},A=y.candidates?.[0]?.content?.parts?.[0]?.text;if(A&&(d.text=A),y.usageMetadata){let k=y.usageMetadata;k.promptTokenCount!==void 0&&(d.inputTokens=k.promptTokenCount),k.candidatesTokenCount!==void 0&&(d.outputTokens=k.candidatesTokenCount);}return d},"Gemini"),G={inputTokens:C,outputTokens:O},w=C+O;return r.onMessage?.({role:"assistant",content:R}),chunkKP3G32S7_cjs.f(i,s,t,R,w,G,a),chunkKP3G32S7_cjs.h(t,R,w,G)}catch(e){throw chunkKP3G32S7_cjs.g(i,s,t,e,a),e}}}
2
2
  exports.GEMINI_PRICING=$;exports.createGeminiRunner=v;exports.createGeminiStreamingRunner=B;//# sourceMappingURL=gemini.cjs.map
3
3
  //# sourceMappingURL=gemini.cjs.map
package/dist/gemini.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AdapterHooks, b as AgentRunner, aX as StreamingCallbackRunner } from './types-CRmwFnVk.cjs';
1
+ import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.cjs';
2
2
  import '@directive-run/core';
3
3
 
4
4
  /**
package/dist/gemini.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AdapterHooks, b as AgentRunner, aX as StreamingCallbackRunner } from './types-CRmwFnVk.js';
1
+ import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-DJ09LjZX.js';
2
2
  import '@directive-run/core';
3
3
 
4
4
  /**
package/dist/gemini.js CHANGED
@@ -1,3 +1,3 @@
1
- import {c,e as e$1,a,b,d as d$1,f,h,g}from'./chunk-3PGRBK4E.js';import {d,e}from'./chunk-W6WZBQER.js';var $={"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.025,output:.1}};function v(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,timeoutMs:i,hooks:g,temperature:c$1,topP:l,stopSequences:n}=h;d(m),c(u,"createGeminiRunner");let o={};p!=null&&(o.maxOutputTokens=p),c$1!=null&&(o.temperature=c$1),l!=null&&(o.topP=l),n!=null&&(o.stopSequences=n);let s=Object.keys(o).length>0;return e({fetch:b,hooks:g,buildRequest:(t,r,a)=>({url:`${m}/models/${t.model??T}:generateContent`,init:{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...t.instructions?{systemInstruction:{parts:[{text:t.instructions}]}}:{},contents:a.map(e=>({role:e.role==="assistant"?"model":"user",parts:[{text:e.content}]})),...s?{generationConfig:o}:{}}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let r=await t.json(),a=r.candidates?.[0]?.content?.parts?.[0]?.text??"",e=r.usageMetadata?.promptTokenCount??0,f=r.usageMetadata?.candidatesTokenCount??0;return {text:a,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function B(h$1){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b$1=globalThis.fetch,hooks:i,temperature:g$1,topP:c$1,stopSequences:l}=h$1;d(m),c(u,"createGeminiStreamingRunner");let n={};p!=null&&(n.maxOutputTokens=p),g$1!=null&&(n.temperature=g$1),c$1!=null&&(n.topP=c$1),l!=null&&(n.stopSequences=l);let o=Object.keys(n).length>0;return async(s,t,r)=>{let a$1=e$1(i,s,t);try{let e=await b$1(`${m}/models/${s.model??T}:streamGenerateContent?alt=sse`,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...s.instructions?{systemInstruction:{parts:[{text:s.instructions}]}}:{},contents:[{role:"user",parts:[{text:t}]}],...o?{generationConfig:n}:{}}),signal:r.signal});e.ok||await a(e,"Gemini");let f$1=b(e),{fullText:R,inputTokens:C,outputTokens:O}=await d$1(f$1,r.onToken,y=>{let d={},A=y.candidates?.[0]?.content?.parts?.[0]?.text;if(A&&(d.text=A),y.usageMetadata){let k=y.usageMetadata;k.promptTokenCount!==void 0&&(d.inputTokens=k.promptTokenCount),k.candidatesTokenCount!==void 0&&(d.outputTokens=k.candidatesTokenCount);}return d},"Gemini"),G={inputTokens:C,outputTokens:O},w=C+O;return r.onMessage?.({role:"assistant",content:R}),f(i,s,t,R,w,G,a$1),h(t,R,w,G)}catch(e){throw g(i,s,t,e,a$1),e}}}
1
+ import {c,e,a,b,d as d$1,f as f$1,h,g}from'./chunk-3PGRBK4E.js';import {d,f}from'./chunk-ZFLHWJ56.js';var $={"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.025,output:.1}};function v(h){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b=globalThis.fetch,timeoutMs:i,hooks:g,temperature:c$1,topP:l,stopSequences:n}=h;d(m),c(u,"createGeminiRunner");let o={};p!=null&&(o.maxOutputTokens=p),c$1!=null&&(o.temperature=c$1),l!=null&&(o.topP=l),n!=null&&(o.stopSequences=n);let s=Object.keys(o).length>0;return f({fetch:b,hooks:g,buildRequest:(t,r,a)=>({url:`${m}/models/${t.model??T}:generateContent`,init:{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...t.instructions?{systemInstruction:{parts:[{text:t.instructions}]}}:{},contents:a.map(e=>({role:e.role==="assistant"?"model":"user",parts:[{text:e.content}]})),...s?{generationConfig:o}:{}}),...i!=null?{signal:AbortSignal.timeout(i)}:{}}}),parseResponse:async t=>{let r=await t.json(),a=r.candidates?.[0]?.content?.parts?.[0]?.text??"",e=r.usageMetadata?.promptTokenCount??0,f=r.usageMetadata?.candidatesTokenCount??0;return {text:a,totalTokens:e+f,inputTokens:e,outputTokens:f}}})}function B(h$1){let{apiKey:u,model:T="gemini-2.0-flash",maxOutputTokens:p,baseURL:m="https://generativelanguage.googleapis.com/v1beta",fetch:b$1=globalThis.fetch,hooks:i,temperature:g$1,topP:c$1,stopSequences:l}=h$1;d(m),c(u,"createGeminiStreamingRunner");let n={};p!=null&&(n.maxOutputTokens=p),g$1!=null&&(n.temperature=g$1),c$1!=null&&(n.topP=c$1),l!=null&&(n.stopSequences=l);let o=Object.keys(n).length>0;return async(s,t,r)=>{let a$1=e(i,s,t);try{let e=await b$1(`${m}/models/${s.model??T}:streamGenerateContent?alt=sse`,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":u},body:JSON.stringify({...s.instructions?{systemInstruction:{parts:[{text:s.instructions}]}}:{},contents:[{role:"user",parts:[{text:t}]}],...o?{generationConfig:n}:{}}),signal:r.signal});e.ok||await a(e,"Gemini");let f=b(e),{fullText:R,inputTokens:C,outputTokens:O}=await d$1(f,r.onToken,y=>{let d={},A=y.candidates?.[0]?.content?.parts?.[0]?.text;if(A&&(d.text=A),y.usageMetadata){let k=y.usageMetadata;k.promptTokenCount!==void 0&&(d.inputTokens=k.promptTokenCount),k.candidatesTokenCount!==void 0&&(d.outputTokens=k.candidatesTokenCount);}return d},"Gemini"),G={inputTokens:C,outputTokens:O},w=C+O;return r.onMessage?.({role:"assistant",content:R}),f$1(i,s,t,R,w,G,a$1),h(t,R,w,G)}catch(e){throw g(i,s,t,e,a$1),e}}}
2
2
  export{$ as GEMINI_PRICING,v as createGeminiRunner,B as createGeminiStreamingRunner};//# sourceMappingURL=gemini.js.map
3
3
  //# sourceMappingURL=gemini.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/gemini.ts"],"names":["GEMINI_PRICING","createGeminiRunner","options","apiKey","model","maxOutputTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","validateBaseURL","warnIfMissingApiKey","genConfig","hasGenConfig","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createGeminiStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","textVal","meta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAgDO,IAAMA,CAAAA,CACX,CACE,gBAAA,CAAkB,CAAE,KAAA,CAAO,IAAA,CAAM,MAAA,CAAQ,EAAG,CAAA,CAC5C,kBAAA,CAAoB,CAAE,KAAA,CAAO,GAAA,CAAM,MAAA,CAAQ,EAAI,CAAA,CAC/C,kBAAA,CAAoB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,CAAA,CAC9C,uBAAA,CAAyB,CAAE,KAAA,CAAO,IAAA,CAAO,MAAA,CAAQ,EAAI,CACvD,EAwCK,SAASC,CAAAA,CAAmBC,CAAAA,CAA2C,CAC5E,GAAM,CACJ,MAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,kBAAA,CACR,eAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAA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AY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,CAAA,CAC9DQ,CAAAA,CACEnC,CAAAA,CACAS,CAAAA,CACAU,CAAAA,CACAQ,CAAAA,CACAO,CAAAA,CACAD,CAAAA,CACAZ,GACF,CAAA,CAEOe,CAAAA,CAAqBjB,EAAOQ,CAAAA,CAAUO,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAActC,CAAAA,CAAOS,CAAAA,CAAOU,CAAAA,CAAOkB,CAAAA,CAAKhB,GAAS,CAAA,CAE3CgB,CACR,CACF,CACF","file":"gemini.js","sourcesContent":["/**\n * @directive-run/ai/gemini\n *\n * Google Gemini adapter for Directive AI. Provides runners for the\n * Gemini generateContent API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createGeminiRunner, createGeminiStreamingRunner } from '@directive-run/ai/gemini';\n *\n * const runner = createGeminiRunner({ apiKey: process.env.GEMINI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * Gemini model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { GEMINI_PRICING } from '@directive-run/ai/gemini';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, GEMINI_PRICING[\"gemini-2.0-flash\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, GEMINI_PRICING[\"gemini-2.0-flash\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://ai.google.dev/pricing\n */\nexport const GEMINI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gemini-2.5-pro\": { input: 1.25, output: 10 },\n \"gemini-2.5-flash\": { input: 0.15, output: 0.6 },\n \"gemini-2.0-flash\": { input: 0.1, output: 0.4 },\n \"gemini-2.0-flash-lite\": { input: 0.025, output: 0.1 },\n };\n\n// ============================================================================\n// Gemini Runner\n// ============================================================================\n\n/** Options for createGeminiRunner */\nexport interface GeminiRunnerOptions {\n apiKey: string;\n model?: string;\n maxOutputTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature. Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create an AgentRunner for the Google Gemini generateContent API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createGeminiRunner({\n * apiKey: process.env.GEMINI_API_KEY!,\n * model: 'gemini-2.0-flash',\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n */\nexport function createGeminiRunner(options: GeminiRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gemini-2.0-flash\",\n maxOutputTokens,\n baseURL = \"https://generativelanguage.googleapis.com/v1beta\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createGeminiRunner\");\n\n const genConfig: Record<string, unknown> = {};\n if (maxOutputTokens != null) {\n genConfig.maxOutputTokens = maxOutputTokens;\n }\n if (temperature != null) {\n genConfig.temperature = temperature;\n }\n if (topP != null) {\n genConfig.topP = topP;\n }\n if (stopSequences != null) {\n genConfig.stopSequences = stopSequences;\n }\n const hasGenConfig = Object.keys(genConfig).length > 0;\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/models/${agent.model ?? model}:generateContent`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n ...(agent.instructions\n ? { systemInstruction: { parts: [{ text: agent.instructions }] } }\n : {}),\n contents: messages.map((m) => ({\n role: m.role === \"assistant\" ? \"model\" : \"user\",\n parts: [{ text: m.content }],\n })),\n ...(hasGenConfig ? { generationConfig: genConfig } : {}),\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.candidates?.[0]?.content?.parts?.[0]?.text ?? \"\";\n const inputTokens = data.usageMetadata?.promptTokenCount ?? 0;\n const outputTokens = data.usageMetadata?.candidatesTokenCount ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Gemini Streaming Runner\n// ============================================================================\n\n/** Options for createGeminiStreamingRunner */\nexport interface GeminiStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxOutputTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature. Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Gemini streamGenerateContent API\n * with server-sent events. Can be used standalone or paired with `createGeminiRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createGeminiStreamingRunner({\n * apiKey: process.env.GEMINI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createGeminiStreamingRunner(\n options: GeminiStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gemini-2.0-flash\",\n maxOutputTokens,\n baseURL = \"https://generativelanguage.googleapis.com/v1beta\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createGeminiStreamingRunner\");\n\n const genConfig: Record<string, unknown> = {};\n if (maxOutputTokens != null) {\n genConfig.maxOutputTokens = maxOutputTokens;\n }\n if (temperature != null) {\n genConfig.temperature = temperature;\n }\n if (topP != null) {\n genConfig.topP = topP;\n }\n if (stopSequences != null) {\n genConfig.stopSequences = stopSequences;\n }\n const hasGenConfig = Object.keys(genConfig).length > 0;\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(\n `${baseURL}/models/${agent.model ?? model}:streamGenerateContent?alt=sse`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n ...(agent.instructions\n ? { systemInstruction: { parts: [{ text: agent.instructions }] } }\n : {}),\n contents: [{ role: \"user\", parts: [{ text: input }] }],\n ...(hasGenConfig ? { generationConfig: genConfig } : {}),\n }),\n signal: callbacks.signal,\n },\n );\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Gemini\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const text = (\n (event.candidates as Array<Record<string, unknown>>)?.[0]\n ?.content as Record<string, unknown>\n )?.parts as Array<Record<string, unknown>> | undefined;\n const textVal = text?.[0]?.text;\n if (textVal) {\n result.text = textVal as string;\n }\n\n if (event.usageMetadata) {\n const meta = event.usageMetadata as Record<string, unknown>;\n if (meta.promptTokenCount !== undefined) {\n result.inputTokens = meta.promptTokenCount as number;\n }\n if (meta.candidatesTokenCount !== undefined) {\n result.outputTokens = meta.candidatesTokenCount as number;\n }\n }\n\n return result;\n },\n \"Gemini\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/adapters/gemini.ts"],"names":["GEMINI_PRICING","createGeminiRunner","options","apiKey","model","maxOutputTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","validateBaseURL","warnIfMissingApiKey","genConfig","hasGenConfig","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createGeminiStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","textVal","meta","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAgDO,IAAMA,CAAAA,CACX,CACE,gBAAA,CAAkB,CAAE,KAAA,CAAO,IAAA,CAAM,MAAA,CAAQ,EAAG,CAAA,CAC5C,kBAAA,CAAoB,CAAE,KAAA,CAAO,GAAA,CAAM,MAAA,CAAQ,EAAI,CAAA,CAC/C,kBAAA,CAAoB,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,EAAI,CAAA,CAC9C,uBAAA,CAAyB,CAAE,KAAA,CAAO,IAAA,CAAO,MAAA,CAAQ,EAAI,CACvD,EAwCK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,QACF,CAAA,CAEMG,CAAAA,CAAa,CAAE,WAAA,CAAAjB,CAAAA,CAAa,YAAA,CAAAC,CAAa,CAAA,CACzCiB,CAAAA,CAAclB,CAAAA,CAAcC,CAAAA,CAElC,OAAAG,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,CAAA,CAC9DQ,GAAAA,CACEnC,CAAAA,CACAS,CAAAA,CACAU,CAAAA,CACAQ,CAAAA,CACAO,CAAAA,CACAD,CAAAA,CACAZ,GACF,CAAA,CAEOe,CAAAA,CAAqBjB,EAAOQ,CAAAA,CAAUO,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAActC,CAAAA,CAAOS,CAAAA,CAAOU,CAAAA,CAAOkB,CAAAA,CAAKhB,GAAS,CAAA,CAE3CgB,CACR,CACF,CACF","file":"gemini.js","sourcesContent":["/**\n * @directive-run/ai/gemini\n *\n * Google Gemini adapter for Directive AI. Provides runners for the\n * Gemini generateContent API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createGeminiRunner, createGeminiStreamingRunner } from '@directive-run/ai/gemini';\n *\n * const runner = createGeminiRunner({ apiKey: process.env.GEMINI_API_KEY! });\n * ```\n */\n\nimport { createRunner, validateBaseURL } from \"../agent-utils.js\";\nimport type { AdapterHooks, AgentRunner } from \"../types.js\";\nimport type { StreamingCallbackRunner } from \"../types.js\";\nimport {\n buildStreamingResult,\n fireAfterCallHook,\n fireBeforeCallHook,\n fireErrorHook,\n getSSEReader,\n parseSSEStream,\n throwStreamingHTTPError,\n warnIfMissingApiKey,\n} from \"./shared.js\";\n\n// ============================================================================\n// Pricing Constants\n// ============================================================================\n\n/**\n * Gemini model pricing (USD per million tokens).\n *\n * Use with `estimateCost()` for per-call cost tracking:\n * ```typescript\n * import { estimateCost } from '@directive-run/ai';\n * import { GEMINI_PRICING } from '@directive-run/ai/gemini';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, GEMINI_PRICING[\"gemini-2.0-flash\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, GEMINI_PRICING[\"gemini-2.0-flash\"].output);\n * ```\n *\n * **Note:** Pricing changes over time. These values are provided as a convenience\n * and may not reflect the latest rates. Always verify at https://ai.google.dev/pricing\n */\nexport const GEMINI_PRICING: Record<string, { input: number; output: number }> =\n {\n \"gemini-2.5-pro\": { input: 1.25, output: 10 },\n \"gemini-2.5-flash\": { input: 0.15, output: 0.6 },\n \"gemini-2.0-flash\": { input: 0.1, output: 0.4 },\n \"gemini-2.0-flash-lite\": { input: 0.025, output: 0.1 },\n };\n\n// ============================================================================\n// Gemini Runner\n// ============================================================================\n\n/** Options for createGeminiRunner */\nexport interface GeminiRunnerOptions {\n apiKey: string;\n model?: string;\n maxOutputTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** @default undefined */\n timeoutMs?: number;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature. Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create an AgentRunner for the Google Gemini generateContent API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createGeminiRunner({\n * apiKey: process.env.GEMINI_API_KEY!,\n * model: 'gemini-2.0-flash',\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n */\nexport function createGeminiRunner(options: GeminiRunnerOptions): AgentRunner {\n const {\n apiKey,\n model = \"gemini-2.0-flash\",\n maxOutputTokens,\n baseURL = \"https://generativelanguage.googleapis.com/v1beta\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createGeminiRunner\");\n\n const genConfig: Record<string, unknown> = {};\n if (maxOutputTokens != null) {\n genConfig.maxOutputTokens = maxOutputTokens;\n }\n if (temperature != null) {\n genConfig.temperature = temperature;\n }\n if (topP != null) {\n genConfig.topP = topP;\n }\n if (stopSequences != null) {\n genConfig.stopSequences = stopSequences;\n }\n const hasGenConfig = Object.keys(genConfig).length > 0;\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/models/${agent.model ?? model}:generateContent`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n ...(agent.instructions\n ? { systemInstruction: { parts: [{ text: agent.instructions }] } }\n : {}),\n contents: messages.map((m) => ({\n role: m.role === \"assistant\" ? \"model\" : \"user\",\n parts: [{ text: m.content }],\n })),\n ...(hasGenConfig ? { generationConfig: genConfig } : {}),\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n }),\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.candidates?.[0]?.content?.parts?.[0]?.text ?? \"\";\n const inputTokens = data.usageMetadata?.promptTokenCount ?? 0;\n const outputTokens = data.usageMetadata?.candidatesTokenCount ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Gemini Streaming Runner\n// ============================================================================\n\n/** Options for createGeminiStreamingRunner */\nexport interface GeminiStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n maxOutputTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature. Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Gemini streamGenerateContent API\n * with server-sent events. Can be used standalone or paired with `createGeminiRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createGeminiStreamingRunner({\n * apiKey: process.env.GEMINI_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createGeminiStreamingRunner(\n options: GeminiStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"gemini-2.0-flash\",\n maxOutputTokens,\n baseURL = \"https://generativelanguage.googleapis.com/v1beta\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createGeminiStreamingRunner\");\n\n const genConfig: Record<string, unknown> = {};\n if (maxOutputTokens != null) {\n genConfig.maxOutputTokens = maxOutputTokens;\n }\n if (temperature != null) {\n genConfig.temperature = temperature;\n }\n if (topP != null) {\n genConfig.topP = topP;\n }\n if (stopSequences != null) {\n genConfig.stopSequences = stopSequences;\n }\n const hasGenConfig = Object.keys(genConfig).length > 0;\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(\n `${baseURL}/models/${agent.model ?? model}:streamGenerateContent?alt=sse`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": apiKey,\n },\n body: JSON.stringify({\n ...(agent.instructions\n ? { systemInstruction: { parts: [{ text: agent.instructions }] } }\n : {}),\n contents: [{ role: \"user\", parts: [{ text: input }] }],\n ...(hasGenConfig ? { generationConfig: genConfig } : {}),\n }),\n signal: callbacks.signal,\n },\n );\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Gemini\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n\n const text = (\n (event.candidates as Array<Record<string, unknown>>)?.[0]\n ?.content as Record<string, unknown>\n )?.parts as Array<Record<string, unknown>> | undefined;\n const textVal = text?.[0]?.text;\n if (textVal) {\n result.text = textVal as string;\n }\n\n if (event.usageMetadata) {\n const meta = event.usageMetadata as Record<string, unknown>;\n if (meta.promptTokenCount !== undefined) {\n result.inputTokens = meta.promptTokenCount as number;\n }\n if (meta.candidatesTokenCount !== undefined) {\n result.outputTokens = meta.candidatesTokenCount as number;\n }\n }\n\n return result;\n },\n \"Gemini\",\n );\n\n const tokenUsage = { inputTokens, outputTokens };\n const totalTokens = inputTokens + outputTokens;\n\n callbacks.onMessage?.({ role: \"assistant\", content: fullText });\n fireAfterCallHook(\n hooks,\n agent,\n input,\n fullText,\n totalTokens,\n tokenUsage,\n startTime,\n );\n\n return buildStreamingResult(input, fullText, totalTokens, tokenUsage);\n } catch (err) {\n fireErrorHook(hooks, agent, input, err, startTime);\n\n throw err;\n }\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkA5K77UDX_cjs=require('./chunk-A5K77UDX.cjs');require('./chunk-K64WKZ22.cjs');Object.defineProperty(exports,"DEFAULT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.n}});Object.defineProperty(exports,"STRICT_INJECTION_PATTERNS",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.o}});Object.defineProperty(exports,"createBatchedEmbedder",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.z}});Object.defineProperty(exports,"createBruteForceIndex",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.A}});Object.defineProperty(exports,"createContentFilterGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.h}});Object.defineProperty(exports,"createEnhancedPIIGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.j}});Object.defineProperty(exports,"createInMemoryStorage",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.v}});Object.defineProperty(exports,"createLengthGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.g}});Object.defineProperty(exports,"createModerationGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.b}});Object.defineProperty(exports,"createOutputPIIGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.k}});Object.defineProperty(exports,"createOutputSchemaGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.e}});Object.defineProperty(exports,"createOutputTypeGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.f}});Object.defineProperty(exports,"createPIIGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.a}});Object.defineProperty(exports,"createPromptInjectionGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.r}});Object.defineProperty(exports,"createRateLimitGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.c}});Object.defineProperty(exports,"createSemanticCache",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.w}});Object.defineProperty(exports,"createSemanticCacheGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.x}});Object.defineProperty(exports,"createTestEmbedder",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.y}});Object.defineProperty(exports,"createToolGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.d}});Object.defineProperty(exports,"createUntrustedContentGuardrail",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.t}});Object.defineProperty(exports,"createVPTreeIndex",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.B}});Object.defineProperty(exports,"detectAndRedactPII",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.m}});Object.defineProperty(exports,"detectPII",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.l}});Object.defineProperty(exports,"detectPromptInjection",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.p}});Object.defineProperty(exports,"markUntrustedContent",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.s}});Object.defineProperty(exports,"redactPII",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.i}});Object.defineProperty(exports,"sanitizeInjection",{enumerable:true,get:function(){return chunkA5K77UDX_cjs.q}});//# sourceMappingURL=guardrails.cjs.map
2
+ //# sourceMappingURL=guardrails.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"guardrails.cjs"}