@directive-run/ai 1.23.0 → 1.24.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.
- package/README.md +27 -0
- package/dist/anthropic.cjs +1 -1
- package/dist/anthropic.cjs.map +1 -1
- package/dist/anthropic.d.cts +33 -1
- package/dist/anthropic.d.ts +33 -1
- package/dist/anthropic.js +1 -1
- package/dist/anthropic.js.map +1 -1
- package/dist/{chunk-MPMBFW2P.cjs → chunk-25OLDNZ3.cjs} +3 -3
- package/dist/chunk-25OLDNZ3.cjs.map +1 -0
- package/dist/chunk-2Y4YWZDV.js +3 -0
- package/dist/chunk-2Y4YWZDV.js.map +1 -0
- package/dist/{chunk-J2Q5KKPN.js → chunk-437ADRES.js} +3 -3
- package/dist/{chunk-J2Q5KKPN.js.map → chunk-437ADRES.js.map} +1 -1
- package/dist/{chunk-ESJQSOKJ.cjs → chunk-4LENWYLG.cjs} +7 -7
- package/dist/{chunk-ESJQSOKJ.cjs.map → chunk-4LENWYLG.cjs.map} +1 -1
- package/dist/chunk-4TDH6ZTX.cjs +3 -0
- package/dist/chunk-4TDH6ZTX.cjs.map +1 -0
- package/dist/{chunk-K64WKZ22.cjs → chunk-AEX7HKNM.cjs} +2 -2
- package/dist/chunk-AEX7HKNM.cjs.map +1 -0
- package/dist/{chunk-7KCLEIAG.js → chunk-CMH5TJGN.js} +15 -15
- package/dist/chunk-CMH5TJGN.js.map +1 -0
- package/dist/{chunk-LOHC2KP5.js → chunk-EUB4NVVN.js} +3 -3
- package/dist/{chunk-LOHC2KP5.js.map → chunk-EUB4NVVN.js.map} +1 -1
- package/dist/{chunk-CXWHLEBQ.js → chunk-H7UFBMLV.js} +3 -3
- package/dist/{chunk-CXWHLEBQ.js.map → chunk-H7UFBMLV.js.map} +1 -1
- package/dist/{chunk-TEPEQE42.js → chunk-L6H6Y6IK.js} +3 -3
- package/dist/chunk-L6H6Y6IK.js.map +1 -0
- package/dist/{chunk-PEM2LPOC.cjs → chunk-L7QHLH6U.cjs} +4 -4
- package/dist/{chunk-PEM2LPOC.cjs.map → chunk-L7QHLH6U.cjs.map} +1 -1
- package/dist/{chunk-GWWZXJOG.cjs → chunk-LPTC3N2Z.cjs} +15 -15
- package/dist/chunk-LPTC3N2Z.cjs.map +1 -0
- package/dist/{chunk-GTB6HTZV.js → chunk-MRKU3UXH.js} +2 -2
- package/dist/chunk-MRKU3UXH.js.map +1 -0
- package/dist/{chunk-UR5BMWEN.js → chunk-XMEJN4FA.js} +2 -2
- package/dist/chunk-XMEJN4FA.js.map +1 -0
- package/dist/{chunk-MDXDPECP.cjs → chunk-Y4A4UJPU.cjs} +2 -2
- package/dist/chunk-Y4A4UJPU.cjs.map +1 -0
- package/dist/{chunk-XN5LUOVS.cjs → chunk-ZUNORULG.cjs} +7 -7
- package/dist/{chunk-XN5LUOVS.cjs.map → chunk-ZUNORULG.cjs.map} +1 -1
- package/dist/{debug-timeline-DpnRMnLU.d.cts → debug-timeline-B_bXRStF.d.cts} +1 -1
- package/dist/{debug-timeline-L13P-U2I.d.ts → debug-timeline-Btt-iaak.d.ts} +1 -1
- package/dist/devtools.d.cts +5 -5
- package/dist/devtools.d.ts +5 -5
- package/dist/evals.cjs +1 -1
- package/dist/evals.d.cts +2 -2
- package/dist/evals.d.ts +2 -2
- package/dist/evals.js +1 -1
- package/dist/gemini.cjs +1 -1
- package/dist/gemini.d.cts +1 -1
- package/dist/gemini.d.ts +1 -1
- package/dist/gemini.js +1 -1
- package/dist/{guardrails-export-CxCOi3sd.d.ts → guardrails-export-lvaBJlt6.d.ts} +5 -5
- package/dist/{guardrails-export-D3pKHiPp.d.cts → guardrails-export-pmpQjIKb.d.cts} +5 -5
- package/dist/guardrails.cjs +1 -1
- package/dist/guardrails.d.cts +2 -2
- package/dist/guardrails.d.ts +2 -2
- package/dist/guardrails.js +1 -1
- package/dist/{health-monitor-C6xoXrQz.d.cts → health-monitor-DqAzufyM.d.cts} +1 -1
- package/dist/{health-monitor-qL9RNMH3.d.ts → health-monitor-DrlBF6n9.d.ts} +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.d.cts +12 -8
- package/dist/index.d.ts +12 -8
- package/dist/index.js +1 -1
- package/dist/{multi-agent-orchestrator-FIF4GLVR.js → multi-agent-orchestrator-PI7X7ZGP.js} +2 -2
- package/dist/{multi-agent-orchestrator-FIF4GLVR.js.map → multi-agent-orchestrator-PI7X7ZGP.js.map} +1 -1
- package/dist/multi-agent-orchestrator-Z5NK4HIJ.cjs +2 -0
- package/dist/{multi-agent-orchestrator-PHDHFCW3.cjs.map → multi-agent-orchestrator-Z5NK4HIJ.cjs.map} +1 -1
- package/dist/multi-agent.cjs +1 -1
- package/dist/multi-agent.d.cts +6 -6
- package/dist/multi-agent.d.ts +6 -6
- package/dist/multi-agent.js +1 -1
- package/dist/ollama.cjs +1 -1
- package/dist/ollama.d.cts +1 -1
- package/dist/ollama.d.ts +1 -1
- package/dist/ollama.js +1 -1
- package/dist/openai.cjs +1 -1
- package/dist/openai.d.cts +1 -1
- package/dist/openai.d.ts +1 -1
- package/dist/openai.js +1 -1
- package/dist/{orchestrator-types-DxWn77qo.d.cts → orchestrator-types-B9nrJYFx.d.cts} +3 -3
- package/dist/{orchestrator-types-BxOJllSa.d.ts → orchestrator-types-ByqFuu3O.d.ts} +3 -3
- package/dist/predicate.cjs +1 -1
- package/dist/predicate.d.cts +2 -2
- package/dist/predicate.d.ts +2 -2
- package/dist/predicate.js +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +4 -4
- package/dist/testing.d.ts +4 -4
- package/dist/testing.js +1 -1
- package/dist/{types-DJ09LjZX.d.cts → types-BzpGfUA2.d.cts} +11 -0
- package/dist/{types-DJ09LjZX.d.ts → types-BzpGfUA2.d.ts} +11 -0
- package/package.json +2 -2
- package/dist/chunk-3WO4MWJM.cjs +0 -3
- package/dist/chunk-3WO4MWJM.cjs.map +0 -1
- package/dist/chunk-7KCLEIAG.js.map +0 -1
- package/dist/chunk-GTB6HTZV.js.map +0 -1
- package/dist/chunk-GWWZXJOG.cjs.map +0 -1
- package/dist/chunk-K64WKZ22.cjs.map +0 -1
- package/dist/chunk-MDXDPECP.cjs.map +0 -1
- package/dist/chunk-MPMBFW2P.cjs.map +0 -1
- package/dist/chunk-TEPEQE42.js.map +0 -1
- package/dist/chunk-UR5BMWEN.js.map +0 -1
- package/dist/chunk-ZFLHWJ56.js +0 -3
- package/dist/chunk-ZFLHWJ56.js.map +0 -1
- package/dist/multi-agent-orchestrator-PHDHFCW3.cjs +0 -2
package/README.md
CHANGED
|
@@ -56,6 +56,7 @@ Adapters are thin wrappers around each provider's HTTP API. No SDK dependencies
|
|
|
56
56
|
| Streaming runner | `createOpenAIStreamingRunner` | `createAnthropicStreamingRunner` | – | `createGeminiStreamingRunner` |
|
|
57
57
|
| Embedder | `createOpenAIEmbedder` | – | – | – |
|
|
58
58
|
| Pricing constants | `OPENAI_PRICING` | `ANTHROPIC_PRICING` | – | `GEMINI_PRICING` |
|
|
59
|
+
| Prompt caching | – | `promptCaching: "automatic"` | – | – |
|
|
59
60
|
| Compatible APIs | Azure, Together, any OpenAI-compatible | – | – | – |
|
|
60
61
|
|
|
61
62
|
## Cost Tracking
|
|
@@ -75,6 +76,32 @@ const cost =
|
|
|
75
76
|
estimateCost(outputTokens, OPENAI_PRICING["gpt-4o"].output);
|
|
76
77
|
```
|
|
77
78
|
|
|
79
|
+
## Prompt Caching (Anthropic)
|
|
80
|
+
|
|
81
|
+
Opt in with `promptCaching: "automatic"` to place a `cache_control` breakpoint on the agent's instructions. Anthropic caches that stable system prefix, so repeat calls that share it read from cache (~0.1x input cost) instead of reprocessing it – the variable message suffix stays uncached. It is off by default (bare-string system, byte-for-byte the prior behavior), non-breaking, and needs no beta header on `anthropic-version: 2023-06-01`.
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
import { createAnthropicRunner } from "@directive-run/ai/anthropic";
|
|
85
|
+
|
|
86
|
+
const runner = createAnthropicRunner({
|
|
87
|
+
apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
88
|
+
promptCaching: "automatic",
|
|
89
|
+
});
|
|
90
|
+
const result = await runner(agent, "Hello");
|
|
91
|
+
|
|
92
|
+
// Cache usage is surfaced on tokenUsage (present only when caching is active):
|
|
93
|
+
const { inputTokens, cacheReadTokens = 0, cacheCreationTokens = 0 } =
|
|
94
|
+
result.tokenUsage!;
|
|
95
|
+
// cacheCreationTokens – tokens written to cache on the first call (~1.25x cost)
|
|
96
|
+
// cacheReadTokens – tokens served from cache on repeat calls (~0.1x cost)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`inputTokens` is the **uncached** remainder only; `cacheReadTokens` / `cacheCreationTokens` are separate, additive fields, and `totalTokens` includes all four (input + output + cache-read + cache-creation). When caching is off the cache fields are omitted and `totalTokens` is `inputTokens + outputTokens`, exactly as before. Currently supported on the non-streaming `createAnthropicRunner`.
|
|
100
|
+
|
|
101
|
+
> **Minimum cacheable prefix (the #1 gotcha).** Anthropic silently ignores `cache_control` when the cached prefix is below a per-model minimum – roughly 1024 tokens on Sonnet-tier models, 2048 on Sonnet-4.6 & Haiku-3.5, and 4096 on Opus & Haiku-4.5. There is no error: caching just doesn't happen and `cacheReadTokens` stays `0` across repeat calls (that `0` is your diagnostic). Because Directive caches `agent.instructions`, short instructions commonly fall below this threshold. The `ephemeral` breakpoint also has a **5-minute default TTL** – prefixes not re-read within that window are evicted.
|
|
102
|
+
|
|
103
|
+
> **Cost tracking caveat.** `withBudget` / `estimateCost` currently weight all tokens equally, so with caching on they do **not** yet reflect the cheaper cache-read (~0.1x) or pricier cache-write (~1.25x) rates – a cached run will read as more expensive than it actually is. Cache-aware cost pricing is a planned follow-up.
|
|
104
|
+
|
|
78
105
|
## Lifecycle Hooks
|
|
79
106
|
|
|
80
107
|
Attach hooks to any adapter for observability:
|
package/dist/anthropic.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),
|
|
1
|
+
'use strict';var chunkKP3G32S7_cjs=require('./chunk-KP3G32S7.cjs'),chunk4TDH6ZTX_cjs=require('./chunk-4TDH6ZTX.cjs');var K={"claude-sonnet-4-5-20250929":{input:3,output:15},"claude-sonnet-4-20250514":{input:3,output:15},"claude-haiku-4-5-20250514":{input:.8,output:4},"claude-haiku-3-5-20241022":{input:.8,output:4},"claude-opus-4-20250514":{input:15,output:75}};function L(f){let{apiKey:c,model:R="claude-sonnet-4-5-20250929",maxTokens:y=4096,baseURL:m="https://api.anthropic.com/v1",fetch:T=globalThis.fetch,timeoutMs:p,hooks:k,temperature:l,topP:g,stopSequences:r,promptCaching:a}=f;return chunk4TDH6ZTX_cjs.d(m),chunkKP3G32S7_cjs.c(c,"createAnthropicRunner"),chunk4TDH6ZTX_cjs.f({fetch:T,hooks:k,buildRequest:(i,s,e)=>{let n=i.instructions??"",o=a==="automatic"&&n.trim()!==""?[{type:"text",text:n,cache_control:{type:"ephemeral"}}]:n;return {url:`${m}/messages`,init:{method:"POST",headers:{"Content-Type":"application/json","x-api-key":c,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:i.model??R,max_tokens:y,...l!=null?{temperature:l}:{},...g!=null?{top_p:g}:{},...r!=null?{stop_sequences:r}:{},system:o,messages:e.map(u=>({role:u.role,content:u.content}))}),...p!=null?{signal:AbortSignal.timeout(p)}:{}}}},parseResponse:async i=>{let s=await i.json(),e=s.content?.[0]?.text??"",n=s.usage?.input_tokens??0,o=s.usage?.output_tokens??0;if(a==="automatic"){let u=s.usage?.cache_read_input_tokens??0,h=s.usage?.cache_creation_input_tokens??0;return {text:e,totalTokens:n+o+u+h,inputTokens:n,outputTokens:o,cacheReadTokens:u,cacheCreationTokens:h}}return {text:e,totalTokens:n+o,inputTokens:n,outputTokens:o}}})}function N(f){let{apiKey:c,model:R="claude-sonnet-4-5-20250929",maxTokens:y=4096,baseURL:m="https://api.anthropic.com/v1",fetch:T=globalThis.fetch,hooks:p,temperature:k,topP:l,stopSequences:g}=f;return chunk4TDH6ZTX_cjs.d(m),chunkKP3G32S7_cjs.c(c,"createAnthropicStreamingRunner"),async(r,a,i)=>{let s=chunkKP3G32S7_cjs.e(p,r,a);try{let e=await T(`${m}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":c,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r.model??R,max_tokens:y,...k!=null?{temperature:k}:{},...l!=null?{top_p:l}:{},...g!=null?{stop_sequences:g}:{},system:r.instructions??"",messages:[{role:"user",content:a}],stream:!0}),signal:i.signal});e.ok||await chunkKP3G32S7_cjs.a(e,"Anthropic");let n=chunkKP3G32S7_cjs.b(e),{fullText:o,inputTokens:u,outputTokens:h}=await chunkKP3G32S7_cjs.d(n,i.onToken,t=>{if(t.type==="error")throw new Error(`[Directive] Anthropic stream error: ${t.error?.message??JSON.stringify(t.error)}`);let d={};return t.type==="content_block_delta"&&t.delta?.type==="text_delta"&&(d.text=t.delta.text),t.type==="message_delta"&&t.usage&&(d.outputTokens=t.usage.output_tokens??0),t.type==="message_start"&&t.message?.usage&&(d.inputTokens=t.message.usage.input_tokens??0),d},"Anthropic"),S={inputTokens:u,outputTokens:h},x=u+h;return i.onMessage?.({role:"assistant",content:o}),chunkKP3G32S7_cjs.f(p,r,a,o,x,S,s),chunkKP3G32S7_cjs.h(a,o,x,S)}catch(e){throw chunkKP3G32S7_cjs.g(p,r,a,e,s),e}}}
|
|
2
2
|
exports.ANTHROPIC_PRICING=K;exports.createAnthropicRunner=L;exports.createAnthropicStreamingRunner=N;//# sourceMappingURL=anthropic.cjs.map
|
|
3
3
|
//# sourceMappingURL=anthropic.cjs.map
|
package/dist/anthropic.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/anthropic.ts"],"names":["ANTHROPIC_PRICING","createAnthropicRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","validateBaseURL","warnIfMissingApiKey","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createAnthropicStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"qHAgDO,IAAMA,CAAAA,CAGT,CACF,4BAAA,CAA8B,CAAE,KAAA,CAAO,CAAA,CAAG,MAAA,CAAQ,EAAG,CAAA,CACrD,0BAAA,CAA4B,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,EAAG,CAAA,CACnD,2BAAA,CAA6B,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,CAAE,CAAA,CACrD,2BAAA,CAA6B,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,CAAE,CAAA,CACrD,wBAAA,CAA0B,CAAE,KAAA,CAAO,EAAA,CAAI,MAAA,CAAQ,EAAG,CACpD,EA6CO,SAASC,CAAAA,CACdC,CAAAA,CACa,CACb,GAAM,CACJ,MAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,4BAAA,CACR,SAAA,CAAAC,CAAAA,CAAY,IAAA,CACZ,OAAA,CAAAC,CAAAA,CAAU,8BAAA,CACV,KAAA,CAAOC,CAAAA,CAAU,UAAA,CAAW,KAAA,CAC5B,UAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CACF,CAAA,CAAIV,CAAAA,CAEJ,OAAAW,mBAAAA,CAAgBP,CAAO,CAAA,CACvBQ,mBAAAA,CAAoBX,CAAAA,CAAQ,uBAAuB,CAAA,CAE5CY,mBAAAA,CAAa,CAClB,KAAA,CAAOR,CAAAA,CACP,KAAA,CAAAE,CAAAA,CACA,YAAA,CAAc,CAACO,CAAAA,CAAOC,CAAAA,CAAQC,CAAA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EAAqC,QAE5CC,CAAAA,CAAO,WAAA,CAEFD,CAAAA,CAAM,OAAA,CAAoC,KAAA,CAI3C,YAAA,EAA2B,CAAA,CAAA,CAG1BC,CACT,CAAA,CACA,WACF,CAAA,CAEMC,CAAAA,CAAa,CAAE,WAAA,CAAAf,CAAAA,CAAa,YAAA,CAAAC,CAAa,CAAA,CACzCe,CAAAA,CAAchB,CAAAA,CAAcC,CAAAA,CAElC,OAAAG,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,EAC9DM,mBAAAA,CACE/B,CAAAA,CACAO,CAAAA,CACAU,CAAAA,CACAQ,CAAAA,CACAK,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,mBAAAA,CAAqBf,CAAAA,CAAOQ,CAAAA,CAAUK,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,mBAAAA,CAAclC,CAAAA,CAAOO,CAAAA,CAAOU,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"anthropic.cjs","sourcesContent":["/**\n * @directive-run/ai/anthropic\n *\n * Anthropic adapter for Directive AI. Provides runners for the\n * Anthropic Messages API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createAnthropicRunner, createAnthropicStreamingRunner } from '@directive-run/ai/anthropic';\n *\n * const runner = createAnthropicRunner({ apiKey: process.env.ANTHROPIC_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 * Anthropic 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 { ANTHROPIC_PRICING } from '@directive-run/ai/anthropic';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].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://anthropic.com/pricing\n */\nexport const ANTHROPIC_PRICING: Record<\n string,\n { input: number; output: number }\n> = {\n \"claude-sonnet-4-5-20250929\": { input: 3, output: 15 },\n \"claude-sonnet-4-20250514\": { input: 3, output: 15 },\n \"claude-haiku-4-5-20250514\": { input: 0.8, output: 4 },\n \"claude-haiku-3-5-20241022\": { input: 0.8, output: 4 },\n \"claude-opus-4-20250514\": { input: 15, output: 75 },\n};\n\n// ============================================================================\n// Anthropic Runner\n// ============================================================================\n\n/** Options for createAnthropicRunner */\nexport interface AnthropicRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: 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 (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create an AgentRunner for the Anthropic Messages API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`${durationMs}ms – ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n */\nexport function createAnthropicRunner(\n options: AnthropicRunnerOptions,\n): AgentRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicRunner\");\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/messages`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\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.content?.[0]?.text ?? \"\";\n const inputTokens = data.usage?.input_tokens ?? 0;\n const outputTokens = data.usage?.output_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Anthropic Streaming Runner\n// ============================================================================\n\n/** Options for createAnthropicStreamingRunner */\nexport interface AnthropicStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Anthropic Messages API with\n * server-sent events. Can be used standalone or paired with `createAnthropicRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createAnthropicStreamingRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createAnthropicStreamingRunner(\n options: AnthropicStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicStreamingRunner\");\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: [{ role: \"user\", content: input }],\n stream: true,\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Anthropic\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n if (event.type === \"error\") {\n throw new Error(\n `[Directive] Anthropic stream error: ${(event.error as Record<string, unknown>)?.message ?? JSON.stringify(event.error)}`,\n );\n }\n\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n if (\n event.type === \"content_block_delta\" &&\n (event.delta as Record<string, unknown>)?.type === \"text_delta\"\n ) {\n result.text = (event.delta as Record<string, unknown>)\n .text as string;\n }\n if (event.type === \"message_delta\" && event.usage) {\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .output_tokens as number) ?? 0;\n }\n if (\n event.type === \"message_start\" &&\n (event.message as Record<string, unknown>)?.usage\n ) {\n result.inputTokens =\n ((\n (event.message as Record<string, unknown>).usage as Record<\n string,\n unknown\n >\n ).input_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"Anthropic\",\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/anthropic.ts"],"names":["ANTHROPIC_PRICING","createAnthropicRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","promptCaching","validateBaseURL","warnIfMissingApiKey","createRunner","agent","_input","messages","instructions","system","m","res","data","text","inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","createAnthropicStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"qHAgDO,IAAMA,CAAAA,CAGT,CACF,4BAAA,CAA8B,CAAE,KAAA,CAAO,CAAA,CAAG,M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AA,CAAO,KAAQD,CAAAA,CAAM,KAAA,CAClB,IAAA,CAAA,CAEDA,CAAAA,CAAM,IAAA,GAAS,eAAA,EAAmBA,CAAAA,CAAM,KAAA,GAC1CC,EAAO,YAAA,CACHD,CAAAA,CAAM,KAAA,CACL,aAAA,EAA4B,CAAA,CAAA,CAGjCA,CAAAA,CAAM,IAAA,GAAS,eAAA,EACdA,CAAAA,CAAM,OAAA,EAAqC,KAAA,GAE5CC,CAAAA,CAAO,WAAA,CAEFD,CAAAA,CAAM,OAAA,CAAoC,KAAA,CAI3C,cAA2B,CAAA,CAAA,CAG1BC,CACT,CAAA,CACA,WACF,CAAA,CAEMC,CAAAA,CAAa,CAAE,WAAA,CAAAjB,EAAa,YAAA,CAAAC,CAAa,CAAA,CACzCiB,CAAAA,CAAclB,CAAAA,CAAcC,CAAAA,CAElC,OAAAK,CAAAA,CAAU,YAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,CAAA,CAC9DM,mBAAAA,CACEpC,CAAAA,CACAQ,CAAAA,CACAc,CAAAA,CACAQ,CAAAA,CACAK,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,oBAAqBf,CAAAA,CAAOQ,CAAAA,CAAUK,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,mBAAAA,CAAcvC,CAAAA,CAAOQ,CAAAA,CAAOc,CAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"anthropic.cjs","sourcesContent":["/**\n * @directive-run/ai/anthropic\n *\n * Anthropic adapter for Directive AI. Provides runners for the\n * Anthropic Messages API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createAnthropicRunner, createAnthropicStreamingRunner } from '@directive-run/ai/anthropic';\n *\n * const runner = createAnthropicRunner({ apiKey: process.env.ANTHROPIC_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 * Anthropic 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 { ANTHROPIC_PRICING } from '@directive-run/ai/anthropic';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].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://anthropic.com/pricing\n */\nexport const ANTHROPIC_PRICING: Record<\n string,\n { input: number; output: number }\n> = {\n \"claude-sonnet-4-5-20250929\": { input: 3, output: 15 },\n \"claude-sonnet-4-20250514\": { input: 3, output: 15 },\n \"claude-haiku-4-5-20250514\": { input: 0.8, output: 4 },\n \"claude-haiku-3-5-20241022\": { input: 0.8, output: 4 },\n \"claude-opus-4-20250514\": { input: 15, output: 75 },\n};\n\n// ============================================================================\n// Anthropic Runner\n// ============================================================================\n\n/** Options for createAnthropicRunner */\nexport interface AnthropicRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: 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 (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n /**\n * Prompt caching strategy. When `\"automatic\"`, a `cache_control` breakpoint is\n * placed on the system prompt so the stable instructions prefix is cached across\n * calls – subsequent runs read it from cache instead of re-processing it. The\n * variable message suffix is never cached. Cache token usage is surfaced on\n * `tokenUsage.cacheReadTokens` / `tokenUsage.cacheCreationTokens`.\n *\n * Anthropic silently ignores `cache_control` when the cached prefix is below a\n * per-model minimum (~1024 tokens Sonnet-tier, 2048 for Sonnet-4.6 & Haiku-3.5,\n * 4096 for Opus & Haiku-4.5) – no error, no caching, and `cacheReadTokens` stays\n * 0 (that 0 is the diagnostic). Since Directive caches `agent.instructions`,\n * short instructions commonly fall below this. The `ephemeral` breakpoint has a\n * 5-minute default TTL.\n *\n * @default undefined – caching disabled (bare-string system, current behavior).\n */\n promptCaching?: \"automatic\";\n}\n\n/**\n * Create an AgentRunner for the Anthropic Messages API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`${durationMs}ms – ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n *\n * @example Prompt caching – cache the stable instructions prefix and read the\n * cache-token breakdown back for cost tracking:\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * promptCaching: \"automatic\",\n * });\n * const result = await orchestrator.run(agent, input);\n * // tokenUsage.cacheCreationTokens – tokens written on the first call\n * // tokenUsage.cacheReadTokens – tokens served from cache on repeat calls\n * const { inputTokens, cacheReadTokens = 0, cacheCreationTokens = 0 } =\n * result.tokenUsage!;\n * // Cache reads bill ~0.1x and cache writes ~1.25x the base input rate.\n * ```\n */\nexport function createAnthropicRunner(\n options: AnthropicRunnerOptions,\n): AgentRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n promptCaching,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicRunner\");\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => {\n const instructions = agent.instructions ?? \"\";\n // With prompt caching enabled, send the structured system form so a\n // `cache_control` breakpoint caches the stable instructions prefix.\n // Fall back to the bare string – byte-for-byte the prior behavior – when\n // caching is off, and also when there is nothing stable to cache: an\n // empty/whitespace-only cached block is wasteful and risks a 400.\n const system =\n promptCaching === \"automatic\" && instructions.trim() !== \"\"\n ? [\n {\n type: \"text\",\n text: instructions,\n cache_control: { type: \"ephemeral\" },\n },\n ]\n : instructions;\n\n return {\n url: `${baseURL}/messages`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system,\n messages: messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n };\n },\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.content?.[0]?.text ?? \"\";\n const inputTokens = data.usage?.input_tokens ?? 0;\n const outputTokens = data.usage?.output_tokens ?? 0;\n\n // Cache-token emission is gated on the OPTION, not on the response fields:\n // the live API returns `cache_*_input_tokens: 0` on every response even\n // when no `cache_control` was sent, so keying off their presence would\n // wrongly emit `cacheReadTokens: 0` on a caching-off call. When caching is\n // on we always emit both (default 0, so a cache miss correctly reports 0);\n // when it's off we omit them entirely so `tokenUsage` is byte-identical to\n // the pre-caching behavior. `input_tokens` is the uncached remainder, so\n // cache tokens are additive – include them in `totalTokens`.\n if (promptCaching === \"automatic\") {\n const cacheReadTokens = data.usage?.cache_read_input_tokens ?? 0;\n const cacheCreationTokens =\n data.usage?.cache_creation_input_tokens ?? 0;\n\n return {\n text,\n totalTokens:\n inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheCreationTokens,\n };\n }\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Anthropic Streaming Runner\n// ============================================================================\n\n/** Options for createAnthropicStreamingRunner */\nexport interface AnthropicStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Anthropic Messages API with\n * server-sent events. Can be used standalone or paired with `createAnthropicRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createAnthropicStreamingRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createAnthropicStreamingRunner(\n options: AnthropicStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicStreamingRunner\");\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: [{ role: \"user\", content: input }],\n stream: true,\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Anthropic\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n if (event.type === \"error\") {\n throw new Error(\n `[Directive] Anthropic stream error: ${(event.error as Record<string, unknown>)?.message ?? JSON.stringify(event.error)}`,\n );\n }\n\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n if (\n event.type === \"content_block_delta\" &&\n (event.delta as Record<string, unknown>)?.type === \"text_delta\"\n ) {\n result.text = (event.delta as Record<string, unknown>)\n .text as string;\n }\n if (event.type === \"message_delta\" && event.usage) {\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .output_tokens as number) ?? 0;\n }\n if (\n event.type === \"message_start\" &&\n (event.message as Record<string, unknown>)?.usage\n ) {\n result.inputTokens =\n ((\n (event.message as Record<string, unknown>).usage as Record<\n string,\n unknown\n >\n ).input_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"Anthropic\",\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"]}
|
package/dist/anthropic.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-
|
|
1
|
+
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-BzpGfUA2.cjs';
|
|
2
2
|
import '@directive-run/core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -53,6 +53,23 @@ interface AnthropicRunnerOptions {
|
|
|
53
53
|
topP?: number;
|
|
54
54
|
/** Custom stop sequences. The model will stop generating when it encounters one. */
|
|
55
55
|
stopSequences?: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Prompt caching strategy. When `"automatic"`, a `cache_control` breakpoint is
|
|
58
|
+
* placed on the system prompt so the stable instructions prefix is cached across
|
|
59
|
+
* calls – subsequent runs read it from cache instead of re-processing it. The
|
|
60
|
+
* variable message suffix is never cached. Cache token usage is surfaced on
|
|
61
|
+
* `tokenUsage.cacheReadTokens` / `tokenUsage.cacheCreationTokens`.
|
|
62
|
+
*
|
|
63
|
+
* Anthropic silently ignores `cache_control` when the cached prefix is below a
|
|
64
|
+
* per-model minimum (~1024 tokens Sonnet-tier, 2048 for Sonnet-4.6 & Haiku-3.5,
|
|
65
|
+
* 4096 for Opus & Haiku-4.5) – no error, no caching, and `cacheReadTokens` stays
|
|
66
|
+
* 0 (that 0 is the diagnostic). Since Directive caches `agent.instructions`,
|
|
67
|
+
* short instructions commonly fall below this. The `ephemeral` breakpoint has a
|
|
68
|
+
* 5-minute default TTL.
|
|
69
|
+
*
|
|
70
|
+
* @default undefined – caching disabled (bare-string system, current behavior).
|
|
71
|
+
*/
|
|
72
|
+
promptCaching?: "automatic";
|
|
56
73
|
}
|
|
57
74
|
/**
|
|
58
75
|
* Create an AgentRunner for the Anthropic Messages API.
|
|
@@ -72,6 +89,21 @@ interface AnthropicRunnerOptions {
|
|
|
72
89
|
* const orchestrator = createAgentOrchestrator({ runner });
|
|
73
90
|
* const result = await orchestrator.run(agent, input);
|
|
74
91
|
* ```
|
|
92
|
+
*
|
|
93
|
+
* @example Prompt caching – cache the stable instructions prefix and read the
|
|
94
|
+
* cache-token breakdown back for cost tracking:
|
|
95
|
+
* ```typescript
|
|
96
|
+
* const runner = createAnthropicRunner({
|
|
97
|
+
* apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
98
|
+
* promptCaching: "automatic",
|
|
99
|
+
* });
|
|
100
|
+
* const result = await orchestrator.run(agent, input);
|
|
101
|
+
* // tokenUsage.cacheCreationTokens – tokens written on the first call
|
|
102
|
+
* // tokenUsage.cacheReadTokens – tokens served from cache on repeat calls
|
|
103
|
+
* const { inputTokens, cacheReadTokens = 0, cacheCreationTokens = 0 } =
|
|
104
|
+
* result.tokenUsage!;
|
|
105
|
+
* // Cache reads bill ~0.1x and cache writes ~1.25x the base input rate.
|
|
106
|
+
* ```
|
|
75
107
|
*/
|
|
76
108
|
declare function createAnthropicRunner(options: AnthropicRunnerOptions): AgentRunner;
|
|
77
109
|
/** Options for createAnthropicStreamingRunner */
|
package/dist/anthropic.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-
|
|
1
|
+
import { o as AdapterHooks, c as AgentRunner, p as StreamingCallbackRunner } from './types-BzpGfUA2.js';
|
|
2
2
|
import '@directive-run/core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -53,6 +53,23 @@ interface AnthropicRunnerOptions {
|
|
|
53
53
|
topP?: number;
|
|
54
54
|
/** Custom stop sequences. The model will stop generating when it encounters one. */
|
|
55
55
|
stopSequences?: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Prompt caching strategy. When `"automatic"`, a `cache_control` breakpoint is
|
|
58
|
+
* placed on the system prompt so the stable instructions prefix is cached across
|
|
59
|
+
* calls – subsequent runs read it from cache instead of re-processing it. The
|
|
60
|
+
* variable message suffix is never cached. Cache token usage is surfaced on
|
|
61
|
+
* `tokenUsage.cacheReadTokens` / `tokenUsage.cacheCreationTokens`.
|
|
62
|
+
*
|
|
63
|
+
* Anthropic silently ignores `cache_control` when the cached prefix is below a
|
|
64
|
+
* per-model minimum (~1024 tokens Sonnet-tier, 2048 for Sonnet-4.6 & Haiku-3.5,
|
|
65
|
+
* 4096 for Opus & Haiku-4.5) – no error, no caching, and `cacheReadTokens` stays
|
|
66
|
+
* 0 (that 0 is the diagnostic). Since Directive caches `agent.instructions`,
|
|
67
|
+
* short instructions commonly fall below this. The `ephemeral` breakpoint has a
|
|
68
|
+
* 5-minute default TTL.
|
|
69
|
+
*
|
|
70
|
+
* @default undefined – caching disabled (bare-string system, current behavior).
|
|
71
|
+
*/
|
|
72
|
+
promptCaching?: "automatic";
|
|
56
73
|
}
|
|
57
74
|
/**
|
|
58
75
|
* Create an AgentRunner for the Anthropic Messages API.
|
|
@@ -72,6 +89,21 @@ interface AnthropicRunnerOptions {
|
|
|
72
89
|
* const orchestrator = createAgentOrchestrator({ runner });
|
|
73
90
|
* const result = await orchestrator.run(agent, input);
|
|
74
91
|
* ```
|
|
92
|
+
*
|
|
93
|
+
* @example Prompt caching – cache the stable instructions prefix and read the
|
|
94
|
+
* cache-token breakdown back for cost tracking:
|
|
95
|
+
* ```typescript
|
|
96
|
+
* const runner = createAnthropicRunner({
|
|
97
|
+
* apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
98
|
+
* promptCaching: "automatic",
|
|
99
|
+
* });
|
|
100
|
+
* const result = await orchestrator.run(agent, input);
|
|
101
|
+
* // tokenUsage.cacheCreationTokens – tokens written on the first call
|
|
102
|
+
* // tokenUsage.cacheReadTokens – tokens served from cache on repeat calls
|
|
103
|
+
* const { inputTokens, cacheReadTokens = 0, cacheCreationTokens = 0 } =
|
|
104
|
+
* result.tokenUsage!;
|
|
105
|
+
* // Cache reads bill ~0.1x and cache writes ~1.25x the base input rate.
|
|
106
|
+
* ```
|
|
75
107
|
*/
|
|
76
108
|
declare function createAnthropicRunner(options: AnthropicRunnerOptions): AgentRunner;
|
|
77
109
|
/** Options for createAnthropicStreamingRunner */
|
package/dist/anthropic.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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-
|
|
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-2Y4YWZDV.js';var K={"claude-sonnet-4-5-20250929":{input:3,output:15},"claude-sonnet-4-20250514":{input:3,output:15},"claude-haiku-4-5-20250514":{input:.8,output:4},"claude-haiku-3-5-20241022":{input:.8,output:4},"claude-opus-4-20250514":{input:15,output:75}};function L(f$1){let{apiKey:c$1,model:R="claude-sonnet-4-5-20250929",maxTokens:y=4096,baseURL:m="https://api.anthropic.com/v1",fetch:T=globalThis.fetch,timeoutMs:p,hooks:k,temperature:l,topP:g,stopSequences:r,promptCaching:a}=f$1;return d(m),c(c$1,"createAnthropicRunner"),f({fetch:T,hooks:k,buildRequest:(i,s,e)=>{let n=i.instructions??"",o=a==="automatic"&&n.trim()!==""?[{type:"text",text:n,cache_control:{type:"ephemeral"}}]:n;return {url:`${m}/messages`,init:{method:"POST",headers:{"Content-Type":"application/json","x-api-key":c$1,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:i.model??R,max_tokens:y,...l!=null?{temperature:l}:{},...g!=null?{top_p:g}:{},...r!=null?{stop_sequences:r}:{},system:o,messages:e.map(u=>({role:u.role,content:u.content}))}),...p!=null?{signal:AbortSignal.timeout(p)}:{}}}},parseResponse:async i=>{let s=await i.json(),e=s.content?.[0]?.text??"",n=s.usage?.input_tokens??0,o=s.usage?.output_tokens??0;if(a==="automatic"){let u=s.usage?.cache_read_input_tokens??0,h=s.usage?.cache_creation_input_tokens??0;return {text:e,totalTokens:n+o+u+h,inputTokens:n,outputTokens:o,cacheReadTokens:u,cacheCreationTokens:h}}return {text:e,totalTokens:n+o,inputTokens:n,outputTokens:o}}})}function N(f){let{apiKey:c$1,model:R="claude-sonnet-4-5-20250929",maxTokens:y=4096,baseURL:m="https://api.anthropic.com/v1",fetch:T=globalThis.fetch,hooks:p,temperature:k,topP:l,stopSequences:g$1}=f;return d(m),c(c$1,"createAnthropicStreamingRunner"),async(r,a$1,i)=>{let s=e(p,r,a$1);try{let e=await T(`${m}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":c$1,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r.model??R,max_tokens:y,...k!=null?{temperature:k}:{},...l!=null?{top_p:l}:{},...g$1!=null?{stop_sequences:g$1}:{},system:r.instructions??"",messages:[{role:"user",content:a$1}],stream:!0}),signal:i.signal});e.ok||await a(e,"Anthropic");let n=b(e),{fullText:o,inputTokens:u,outputTokens:h$1}=await d$1(n,i.onToken,t=>{if(t.type==="error")throw new Error(`[Directive] Anthropic stream error: ${t.error?.message??JSON.stringify(t.error)}`);let d={};return t.type==="content_block_delta"&&t.delta?.type==="text_delta"&&(d.text=t.delta.text),t.type==="message_delta"&&t.usage&&(d.outputTokens=t.usage.output_tokens??0),t.type==="message_start"&&t.message?.usage&&(d.inputTokens=t.message.usage.input_tokens??0),d},"Anthropic"),S={inputTokens:u,outputTokens:h$1},x=u+h$1;return i.onMessage?.({role:"assistant",content:o}),f$1(p,r,a$1,o,x,S,s),h(a$1,o,x,S)}catch(e){throw g(p,r,a$1,e,s),e}}}
|
|
2
2
|
export{K as ANTHROPIC_PRICING,L as createAnthropicRunner,N as createAnthropicStreamingRunner};//# sourceMappingURL=anthropic.js.map
|
|
3
3
|
//# sourceMappingURL=anthropic.js.map
|
package/dist/anthropic.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/anthropic.ts"],"names":["ANTHROPIC_PRICING","createAnthropicRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","validateBaseURL","warnIfMissingApiKey","createRunner","agent","_input","messages","m","res","data","text","inputTokens","outputTokens","createAnthropicStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","tokenUsage","totalTokens","fireAfterCallHook","buildStreamingResult","err","fireErrorHook"],"mappings":"sGAgDO,IAAMA,CAAAA,CAGT,CACF,4BAAA,CAA8B,CAAE,KAAA,CAAO,CAAA,CAAG,MAAA,CAAQ,EAAG,CAAA,CACrD,0BAAA,CAA4B,CAAE,KAAA,CAAO,CAAA,CAAG,OAAQ,EAAG,CAAA,CACnD,2BAAA,CAA6B,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,CAAE,CAAA,CACrD,2BAAA,CAA6B,CAAE,KAAA,CAAO,EAAA,CAAK,MAAA,CAAQ,CAAE,CAAA,CACrD,wBAAA,CAA0B,CAAE,KAAA,CAAO,EAAA,CAAI,MAAA,CAAQ,EAAG,CACpD,EA6CO,SAASC,CAAAA,CACdC,CAAAA,CACa,CACb,GAAM,CACJ,MAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,4BAAA,CACR,SAAA,CAAAC,GAAAA,CAAY,IAAA,CACZ,OAAA,CAAAC,CAAAA,CAAU,8BAAA,CACV,KAAA,CAAOC,GAAAA,CAAU,UAAA,CAAW,KAAA,CAC5B,UAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,GAAAA,CACA,aAAA,CAAAC,CACF,CAAA,CAAIV,CAAAA,CAEJ,OAAAW,CAAAA,CAAgBP,CAAO,CAAA,CACvBQ,CAAAA,CAAoBX,CAAAA,CAAQ,uBAAuB,CAAA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AA,CACHD,CAAAA,CAAM,KAAA,CACL,aAAA,EAA4B,CAAA,CAAA,CAGjCA,CAAAA,CAAM,IAAA,GAAS,eAAA,EACdA,CAAAA,CAAM,OAAA,EAAqC,QAE5CC,CAAAA,CAAO,WAAA,CAEFD,CAAAA,CAAM,OAAA,CAAoC,KAAA,CAI3C,YAAA,EAA2B,CAAA,CAAA,CAG1BC,CACT,CAAA,CACA,WACF,CAAA,CAEMC,CAAAA,CAAa,CAAE,WAAA,CAAAf,GAAAA,CAAa,YAAA,CAAAC,CAAa,CAAA,CACzCe,CAAAA,CAAchB,GAAAA,CAAcC,CAAAA,CAElC,OAAAG,CAAAA,CAAU,SAAA,GAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,EAC9DM,GAAAA,CACE/B,CAAAA,CACAO,CAAAA,CACAU,CAAAA,CACAQ,CAAAA,CACAK,CAAAA,CACAD,CAAAA,CACAV,GACF,CAAA,CAEOa,CAAAA,CAAqBf,CAAAA,CAAOQ,CAAAA,CAAUK,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAclC,CAAAA,CAAOO,CAAAA,CAAOU,CAAAA,CAAOgB,CAAAA,CAAKd,GAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"anthropic.js","sourcesContent":["/**\n * @directive-run/ai/anthropic\n *\n * Anthropic adapter for Directive AI. Provides runners for the\n * Anthropic Messages API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createAnthropicRunner, createAnthropicStreamingRunner } from '@directive-run/ai/anthropic';\n *\n * const runner = createAnthropicRunner({ apiKey: process.env.ANTHROPIC_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 * Anthropic 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 { ANTHROPIC_PRICING } from '@directive-run/ai/anthropic';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].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://anthropic.com/pricing\n */\nexport const ANTHROPIC_PRICING: Record<\n string,\n { input: number; output: number }\n> = {\n \"claude-sonnet-4-5-20250929\": { input: 3, output: 15 },\n \"claude-sonnet-4-20250514\": { input: 3, output: 15 },\n \"claude-haiku-4-5-20250514\": { input: 0.8, output: 4 },\n \"claude-haiku-3-5-20241022\": { input: 0.8, output: 4 },\n \"claude-opus-4-20250514\": { input: 15, output: 75 },\n};\n\n// ============================================================================\n// Anthropic Runner\n// ============================================================================\n\n/** Options for createAnthropicRunner */\nexport interface AnthropicRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: 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 (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create an AgentRunner for the Anthropic Messages API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`${durationMs}ms – ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n */\nexport function createAnthropicRunner(\n options: AnthropicRunnerOptions,\n): AgentRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicRunner\");\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => ({\n url: `${baseURL}/messages`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\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.content?.[0]?.text ?? \"\";\n const inputTokens = data.usage?.input_tokens ?? 0;\n const outputTokens = data.usage?.output_tokens ?? 0;\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Anthropic Streaming Runner\n// ============================================================================\n\n/** Options for createAnthropicStreamingRunner */\nexport interface AnthropicStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Anthropic Messages API with\n * server-sent events. Can be used standalone or paired with `createAnthropicRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createAnthropicStreamingRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createAnthropicStreamingRunner(\n options: AnthropicStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicStreamingRunner\");\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: [{ role: \"user\", content: input }],\n stream: true,\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Anthropic\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n if (event.type === \"error\") {\n throw new Error(\n `[Directive] Anthropic stream error: ${(event.error as Record<string, unknown>)?.message ?? JSON.stringify(event.error)}`,\n );\n }\n\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n if (\n event.type === \"content_block_delta\" &&\n (event.delta as Record<string, unknown>)?.type === \"text_delta\"\n ) {\n result.text = (event.delta as Record<string, unknown>)\n .text as string;\n }\n if (event.type === \"message_delta\" && event.usage) {\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .output_tokens as number) ?? 0;\n }\n if (\n event.type === \"message_start\" &&\n (event.message as Record<string, unknown>)?.usage\n ) {\n result.inputTokens =\n ((\n (event.message as Record<string, unknown>).usage as Record<\n string,\n unknown\n >\n ).input_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"Anthropic\",\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/anthropic.ts"],"names":["ANTHROPIC_PRICING","createAnthropicRunner","options","apiKey","model","maxTokens","baseURL","fetchFn","timeoutMs","hooks","temperature","topP","stopSequences","promptCaching","validateBaseURL","warnIfMissingApiKey","createRunner","agent","_input","messages","instructions","system","m","res","data","text","inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","createAnthropicStreamingRunner","input","callbacks","startTime","fireBeforeCallHook","response","throwStreamingHTTPError","reader","getSSEReader","fullText","parseSSEStream","event","result","tokenUsage","totalTokens","fireAf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C,CACL,OACED,CAAAA,CAAM,IAAA,GAAS,qBAAA,EACdA,CAAAA,CAAM,KAAA,EAAmC,IAAA,GAAS,YAAA,GAEnDC,CAAAA,CAAO,KAAQD,CAAAA,CAAM,KAAA,CAClB,IAAA,CAAA,CAEDA,CAAAA,CAAM,IAAA,GAAS,eAAA,EAAmBA,CAAAA,CAAM,KAAA,GAC1CC,EAAO,YAAA,CACHD,CAAAA,CAAM,KAAA,CACL,aAAA,EAA4B,CAAA,CAAA,CAGjCA,CAAAA,CAAM,IAAA,GAAS,eAAA,EACdA,CAAAA,CAAM,OAAA,EAAqC,KAAA,GAE5CC,CAAAA,CAAO,WAAA,CAEFD,CAAAA,CAAM,OAAA,CAAoC,KAAA,CAI3C,cAA2B,CAAA,CAAA,CAG1BC,CACT,CAAA,CACA,WACF,CAAA,CAEMC,CAAAA,CAAa,CAAE,WAAA,CAAAjB,EAAa,YAAA,CAAAC,GAAa,CAAA,CACzCiB,CAAAA,CAAclB,CAAAA,CAAcC,GAAAA,CAElC,OAAAK,CAAAA,CAAU,YAAY,CAAE,IAAA,CAAM,WAAA,CAAa,OAAA,CAASO,CAAS,CAAC,CAAA,CAC9DM,GAAAA,CACEpC,CAAAA,CACAQ,CAAAA,CACAc,GAAAA,CACAQ,CAAAA,CACAK,CAAAA,CACAD,CAAAA,CACAV,CACF,CAAA,CAEOa,EAAqBf,GAAAA,CAAOQ,CAAAA,CAAUK,CAAAA,CAAaD,CAAU,CACtE,CAAA,MAASI,CAAAA,CAAK,CACZ,MAAAC,CAAAA,CAAcvC,CAAAA,CAAOQ,CAAAA,CAAOc,GAAAA,CAAOgB,CAAAA,CAAKd,CAAS,CAAA,CAE3Cc,CACR,CACF,CACF","file":"anthropic.js","sourcesContent":["/**\n * @directive-run/ai/anthropic\n *\n * Anthropic adapter for Directive AI. Provides runners for the\n * Anthropic Messages API, including streaming support.\n *\n * @example\n * ```typescript\n * import { createAnthropicRunner, createAnthropicStreamingRunner } from '@directive-run/ai/anthropic';\n *\n * const runner = createAnthropicRunner({ apiKey: process.env.ANTHROPIC_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 * Anthropic 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 { ANTHROPIC_PRICING } from '@directive-run/ai/anthropic';\n *\n * const cost =\n * estimateCost(result.tokenUsage!.inputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].input) +\n * estimateCost(result.tokenUsage!.outputTokens, ANTHROPIC_PRICING[\"claude-sonnet-4-5-20250929\"].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://anthropic.com/pricing\n */\nexport const ANTHROPIC_PRICING: Record<\n string,\n { input: number; output: number }\n> = {\n \"claude-sonnet-4-5-20250929\": { input: 3, output: 15 },\n \"claude-sonnet-4-20250514\": { input: 3, output: 15 },\n \"claude-haiku-4-5-20250514\": { input: 0.8, output: 4 },\n \"claude-haiku-3-5-20241022\": { input: 0.8, output: 4 },\n \"claude-opus-4-20250514\": { input: 15, output: 75 },\n};\n\n// ============================================================================\n// Anthropic Runner\n// ============================================================================\n\n/** Options for createAnthropicRunner */\nexport interface AnthropicRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: 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 (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n /**\n * Prompt caching strategy. When `\"automatic\"`, a `cache_control` breakpoint is\n * placed on the system prompt so the stable instructions prefix is cached across\n * calls – subsequent runs read it from cache instead of re-processing it. The\n * variable message suffix is never cached. Cache token usage is surfaced on\n * `tokenUsage.cacheReadTokens` / `tokenUsage.cacheCreationTokens`.\n *\n * Anthropic silently ignores `cache_control` when the cached prefix is below a\n * per-model minimum (~1024 tokens Sonnet-tier, 2048 for Sonnet-4.6 & Haiku-3.5,\n * 4096 for Opus & Haiku-4.5) – no error, no caching, and `cacheReadTokens` stays\n * 0 (that 0 is the diagnostic). Since Directive caches `agent.instructions`,\n * short instructions commonly fall below this. The `ephemeral` breakpoint has a\n * 5-minute default TTL.\n *\n * @default undefined – caching disabled (bare-string system, current behavior).\n */\n promptCaching?: \"automatic\";\n}\n\n/**\n * Create an AgentRunner for the Anthropic Messages API.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * hooks: {\n * onAfterCall: ({ durationMs, tokenUsage }) => {\n * console.log(`${durationMs}ms – ${tokenUsage.inputTokens}in/${tokenUsage.outputTokens}out`);\n * },\n * },\n * });\n * const orchestrator = createAgentOrchestrator({ runner });\n * const result = await orchestrator.run(agent, input);\n * ```\n *\n * @example Prompt caching – cache the stable instructions prefix and read the\n * cache-token breakdown back for cost tracking:\n * ```typescript\n * const runner = createAnthropicRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * promptCaching: \"automatic\",\n * });\n * const result = await orchestrator.run(agent, input);\n * // tokenUsage.cacheCreationTokens – tokens written on the first call\n * // tokenUsage.cacheReadTokens – tokens served from cache on repeat calls\n * const { inputTokens, cacheReadTokens = 0, cacheCreationTokens = 0 } =\n * result.tokenUsage!;\n * // Cache reads bill ~0.1x and cache writes ~1.25x the base input rate.\n * ```\n */\nexport function createAnthropicRunner(\n options: AnthropicRunnerOptions,\n): AgentRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n timeoutMs,\n hooks,\n temperature,\n topP,\n stopSequences,\n promptCaching,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicRunner\");\n\n return createRunner({\n fetch: fetchFn,\n hooks,\n buildRequest: (agent, _input, messages) => {\n const instructions = agent.instructions ?? \"\";\n // With prompt caching enabled, send the structured system form so a\n // `cache_control` breakpoint caches the stable instructions prefix.\n // Fall back to the bare string – byte-for-byte the prior behavior – when\n // caching is off, and also when there is nothing stable to cache: an\n // empty/whitespace-only cached block is wasteful and risks a 400.\n const system =\n promptCaching === \"automatic\" && instructions.trim() !== \"\"\n ? [\n {\n type: \"text\",\n text: instructions,\n cache_control: { type: \"ephemeral\" },\n },\n ]\n : instructions;\n\n return {\n url: `${baseURL}/messages`,\n init: {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system,\n messages: messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n }),\n ...(timeoutMs != null\n ? { signal: AbortSignal.timeout(timeoutMs) }\n : {}),\n },\n };\n },\n parseResponse: async (res) => {\n const data = await res.json();\n const text = data.content?.[0]?.text ?? \"\";\n const inputTokens = data.usage?.input_tokens ?? 0;\n const outputTokens = data.usage?.output_tokens ?? 0;\n\n // Cache-token emission is gated on the OPTION, not on the response fields:\n // the live API returns `cache_*_input_tokens: 0` on every response even\n // when no `cache_control` was sent, so keying off their presence would\n // wrongly emit `cacheReadTokens: 0` on a caching-off call. When caching is\n // on we always emit both (default 0, so a cache miss correctly reports 0);\n // when it's off we omit them entirely so `tokenUsage` is byte-identical to\n // the pre-caching behavior. `input_tokens` is the uncached remainder, so\n // cache tokens are additive – include them in `totalTokens`.\n if (promptCaching === \"automatic\") {\n const cacheReadTokens = data.usage?.cache_read_input_tokens ?? 0;\n const cacheCreationTokens =\n data.usage?.cache_creation_input_tokens ?? 0;\n\n return {\n text,\n totalTokens:\n inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheCreationTokens,\n };\n }\n\n return {\n text,\n totalTokens: inputTokens + outputTokens,\n inputTokens,\n outputTokens,\n };\n },\n });\n}\n\n// ============================================================================\n// Anthropic Streaming Runner\n// ============================================================================\n\n/** Options for createAnthropicStreamingRunner */\nexport interface AnthropicStreamingRunnerOptions {\n apiKey: string;\n model?: string;\n /** @default 4096 */\n maxTokens?: number;\n baseURL?: string;\n fetch?: typeof globalThis.fetch;\n /** Lifecycle hooks for tracing, logging, and metrics */\n hooks?: AdapterHooks;\n /** Sampling temperature (0–1). Higher = more random. */\n temperature?: number;\n /** Nucleus sampling: top-P probability mass (0–1). */\n topP?: number;\n /** Custom stop sequences. The model will stop generating when it encounters one. */\n stopSequences?: string[];\n}\n\n/**\n * Create a StreamingCallbackRunner for the Anthropic Messages API with\n * server-sent events. Can be used standalone or paired with `createAnthropicRunner`.\n *\n * Returns `tokenUsage` with input/output breakdown for cost tracking.\n *\n * @example\n * ```typescript\n * const streamingRunner = createAnthropicStreamingRunner({\n * apiKey: process.env.ANTHROPIC_API_KEY!,\n * });\n * const streamRunner = createStreamingRunner(streamingRunner);\n * const { stream, result } = streamRunner(agent, input);\n * ```\n */\nexport function createAnthropicStreamingRunner(\n options: AnthropicStreamingRunnerOptions,\n): StreamingCallbackRunner {\n const {\n apiKey,\n model = \"claude-sonnet-4-5-20250929\",\n maxTokens = 4096,\n baseURL = \"https://api.anthropic.com/v1\",\n fetch: fetchFn = globalThis.fetch,\n hooks,\n temperature,\n topP,\n stopSequences,\n } = options;\n\n validateBaseURL(baseURL);\n warnIfMissingApiKey(apiKey, \"createAnthropicStreamingRunner\");\n\n return async (agent, input, callbacks) => {\n const startTime = fireBeforeCallHook(hooks, agent, input);\n\n try {\n const response = await fetchFn(`${baseURL}/messages`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify({\n model: agent.model ?? model,\n max_tokens: maxTokens,\n ...(temperature != null ? { temperature } : {}),\n ...(topP != null ? { top_p: topP } : {}),\n ...(stopSequences != null ? { stop_sequences: stopSequences } : {}),\n system: agent.instructions ?? \"\",\n messages: [{ role: \"user\", content: input }],\n stream: true,\n }),\n signal: callbacks.signal,\n });\n\n if (!response.ok) {\n await throwStreamingHTTPError(response, \"Anthropic\");\n }\n\n const reader = getSSEReader(response);\n\n const { fullText, inputTokens, outputTokens } = await parseSSEStream(\n reader,\n callbacks.onToken,\n (event) => {\n if (event.type === \"error\") {\n throw new Error(\n `[Directive] Anthropic stream error: ${(event.error as Record<string, unknown>)?.message ?? JSON.stringify(event.error)}`,\n );\n }\n\n const result: {\n text?: string;\n inputTokens?: number;\n outputTokens?: number;\n } = {};\n if (\n event.type === \"content_block_delta\" &&\n (event.delta as Record<string, unknown>)?.type === \"text_delta\"\n ) {\n result.text = (event.delta as Record<string, unknown>)\n .text as string;\n }\n if (event.type === \"message_delta\" && event.usage) {\n result.outputTokens =\n ((event.usage as Record<string, unknown>)\n .output_tokens as number) ?? 0;\n }\n if (\n event.type === \"message_start\" &&\n (event.message as Record<string, unknown>)?.usage\n ) {\n result.inputTokens =\n ((\n (event.message as Record<string, unknown>).usage as Record<\n string,\n unknown\n >\n ).input_tokens as number) ?? 0;\n }\n\n return result;\n },\n \"Anthropic\",\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,4 +1,4 @@
|
|
|
1
|
-
'use strict';var chunkK64WKZ22_cjs=require('./chunk-K64WKZ22.cjs'),internals=require('@directive-run/core/internals');function le(a){let{patterns:r=[/\b\d{3}-\d{2}-\d{4}\b/g,/\b\d{16}\b/g,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi],redact:i=false,redactReplacement:t="[REDACTED]"}=a;return e=>{let n=e.input,s=false;for(let c of r)c.lastIndex=0,c.test(n)&&(s=true,i&&(c.lastIndex=0,n=n.replace(c,t)));return s&&!i?{passed:false,reason:"Input contains PII"}:{passed:true,transformed:i&&s?n:void 0}}}function ue(a){let{checkFn:r,message:i="Content flagged by moderation"}=a;return async t=>{let e="output"in t?typeof t.output=="string"?t.output:JSON.stringify(t.output):t.input,n=await r(e);return {passed:!n,reason:n?i:void 0}}}function me(a){let{maxTokensPerMinute:r=1e5,maxRequestsPerMinute:i=60}=a,t=Math.max(i,1e3),e=[],n=[],s=6e4;function c(d,u){let m=0,x=d.length;for(;m<x;){let p=m+x>>>1;(d[p]??0)<u?m=p+1:x=p;}return m}let o=(d,u)=>{let m=Date.now(),x=m-s,p=c(e,x);p>0&&(e=e.slice(p));let S=c(n,x);S>0&&(n=n.slice(S));let v=u.facts[chunkK64WKZ22_cjs.c]?.tokenUsage??0,I=e.length,T=n.length;return I+v>r?{passed:false,reason:"Token rate limit exceeded"}:T>=i?{passed:false,reason:"Request rate limit exceeded"}:(n.length<t&&n.push(m),e.length<t&&e.push(m),{passed:true})};return o.reset=()=>{e=[],n=[];},o}function fe(a){let{allowlist:r,denylist:i,caseSensitive:t=false}=a,e=r?.map(s=>t?s:s.toLowerCase()),n=i?.map(s=>t?s:s.toLowerCase());return s=>{let c=t?s.toolCall.name:s.toolCall.name.toLowerCase();return e&&!e.includes(c)?{passed:false,reason:`Tool "${s.toolCall.name}" not in allowlist`}:n?.includes(c)?{passed:false,reason:`Tool "${s.toolCall.name}" is blocked`}:{passed:true}}}function pe(a){let{validate:r,errorPrefix:i="Output schema validation failed"}=a;return t=>{let e=r(t.output);return typeof e=="boolean"?{passed:e,reason:e?void 0:i}:e.valid?{passed:true}:{passed:false,reason:e.errors?.length?`${i}: ${e.errors.join("; ")}`:i}}}function ge(a){let{type:r,requiredFields:i=[],minLength:t,maxLength:e,minStringLength:n,maxStringLength:s}=a;return c=>{let o=c.output;switch(r){case "string":return typeof o!="string"?{passed:false,reason:`Expected string, got ${typeof o}`}:n!==void 0&&o.length<n?{passed:false,reason:`String too short: ${o.length} < ${n}`}:s!==void 0&&o.length>s?{passed:false,reason:`String too long: ${o.length} > ${s}`}:{passed:true};case "number":return typeof o!="number"||Number.isNaN(o)?{passed:false,reason:`Expected number, got ${typeof o}`}:{passed:true};case "boolean":return typeof o!="boolean"?{passed:false,reason:`Expected boolean, got ${typeof o}`}:{passed:true};case "object":if(typeof o!="object"||o===null||Array.isArray(o))return {passed:false,reason:`Expected object, got ${Array.isArray(o)?"array":typeof o}`};for(let d of i)if(!(d in o))return {passed:false,reason:`Missing required field: ${d}`};return {passed:true};case "array":return Array.isArray(o)?t!==void 0&&o.length<t?{passed:false,reason:`Array too short: ${o.length} < ${t}`}:e!==void 0&&o.length>e?{passed:false,reason:`Array too long: ${o.length} > ${e}`}:{passed:true}:{passed:false,reason:`Expected array, got ${typeof o}`};default:return {passed:false,reason:`Unknown type: ${r}`}}}}function ye(a){let{maxCharacters:r,maxTokens:i,estimateTokens:t=e=>Math.ceil(e.length/4)}=a;return e=>{let n=internals.safeStringify(e.output);if(r!==void 0&&n.length>r)return {passed:false,reason:`Output too long: ${n.length} characters (max: ${r})`};if(i!==void 0){let s=t(n);if(s>i)return {passed:false,reason:`Output too long: ~${s} tokens (max: ${i})`}}return {passed:true}}}function he(a){let{blockedPatterns:r,caseSensitive:i=false}=a;r.length===0&&console.warn("[Directive] createContentFilterGuardrail: blockedPatterns is empty \u2014 no content will be filtered");let t=r.map(e=>{if(e instanceof RegExp)return e;let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(n,i?"g":"gi")});return e=>{let n=internals.safeStringify(e.output);for(let s of t)if(s.lastIndex=0,s.test(n))return {passed:false,reason:`Output contains blocked content matching: ${s.source}`};return {passed:true}}}function U(a){let r=a.replace(/[\s-]/g,"");if(r.length<13||r.length>19||!/^\d+$/.test(r))return false;let i=0,t=false;for(let e=r.length-1;e>=0;e--){let n=r[e];if(!n)continue;let s=Number.parseInt(n,10);t&&(s*=2,s>9&&(s-=9)),i+=s,t=!t;}return i%10===0}var Z=[{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g,redactionToken:"[SSN]"},{type:"credit_card",regex:/\b((?:\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|\d{13,19})\b/g,validate:U,redactionToken:"[CREDIT_CARD]"},{type:"email",regex:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,redactionToken:"[EMAIL]"}];function q(a,r){let i=[];for(let t of Z){if(!r.has(t.type))continue;t.regex.lastIndex=0;let e;for(;(e=t.regex.exec(a))!==null;)t.validate&&!t.validate(e[0])||i.push({type:t.type,value:e[0],start:e.index,end:e.index+e[0].length});}return i}function A(a,r){if(r.length===0)return a;let i=[...r].sort((n,s)=>s.start-n.start),t={ssn:"[SSN]",credit_card:"[CREDIT_CARD]",email:"[EMAIL]"},e=a;for(let n of i)e=e.slice(0,n.start)+t[n.type]+e.slice(n.end);return e}function Ie(a={}){let{mode:r="redact",types:i=["ssn","credit_card","email"],includeKeys:t=[],excludeKeys:e=[],onBlocked:n,customDetector:s,walkDepth:c=4,errorMode:o=r==="redact"?"redact":"alert-only"}=a,d=new Set(i),u=new Set(t),m=new Set(e),x=Number.isFinite(c)?Math.max(1,Math.min(5,Math.floor(c))):1,p=1e4,S=false,g=null;function w(l){if(S)return;S=true,g=l;let f=l.meta?.byTag?.("pii");if(f)for(let h of f)h.type==="fact"&&h.id&&!m.has(h.id)&&u.add(h.id);}function v(l,f){let h=typeof l.message=="string"?l.message:"",b=A(h,f),y=new Error(b);return typeof l.name=="string"&&l.name!=="Error"&&Object.defineProperty(y,"name",{value:l.name,configurable:true,writable:true}),y}function I(l){let f=[];if(d.size>0)for(let h of q(l,d))f.push(h);if(s)for(let h of s(l))f.push(h);return f}function T(l,f=x){if(typeof l=="string"){let y=I(l);return y.length===0?{matched:false}:{matched:true,redacted:A(l,y),detected:y}}if(f<=0)return {matched:false};if(l===null||typeof l!="object")return {matched:false};let h=l;if(Array.isArray(l)){let y=l.length,E=Number.isFinite(y)&&y>0?Math.min(Math.floor(y),p):0;y>p&&console.warn(`[Directive] fact-pii walker truncated top-level array at ${p} elements before clone \u2014 pass a customDetector for larger payloads`);let P=new Array(E);for(let R=0;R<E;R++)P[R]=l[R];h=P;}let b;try{b=structuredClone(h);}catch(y){return console.warn("[Directive] fact-pii walker: value is not structured-cloneable \u2014 leaving it as-is and skipping inspection. Wire a customDetector for shapes containing functions, DOM nodes, cycles, or WeakMaps.",y instanceof Error?y.message:String(y)),{matched:false}}return C(b,f)}function C(l,f){if(typeof l=="string"){let h=I(l);return h.length===0?{matched:false}:{matched:true,redacted:A(l,h),detected:h}}if(f<=0)return {matched:false};if(Array.isArray(l)){l.length>p&&console.warn(`[Directive] fact-pii walker truncated array at ${p} elements \u2014 pass a customDetector for larger payloads`);let h=Math.min(l.length,p),b=null,y=[];for(let E=0;E<h;E++){let P=C(l[E],f-1);if(P.matched){b===null&&(b=[...l]),b[E]=P.redacted;for(let R of P.detected)y.push(R);}}return b===null?{matched:false}:{matched:true,redacted:b,detected:y}}if(l&&typeof l=="object"){if(l instanceof Map||l instanceof Set||l instanceof Date||l instanceof RegExp||l instanceof Error||ArrayBuffer.isView(l)||l instanceof ArrayBuffer||typeof Blob<"u"&&l instanceof Blob){if(l instanceof Error){let y=[];if(typeof l.message=="string")for(let E of I(l.message))y.push(E);if(typeof l.cause=="string")for(let E of I(l.cause))y.push(E);else if(l.cause instanceof Error&&f>1){let E=C(l.cause,f-1);if(E.matched)for(let P of E.detected)y.push(P);}if(typeof AggregateError<"u"&&l instanceof AggregateError&&Array.isArray(l.errors)&&f>1){for(let E of l.errors)if(typeof E=="string")for(let P of I(E))y.push(P);else if(E instanceof Error){let P=C(E,f-1);if(P.matched)for(let R of P.detected)y.push(R);}}if(y.length>0)return {matched:true,redacted:o==="redact"?v(l,y):l,detected:y}}return {matched:false}}let h=null,b=[];for(let[y,E]of Object.entries(l))if(typeof E=="string"){let P=I(E);if(P.length===0)continue;h===null&&(h={...l}),h[y]=A(E,P);for(let R of P)b.push(R);}else if(f>1&&E&&typeof E=="object"){let P=C(E,f-1);if(!P.matched)continue;h===null&&(h={...l}),h[y]=P.redacted;for(let R of P.detected)b.push(R);}return h===null?{matched:false}:{matched:true,redacted:h,detected:b}}return {matched:false}}return {name:"fact-pii-guardrail",onInit(l){w(l);},onFactSet(l,f,h){if(!S||!u.has(l)||f===h&&(typeof f!="object"||f===null))return;let b=T(f);if(!b.matched)return;n?.(l,b.detected,r);let y=r==="alert"||o==="alert-only"&&f instanceof Error?"alert":b.redacted===f?"detect":"redact";if(g?.notify?.guardrailBlocked?.("fact-pii-guardrail",l,y,b.detected.length,b.detected[0]?.type),r==="alert"||b.redacted===f)return;let P=g?.facts;if(P?.$store?.set)try{P.$store.set(l,b.redacted);}catch(R){console.warn("[Directive] guardrail redact write failed",{plugin:"fact-pii-guardrail",key:l,phase:"onFactSet",error:R});}},onFactsBatch(l){if(S)for(let f of l){if(f.type!=="set"||!u.has(f.key))continue;let h=f.prev;if(f.value===h&&(typeof f.value!="object"||f.value===null))continue;let b=T(f.value);if(!b.matched)continue;n?.(f.key,b.detected,r);let y=r==="alert"||o==="alert-only"&&f.value instanceof Error?"alert":b.redacted===f.value?"detect":"redact";if(g?.notify?.guardrailBlocked?.("fact-pii-guardrail",f.key,y,b.detected.length,b.detected[0]?.type),r==="alert"||b.redacted===f.value)continue;try{f.value=b.redacted;}catch{}let P=g?.facts;if(P?.$store?.set)try{P.$store.set(f.key,b.redacted);}catch(R){console.warn("[Directive] guardrail redact write failed",{plugin:"fact-pii-guardrail",key:f.key,phase:"onFactsBatch",error:R});}}}}}var K=[{type:"ssn",pattern:/\b(\d{3}[-\s]?\d{2}[-\s]?\d{4})\b/g,validate:a=>{let r=a.replace(/[-\s]/g,"");return !(r.startsWith("000")||r.startsWith("666")||r.startsWith("9")||r.slice(3,5)==="00"||r.slice(5)==="0000")},confidence:.95},{type:"credit_card",pattern:/\b((?:\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|\d{13,19})\b/g,validate:a=>{let r=a.replace(/[-\s]/g,"");if(r.length<13||r.length>19)return false;let i=0,t=false;for(let e=r.length-1;e>=0;e--){let n=r[e];if(!n)continue;let s=Number.parseInt(n,10);t&&(s*=2,s>9&&(s-=9)),i+=s,t=!t;}return i%10===0},confidence:.95},{type:"email",pattern:/\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})\b/gi,confidence:.9},{type:"phone",pattern:/\b(\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4})\b/g,validate:a=>{let r=a.replace(/\D/g,"");return r.length>=10&&r.length<=11},confidence:.8},{type:"date_of_birth",pattern:/\b(born|dob|birth.?date|date.?of.?birth)[:.\s]+(\d{1,4}[-/]\d{1,2}[-/]\d{1,4})\b/gi,valueGroup:2,confidence:.85},{type:"ip_address",pattern:/\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/g,validate:a=>{let i=a.split(".").map(n=>Number.parseInt(n,10));if(i.some(n=>Number.isNaN(n)||n<0||n>255))return false;let[t,e]=i;return !(t===10||t===172&&e>=16&&e<=31||t===192&&e===168||t===127||t===169&&e===254||a==="0.0.0.0"||a==="255.255.255.255")},confidence:.9},{type:"bank_account",pattern:/\b(account|acct)[\s#:]+(\d{8,17})\b/gi,valueGroup:2,confidence:.7},{type:"passport",pattern:/\b(passport)[\s#:]+([A-Z0-9]{6,9})\b/gi,valueGroup:2,confidence:.75},{type:"driver_license",pattern:/\b(driver'?s?\s*licen[cs]e|dl)[\s#:]+([A-Z0-9]{5,15})\b/gi,valueGroup:2,confidence:.7},{type:"medical_id",pattern:/\b(mrn|medical.?record|patient.?id)[\s#:]+([A-Z0-9-]{6,15})\b/gi,valueGroup:2,confidence:.7},{type:"national_id",pattern:/\b(national.?id|nin|identity.?number|identity.?card|id.?number)[\s#:]+([A-Z0-9-]{6,20})\b/gi,valueGroup:2,confidence:.85}];function W(a){let r=[],i="street|st|avenue|ave|road|rd|drive|dr|lane|ln|court|ct|way|boulevard|blvd|circle|cir|place|pl",t=new RegExp(`\\b(\\d{1,5}\\s+(?:\\w+\\s+){1,4}(?:${i})\\b[^\\n]{0,50}\\b[A-Z]{2}\\s+\\d{5}(?:-\\d{4})?)\\b`,"gi"),e;for(;(e=t.exec(a))!==null;)r.push({type:"address",value:e[0],position:{start:e.index,end:e.index+e[0].length},confidence:.7});return r}var $=["mr","mrs","ms","miss","dr","prof","sir","madam","name is","called","known as","signed by","from","dear","hi","hello","contact","recipient"];function Y(a){let r=[],i=$.join("|"),t=new RegExp(`\\b(${i})[.,:]?\\s+([A-Z][a-z]{1,20}(?:\\s[A-Z][a-z]{1,20}){0,2})\\b`,"gi"),e;for(;(e=t.exec(a))!==null;){let n=e[2],s=e[1];n&&(n.split(/\s+/).length>=2||s&&$.some(c=>s.toLowerCase().includes(c)))&&r.push({type:"name",value:n,position:{start:e.index,end:e.index+e[0].length},confidence:.6,context:e[0]});}return r}var j=1e5;function J(a,r){let i=[],t=new RegExp(a.pattern.source,a.pattern.flags),e=a.valueGroup??1,n;for(;(n=t.exec(r))!==null;){let s=n[e]??n[0],c=n.index,o=n.index+n[0].length,d=r.slice(Math.max(0,c-20),o+20);a.validate&&!a.validate(s,d)||i.push({type:a.type,value:s,position:{start:c,end:o},confidence:a.confidence,context:d});}return i}var N={name:"regex",async detect(a,r){if(a.length>j)throw new Error(`[Directive] Input exceeds maximum length of ${j} characters for PII detection. Truncate input or process in chunks.`);let i=[],t=new Set(r);for(let e of K)t.has(e.type)&&i.push(...J(e,a));return t.has("address")&&i.push(...W(a)),t.has("name")&&i.push(...Y(a)),i}},X=new Set(["ssn","credit_card","date_of_birth","medical_id","national_id","passport","driver_license","bank_account"]);function Q(a,r){let{start:i,end:t}=a.position;return Number.isInteger(i)&&Number.isInteger(t)&&i>=0&&i<t&&t<=r}function ee(a,r){switch(r){case "placeholder":return "[REDACTED]";case "typed":return X.has(a.type)?"[REDACTED]":`[${a.type.toUpperCase()}]`;case "masked":{if(a.type!=="credit_card")return "****";let i=a.value.replace(/\D/g,"");return `****${i.length>4?i.slice(-4):""}`}case "hashed":return `[HASH:${te(a.value)}]`}}function O(a,r,i="typed"){let e=[...r.filter(o=>Q(o,a.length))].sort((o,d)=>{if(d.confidence!==o.confidence)return d.confidence-o.confidence;let u=o.position.end-o.position.start,m=d.position.end-d.position.start;return m!==u?m-u:o.position.start-d.position.start}),n=[];for(let o of e)n.some(u=>o.position.start<u.position.end&&u.position.start<o.position.end)||n.push(o);let s=n.sort((o,d)=>d.position.start-o.position.start),c=a;for(let o of s){let d=ee(o,i);c=c.slice(0,o.position.start)+d+c.slice(o.position.end);}return c}function te(a){let t=2166136261;for(let e=0;e<a.length;e++)t^=a.charCodeAt(e),t=Math.imul(t,16777619);return (t>>>0).toString(16).padStart(8,"0")}var B=["ssn","credit_card","email","phone","date_of_birth","bank_account"];function ne(a={}){let{types:r=B,detector:i="regex",redact:t=false,redactionStyle:e="typed",minConfidence:n=.7,onDetected:s,allowlist:c=[],minItemsToBlock:o=1,detectorTimeout:d=5e3}=a,u=i==="regex"?N:i,m=new Set(c.map(p=>p.toLowerCase().trim()));async function x(p,S){if(u===N)return u.detect(p,S);let g,w=u.detect(p,S),v=new Promise((I,T)=>{g=setTimeout(()=>T(new Error(`[Directive] PII detector '${u.name}' timed out after ${d}ms`)),d);});w.catch(()=>{}),v.catch(()=>{});try{return await Promise.race([w,v])}finally{clearTimeout(g);}}return async p=>{let g=(await x(p.input,r)).filter(w=>!(w.confidence<n||m.has(w.value.toLowerCase().trim())));if(g.length>0&&s?.(g),g.length>=o){if(t)return {passed:true,transformed:O(p.input,g,e)};let w={};for(let I of g)w[I.type]=(w[I.type]||0)+1;return {passed:false,reason:`PII detected (${Object.entries(w).map(([I,T])=>`${I}: ${T}`).join(", ")})`}}return {passed:true}}}function Pe(a={}){let r=ne(a);return async(i,t)=>{let e=typeof i.output=="string"?i.output:JSON.stringify(i.output);return r({input:e,agentName:i.agentName},t)}}async function re(a,r={}){let{types:i=B,detector:t="regex",minConfidence:e=.7,timeout:n=5e3}=r,s=t==="regex"?N:t,c;if(s===N)c=await s.detect(a,i);else {let u,m=s.detect(a,i),x=new Promise((p,S)=>{u=setTimeout(()=>S(new Error(`[Directive] PII detector '${s.name}' timed out after ${n}ms`)),n);});m.catch(()=>{}),x.catch(()=>{});try{c=await Promise.race([m,x]);}finally{clearTimeout(u);}}let o=c.filter(u=>u.confidence>=e),d={};for(let u of o)d[u.type]=(d[u.type]||0)+1;return {detected:o.length>0,items:o,typeCounts:d}}async function xe(a,r={}){let i=await re(a,r);return i.detected?{...i,redactedText:O(a,i.items,r.style??"typed")}:{...i}}var M=[{pattern:/ignore\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?|rules?|guidelines?)/i,name:"ignore-previous",severity:"critical",category:"instruction_override"},{pattern:/disregard\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?)/i,name:"disregard-previous",severity:"critical",category:"instruction_override"},{pattern:/forget\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?)/i,name:"forget-previous",severity:"critical",category:"instruction_override"},{pattern:/override\s+(the\s+)?(system|base)\s+(prompt|instructions?)/i,name:"override-system",severity:"critical",category:"instruction_override"},{pattern:/\bDAN\s+(mode|jailbreak)\b/i,name:"dan-mode",severity:"critical",category:"jailbreak"},{pattern:/\bjailbreak(ed)?\s*(mode)?\b/i,name:"jailbreak-keyword",severity:"high",category:"jailbreak"},{pattern:/developer\s+mode\s+(enabled|activated|on)/i,name:"developer-mode",severity:"critical",category:"jailbreak"},{pattern:/pretend\s+(you\s+)?(are|can|have)\s+(no\s+)?(restrictions?|limits?|boundaries?|ethics)/i,name:"pretend-no-restrictions",severity:"high",category:"jailbreak"},{pattern:/you\s+(now\s+)?have\s+no\s+(ethical\s+)?(restrictions?|guidelines?|boundaries?)/i,name:"no-restrictions",severity:"high",category:"jailbreak"},{pattern:/you\s+are\s+now\s+(a|an)\s+\w+\s+(that|who)\s+(can|will|must)/i,name:"role-assignment",severity:"medium",category:"role_manipulation"},{pattern:/from\s+now\s+on,?\s+(you\s+)?(will|must|should)\s+(only\s+)?/i,name:"from-now-on",severity:"medium",category:"role_manipulation"},{pattern:/^(system|assistant|user):\s*/im,name:"fake-role-marker",severity:"high",category:"context_manipulation"},{pattern:/<\|?(system|endofprompt|im_start|im_end)\|?>/i,name:"special-token-injection",severity:"critical",category:"context_manipulation"},{pattern:/```(system|assistant|instructions?)\n/i,name:"markdown-code-injection",severity:"medium",category:"delimiter_injection"},{pattern:/<system>|<\/system>|<instructions?>|<\/instructions?>/i,name:"xml-tag-injection",severity:"high",category:"delimiter_injection"},{pattern:/fetch\s+(content\s+)?(from|at)\s+(the\s+)?url/i,name:"url-fetch-instruction",severity:"medium",category:"indirect_injection"},{pattern:/execute\s+(the\s+)?(code|script|command)\s+(from|in|at)/i,name:"execute-from-source",severity:"high",category:"indirect_injection"}],z=[...M,{pattern:/act\s+as\s+(if\s+)?(you\s+)?(were|are|can)/i,name:"act-as",severity:"low",category:"role_manipulation"},{pattern:/new\s+instructions?:/i,name:"new-instructions",severity:"medium",category:"instruction_override"},{pattern:/\[system\]|\[admin\]|\[developer\]/i,name:"bracket-role-marker",severity:"medium",category:"context_manipulation"},{pattern:/base64|rot13|decode\s+(this|the)/i,name:"encoding-reference",severity:"low",category:"encoding_evasion"},{pattern:/\u200b|\u200c|\u200d|\u2060|\ufeff/,name:"zero-width-chars",severity:"medium",category:"encoding_evasion"}],L=1e5;function H(a,r=M){if(a.length>L)throw new Error(`[Directive] Input exceeds maximum length of ${L} characters for injection detection. Truncate input or process in chunks.`);let i=[];for(let{pattern:s,name:c,severity:o,category:d}of r){let m=new RegExp(s.source,s.flags).exec(a);m&&i.push({name:c,category:d,severity:o,match:m[0],position:m.index});}let t={low:10,medium:25,high:50,critical:100},e=i.reduce((s,c)=>s+t[c.severity],0),n=Math.min(100,e);return {detected:i.length>0,patterns:i,riskScore:n}}function ie(a,r=M){let i=a.replace(/\u200b|\u200c|\u200d|\u2060|\ufeff/g,""),t=r.map(d=>`(${d.pattern.source})`);if(t.length===0)return i;let e=r.some(d=>d.pattern.flags.includes("g")),n=r.some(d=>d.pattern.flags.includes("i")),s=r.some(d=>d.pattern.flags.includes("m")),c=`${e?"g":""}${n?"i":""}${s?"m":""}`,o=new RegExp(t.join("|"),c||"gi");return i=i.replace(o,"[REDACTED]"),i}function ae(a={}){let{additionalPatterns:r=[],replacePatterns:i,strictMode:t=false,blockThreshold:e=50,sanitize:n=false,onBlocked:s,ignoreCategories:c=[]}=a,o;if(i?o=i:o=t?[...z]:[...M],o=[...o,...r],c.length>0){let d=new Set(c);o=o.filter(u=>!d.has(u.category));}return d=>{let u=H(d.input,o);if(u.detected&&u.riskScore>=e){if(s?.(d.input,u),n)return {passed:true,transformed:ie(d.input,o)};let m=u.patterns.sort((x,p)=>{let S={critical:0,high:1,medium:2,low:3};return S[x.severity]-S[p.severity]}).slice(0,3).map(x=>x.name).join(", ");return {passed:false,reason:`Prompt injection detected (risk: ${u.riskScore}%, patterns: ${m})`}}return {passed:true}}}function ve(a,r){return `[UNTRUSTED_CONTENT source="${r}"]
|
|
1
|
+
'use strict';var chunkAEX7HKNM_cjs=require('./chunk-AEX7HKNM.cjs'),internals=require('@directive-run/core/internals');function le(a){let{patterns:r=[/\b\d{3}-\d{2}-\d{4}\b/g,/\b\d{16}\b/g,/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi],redact:i=false,redactReplacement:t="[REDACTED]"}=a;return e=>{let n=e.input,s=false;for(let c of r)c.lastIndex=0,c.test(n)&&(s=true,i&&(c.lastIndex=0,n=n.replace(c,t)));return s&&!i?{passed:false,reason:"Input contains PII"}:{passed:true,transformed:i&&s?n:void 0}}}function ue(a){let{checkFn:r,message:i="Content flagged by moderation"}=a;return async t=>{let e="output"in t?typeof t.output=="string"?t.output:JSON.stringify(t.output):t.input,n=await r(e);return {passed:!n,reason:n?i:void 0}}}function me(a){let{maxTokensPerMinute:r=1e5,maxRequestsPerMinute:i=60}=a,t=Math.max(i,1e3),e=[],n=[],s=6e4;function c(d,u){let m=0,x=d.length;for(;m<x;){let p=m+x>>>1;(d[p]??0)<u?m=p+1:x=p;}return m}let o=(d,u)=>{let m=Date.now(),x=m-s,p=c(e,x);p>0&&(e=e.slice(p));let S=c(n,x);S>0&&(n=n.slice(S));let v=u.facts[chunkAEX7HKNM_cjs.c]?.tokenUsage??0,I=e.length,T=n.length;return I+v>r?{passed:false,reason:"Token rate limit exceeded"}:T>=i?{passed:false,reason:"Request rate limit exceeded"}:(n.length<t&&n.push(m),e.length<t&&e.push(m),{passed:true})};return o.reset=()=>{e=[],n=[];},o}function fe(a){let{allowlist:r,denylist:i,caseSensitive:t=false}=a,e=r?.map(s=>t?s:s.toLowerCase()),n=i?.map(s=>t?s:s.toLowerCase());return s=>{let c=t?s.toolCall.name:s.toolCall.name.toLowerCase();return e&&!e.includes(c)?{passed:false,reason:`Tool "${s.toolCall.name}" not in allowlist`}:n?.includes(c)?{passed:false,reason:`Tool "${s.toolCall.name}" is blocked`}:{passed:true}}}function pe(a){let{validate:r,errorPrefix:i="Output schema validation failed"}=a;return t=>{let e=r(t.output);return typeof e=="boolean"?{passed:e,reason:e?void 0:i}:e.valid?{passed:true}:{passed:false,reason:e.errors?.length?`${i}: ${e.errors.join("; ")}`:i}}}function ge(a){let{type:r,requiredFields:i=[],minLength:t,maxLength:e,minStringLength:n,maxStringLength:s}=a;return c=>{let o=c.output;switch(r){case "string":return typeof o!="string"?{passed:false,reason:`Expected string, got ${typeof o}`}:n!==void 0&&o.length<n?{passed:false,reason:`String too short: ${o.length} < ${n}`}:s!==void 0&&o.length>s?{passed:false,reason:`String too long: ${o.length} > ${s}`}:{passed:true};case "number":return typeof o!="number"||Number.isNaN(o)?{passed:false,reason:`Expected number, got ${typeof o}`}:{passed:true};case "boolean":return typeof o!="boolean"?{passed:false,reason:`Expected boolean, got ${typeof o}`}:{passed:true};case "object":if(typeof o!="object"||o===null||Array.isArray(o))return {passed:false,reason:`Expected object, got ${Array.isArray(o)?"array":typeof o}`};for(let d of i)if(!(d in o))return {passed:false,reason:`Missing required field: ${d}`};return {passed:true};case "array":return Array.isArray(o)?t!==void 0&&o.length<t?{passed:false,reason:`Array too short: ${o.length} < ${t}`}:e!==void 0&&o.length>e?{passed:false,reason:`Array too long: ${o.length} > ${e}`}:{passed:true}:{passed:false,reason:`Expected array, got ${typeof o}`};default:return {passed:false,reason:`Unknown type: ${r}`}}}}function ye(a){let{maxCharacters:r,maxTokens:i,estimateTokens:t=e=>Math.ceil(e.length/4)}=a;return e=>{let n=internals.safeStringify(e.output);if(r!==void 0&&n.length>r)return {passed:false,reason:`Output too long: ${n.length} characters (max: ${r})`};if(i!==void 0){let s=t(n);if(s>i)return {passed:false,reason:`Output too long: ~${s} tokens (max: ${i})`}}return {passed:true}}}function he(a){let{blockedPatterns:r,caseSensitive:i=false}=a;r.length===0&&console.warn("[Directive] createContentFilterGuardrail: blockedPatterns is empty \u2014 no content will be filtered");let t=r.map(e=>{if(e instanceof RegExp)return e;let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(n,i?"g":"gi")});return e=>{let n=internals.safeStringify(e.output);for(let s of t)if(s.lastIndex=0,s.test(n))return {passed:false,reason:`Output contains blocked content matching: ${s.source}`};return {passed:true}}}function U(a){let r=a.replace(/[\s-]/g,"");if(r.length<13||r.length>19||!/^\d+$/.test(r))return false;let i=0,t=false;for(let e=r.length-1;e>=0;e--){let n=r[e];if(!n)continue;let s=Number.parseInt(n,10);t&&(s*=2,s>9&&(s-=9)),i+=s,t=!t;}return i%10===0}var Z=[{type:"ssn",regex:/\b\d{3}-\d{2}-\d{4}\b/g,redactionToken:"[SSN]"},{type:"credit_card",regex:/\b((?:\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|\d{13,19})\b/g,validate:U,redactionToken:"[CREDIT_CARD]"},{type:"email",regex:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,redactionToken:"[EMAIL]"}];function q(a,r){let i=[];for(let t of Z){if(!r.has(t.type))continue;t.regex.lastIndex=0;let e;for(;(e=t.regex.exec(a))!==null;)t.validate&&!t.validate(e[0])||i.push({type:t.type,value:e[0],start:e.index,end:e.index+e[0].length});}return i}function A(a,r){if(r.length===0)return a;let i=[...r].sort((n,s)=>s.start-n.start),t={ssn:"[SSN]",credit_card:"[CREDIT_CARD]",email:"[EMAIL]"},e=a;for(let n of i)e=e.slice(0,n.start)+t[n.type]+e.slice(n.end);return e}function Ie(a={}){let{mode:r="redact",types:i=["ssn","credit_card","email"],includeKeys:t=[],excludeKeys:e=[],onBlocked:n,customDetector:s,walkDepth:c=4,errorMode:o=r==="redact"?"redact":"alert-only"}=a,d=new Set(i),u=new Set(t),m=new Set(e),x=Number.isFinite(c)?Math.max(1,Math.min(5,Math.floor(c))):1,p=1e4,S=false,g=null;function w(l){if(S)return;S=true,g=l;let f=l.meta?.byTag?.("pii");if(f)for(let h of f)h.type==="fact"&&h.id&&!m.has(h.id)&&u.add(h.id);}function v(l,f){let h=typeof l.message=="string"?l.message:"",b=A(h,f),y=new Error(b);return typeof l.name=="string"&&l.name!=="Error"&&Object.defineProperty(y,"name",{value:l.name,configurable:true,writable:true}),y}function I(l){let f=[];if(d.size>0)for(let h of q(l,d))f.push(h);if(s)for(let h of s(l))f.push(h);return f}function T(l,f=x){if(typeof l=="string"){let y=I(l);return y.length===0?{matched:false}:{matched:true,redacted:A(l,y),detected:y}}if(f<=0)return {matched:false};if(l===null||typeof l!="object")return {matched:false};let h=l;if(Array.isArray(l)){let y=l.length,E=Number.isFinite(y)&&y>0?Math.min(Math.floor(y),p):0;y>p&&console.warn(`[Directive] fact-pii walker truncated top-level array at ${p} elements before clone \u2014 pass a customDetector for larger payloads`);let P=new Array(E);for(let R=0;R<E;R++)P[R]=l[R];h=P;}let b;try{b=structuredClone(h);}catch(y){return console.warn("[Directive] fact-pii walker: value is not structured-cloneable \u2014 leaving it as-is and skipping inspection. Wire a customDetector for shapes containing functions, DOM nodes, cycles, or WeakMaps.",y instanceof Error?y.message:String(y)),{matched:false}}return C(b,f)}function C(l,f){if(typeof l=="string"){let h=I(l);return h.length===0?{matched:false}:{matched:true,redacted:A(l,h),detected:h}}if(f<=0)return {matched:false};if(Array.isArray(l)){l.length>p&&console.warn(`[Directive] fact-pii walker truncated array at ${p} elements \u2014 pass a customDetector for larger payloads`);let h=Math.min(l.length,p),b=null,y=[];for(let E=0;E<h;E++){let P=C(l[E],f-1);if(P.matched){b===null&&(b=[...l]),b[E]=P.redacted;for(let R of P.detected)y.push(R);}}return b===null?{matched:false}:{matched:true,redacted:b,detected:y}}if(l&&typeof l=="object"){if(l instanceof Map||l instanceof Set||l instanceof Date||l instanceof RegExp||l instanceof Error||ArrayBuffer.isView(l)||l instanceof ArrayBuffer||typeof Blob<"u"&&l instanceof Blob){if(l instanceof Error){let y=[];if(typeof l.message=="string")for(let E of I(l.message))y.push(E);if(typeof l.cause=="string")for(let E of I(l.cause))y.push(E);else if(l.cause instanceof Error&&f>1){let E=C(l.cause,f-1);if(E.matched)for(let P of E.detected)y.push(P);}if(typeof AggregateError<"u"&&l instanceof AggregateError&&Array.isArray(l.errors)&&f>1){for(let E of l.errors)if(typeof E=="string")for(let P of I(E))y.push(P);else if(E instanceof Error){let P=C(E,f-1);if(P.matched)for(let R of P.detected)y.push(R);}}if(y.length>0)return {matched:true,redacted:o==="redact"?v(l,y):l,detected:y}}return {matched:false}}let h=null,b=[];for(let[y,E]of Object.entries(l))if(typeof E=="string"){let P=I(E);if(P.length===0)continue;h===null&&(h={...l}),h[y]=A(E,P);for(let R of P)b.push(R);}else if(f>1&&E&&typeof E=="object"){let P=C(E,f-1);if(!P.matched)continue;h===null&&(h={...l}),h[y]=P.redacted;for(let R of P.detected)b.push(R);}return h===null?{matched:false}:{matched:true,redacted:h,detected:b}}return {matched:false}}return {name:"fact-pii-guardrail",onInit(l){w(l);},onFactSet(l,f,h){if(!S||!u.has(l)||f===h&&(typeof f!="object"||f===null))return;let b=T(f);if(!b.matched)return;n?.(l,b.detected,r);let y=r==="alert"||o==="alert-only"&&f instanceof Error?"alert":b.redacted===f?"detect":"redact";if(g?.notify?.guardrailBlocked?.("fact-pii-guardrail",l,y,b.detected.length,b.detected[0]?.type),r==="alert"||b.redacted===f)return;let P=g?.facts;if(P?.$store?.set)try{P.$store.set(l,b.redacted);}catch(R){console.warn("[Directive] guardrail redact write failed",{plugin:"fact-pii-guardrail",key:l,phase:"onFactSet",error:R});}},onFactsBatch(l){if(S)for(let f of l){if(f.type!=="set"||!u.has(f.key))continue;let h=f.prev;if(f.value===h&&(typeof f.value!="object"||f.value===null))continue;let b=T(f.value);if(!b.matched)continue;n?.(f.key,b.detected,r);let y=r==="alert"||o==="alert-only"&&f.value instanceof Error?"alert":b.redacted===f.value?"detect":"redact";if(g?.notify?.guardrailBlocked?.("fact-pii-guardrail",f.key,y,b.detected.length,b.detected[0]?.type),r==="alert"||b.redacted===f.value)continue;try{f.value=b.redacted;}catch{}let P=g?.facts;if(P?.$store?.set)try{P.$store.set(f.key,b.redacted);}catch(R){console.warn("[Directive] guardrail redact write failed",{plugin:"fact-pii-guardrail",key:f.key,phase:"onFactsBatch",error:R});}}}}}var K=[{type:"ssn",pattern:/\b(\d{3}[-\s]?\d{2}[-\s]?\d{4})\b/g,validate:a=>{let r=a.replace(/[-\s]/g,"");return !(r.startsWith("000")||r.startsWith("666")||r.startsWith("9")||r.slice(3,5)==="00"||r.slice(5)==="0000")},confidence:.95},{type:"credit_card",pattern:/\b((?:\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|\d{13,19})\b/g,validate:a=>{let r=a.replace(/[-\s]/g,"");if(r.length<13||r.length>19)return false;let i=0,t=false;for(let e=r.length-1;e>=0;e--){let n=r[e];if(!n)continue;let s=Number.parseInt(n,10);t&&(s*=2,s>9&&(s-=9)),i+=s,t=!t;}return i%10===0},confidence:.95},{type:"email",pattern:/\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})\b/gi,confidence:.9},{type:"phone",pattern:/\b(\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4})\b/g,validate:a=>{let r=a.replace(/\D/g,"");return r.length>=10&&r.length<=11},confidence:.8},{type:"date_of_birth",pattern:/\b(born|dob|birth.?date|date.?of.?birth)[:.\s]+(\d{1,4}[-/]\d{1,2}[-/]\d{1,4})\b/gi,valueGroup:2,confidence:.85},{type:"ip_address",pattern:/\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/g,validate:a=>{let i=a.split(".").map(n=>Number.parseInt(n,10));if(i.some(n=>Number.isNaN(n)||n<0||n>255))return false;let[t,e]=i;return !(t===10||t===172&&e>=16&&e<=31||t===192&&e===168||t===127||t===169&&e===254||a==="0.0.0.0"||a==="255.255.255.255")},confidence:.9},{type:"bank_account",pattern:/\b(account|acct)[\s#:]+(\d{8,17})\b/gi,valueGroup:2,confidence:.7},{type:"passport",pattern:/\b(passport)[\s#:]+([A-Z0-9]{6,9})\b/gi,valueGroup:2,confidence:.75},{type:"driver_license",pattern:/\b(driver'?s?\s*licen[cs]e|dl)[\s#:]+([A-Z0-9]{5,15})\b/gi,valueGroup:2,confidence:.7},{type:"medical_id",pattern:/\b(mrn|medical.?record|patient.?id)[\s#:]+([A-Z0-9-]{6,15})\b/gi,valueGroup:2,confidence:.7},{type:"national_id",pattern:/\b(national.?id|nin|identity.?number|identity.?card|id.?number)[\s#:]+([A-Z0-9-]{6,20})\b/gi,valueGroup:2,confidence:.85}];function W(a){let r=[],i="street|st|avenue|ave|road|rd|drive|dr|lane|ln|court|ct|way|boulevard|blvd|circle|cir|place|pl",t=new RegExp(`\\b(\\d{1,5}\\s+(?:\\w+\\s+){1,4}(?:${i})\\b[^\\n]{0,50}\\b[A-Z]{2}\\s+\\d{5}(?:-\\d{4})?)\\b`,"gi"),e;for(;(e=t.exec(a))!==null;)r.push({type:"address",value:e[0],position:{start:e.index,end:e.index+e[0].length},confidence:.7});return r}var $=["mr","mrs","ms","miss","dr","prof","sir","madam","name is","called","known as","signed by","from","dear","hi","hello","contact","recipient"];function Y(a){let r=[],i=$.join("|"),t=new RegExp(`\\b(${i})[.,:]?\\s+([A-Z][a-z]{1,20}(?:\\s[A-Z][a-z]{1,20}){0,2})\\b`,"gi"),e;for(;(e=t.exec(a))!==null;){let n=e[2],s=e[1];n&&(n.split(/\s+/).length>=2||s&&$.some(c=>s.toLowerCase().includes(c)))&&r.push({type:"name",value:n,position:{start:e.index,end:e.index+e[0].length},confidence:.6,context:e[0]});}return r}var j=1e5;function J(a,r){let i=[],t=new RegExp(a.pattern.source,a.pattern.flags),e=a.valueGroup??1,n;for(;(n=t.exec(r))!==null;){let s=n[e]??n[0],c=n.index,o=n.index+n[0].length,d=r.slice(Math.max(0,c-20),o+20);a.validate&&!a.validate(s,d)||i.push({type:a.type,value:s,position:{start:c,end:o},confidence:a.confidence,context:d});}return i}var N={name:"regex",async detect(a,r){if(a.length>j)throw new Error(`[Directive] Input exceeds maximum length of ${j} characters for PII detection. Truncate input or process in chunks.`);let i=[],t=new Set(r);for(let e of K)t.has(e.type)&&i.push(...J(e,a));return t.has("address")&&i.push(...W(a)),t.has("name")&&i.push(...Y(a)),i}},X=new Set(["ssn","credit_card","date_of_birth","medical_id","national_id","passport","driver_license","bank_account"]);function Q(a,r){let{start:i,end:t}=a.position;return Number.isInteger(i)&&Number.isInteger(t)&&i>=0&&i<t&&t<=r}function ee(a,r){switch(r){case "placeholder":return "[REDACTED]";case "typed":return X.has(a.type)?"[REDACTED]":`[${a.type.toUpperCase()}]`;case "masked":{if(a.type!=="credit_card")return "****";let i=a.value.replace(/\D/g,"");return `****${i.length>4?i.slice(-4):""}`}case "hashed":return `[HASH:${te(a.value)}]`}}function O(a,r,i="typed"){let e=[...r.filter(o=>Q(o,a.length))].sort((o,d)=>{if(d.confidence!==o.confidence)return d.confidence-o.confidence;let u=o.position.end-o.position.start,m=d.position.end-d.position.start;return m!==u?m-u:o.position.start-d.position.start}),n=[];for(let o of e)n.some(u=>o.position.start<u.position.end&&u.position.start<o.position.end)||n.push(o);let s=n.sort((o,d)=>d.position.start-o.position.start),c=a;for(let o of s){let d=ee(o,i);c=c.slice(0,o.position.start)+d+c.slice(o.position.end);}return c}function te(a){let t=2166136261;for(let e=0;e<a.length;e++)t^=a.charCodeAt(e),t=Math.imul(t,16777619);return (t>>>0).toString(16).padStart(8,"0")}var B=["ssn","credit_card","email","phone","date_of_birth","bank_account"];function ne(a={}){let{types:r=B,detector:i="regex",redact:t=false,redactionStyle:e="typed",minConfidence:n=.7,onDetected:s,allowlist:c=[],minItemsToBlock:o=1,detectorTimeout:d=5e3}=a,u=i==="regex"?N:i,m=new Set(c.map(p=>p.toLowerCase().trim()));async function x(p,S){if(u===N)return u.detect(p,S);let g,w=u.detect(p,S),v=new Promise((I,T)=>{g=setTimeout(()=>T(new Error(`[Directive] PII detector '${u.name}' timed out after ${d}ms`)),d);});w.catch(()=>{}),v.catch(()=>{});try{return await Promise.race([w,v])}finally{clearTimeout(g);}}return async p=>{let g=(await x(p.input,r)).filter(w=>!(w.confidence<n||m.has(w.value.toLowerCase().trim())));if(g.length>0&&s?.(g),g.length>=o){if(t)return {passed:true,transformed:O(p.input,g,e)};let w={};for(let I of g)w[I.type]=(w[I.type]||0)+1;return {passed:false,reason:`PII detected (${Object.entries(w).map(([I,T])=>`${I}: ${T}`).join(", ")})`}}return {passed:true}}}function Pe(a={}){let r=ne(a);return async(i,t)=>{let e=typeof i.output=="string"?i.output:JSON.stringify(i.output);return r({input:e,agentName:i.agentName},t)}}async function re(a,r={}){let{types:i=B,detector:t="regex",minConfidence:e=.7,timeout:n=5e3}=r,s=t==="regex"?N:t,c;if(s===N)c=await s.detect(a,i);else {let u,m=s.detect(a,i),x=new Promise((p,S)=>{u=setTimeout(()=>S(new Error(`[Directive] PII detector '${s.name}' timed out after ${n}ms`)),n);});m.catch(()=>{}),x.catch(()=>{});try{c=await Promise.race([m,x]);}finally{clearTimeout(u);}}let o=c.filter(u=>u.confidence>=e),d={};for(let u of o)d[u.type]=(d[u.type]||0)+1;return {detected:o.length>0,items:o,typeCounts:d}}async function xe(a,r={}){let i=await re(a,r);return i.detected?{...i,redactedText:O(a,i.items,r.style??"typed")}:{...i}}var M=[{pattern:/ignore\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?|rules?|guidelines?)/i,name:"ignore-previous",severity:"critical",category:"instruction_override"},{pattern:/disregard\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?)/i,name:"disregard-previous",severity:"critical",category:"instruction_override"},{pattern:/forget\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?)/i,name:"forget-previous",severity:"critical",category:"instruction_override"},{pattern:/override\s+(the\s+)?(system|base)\s+(prompt|instructions?)/i,name:"override-system",severity:"critical",category:"instruction_override"},{pattern:/\bDAN\s+(mode|jailbreak)\b/i,name:"dan-mode",severity:"critical",category:"jailbreak"},{pattern:/\bjailbreak(ed)?\s*(mode)?\b/i,name:"jailbreak-keyword",severity:"high",category:"jailbreak"},{pattern:/developer\s+mode\s+(enabled|activated|on)/i,name:"developer-mode",severity:"critical",category:"jailbreak"},{pattern:/pretend\s+(you\s+)?(are|can|have)\s+(no\s+)?(restrictions?|limits?|boundaries?|ethics)/i,name:"pretend-no-restrictions",severity:"high",category:"jailbreak"},{pattern:/you\s+(now\s+)?have\s+no\s+(ethical\s+)?(restrictions?|guidelines?|boundaries?)/i,name:"no-restrictions",severity:"high",category:"jailbreak"},{pattern:/you\s+are\s+now\s+(a|an)\s+\w+\s+(that|who)\s+(can|will|must)/i,name:"role-assignment",severity:"medium",category:"role_manipulation"},{pattern:/from\s+now\s+on,?\s+(you\s+)?(will|must|should)\s+(only\s+)?/i,name:"from-now-on",severity:"medium",category:"role_manipulation"},{pattern:/^(system|assistant|user):\s*/im,name:"fake-role-marker",severity:"high",category:"context_manipulation"},{pattern:/<\|?(system|endofprompt|im_start|im_end)\|?>/i,name:"special-token-injection",severity:"critical",category:"context_manipulation"},{pattern:/```(system|assistant|instructions?)\n/i,name:"markdown-code-injection",severity:"medium",category:"delimiter_injection"},{pattern:/<system>|<\/system>|<instructions?>|<\/instructions?>/i,name:"xml-tag-injection",severity:"high",category:"delimiter_injection"},{pattern:/fetch\s+(content\s+)?(from|at)\s+(the\s+)?url/i,name:"url-fetch-instruction",severity:"medium",category:"indirect_injection"},{pattern:/execute\s+(the\s+)?(code|script|command)\s+(from|in|at)/i,name:"execute-from-source",severity:"high",category:"indirect_injection"}],z=[...M,{pattern:/act\s+as\s+(if\s+)?(you\s+)?(were|are|can)/i,name:"act-as",severity:"low",category:"role_manipulation"},{pattern:/new\s+instructions?:/i,name:"new-instructions",severity:"medium",category:"instruction_override"},{pattern:/\[system\]|\[admin\]|\[developer\]/i,name:"bracket-role-marker",severity:"medium",category:"context_manipulation"},{pattern:/base64|rot13|decode\s+(this|the)/i,name:"encoding-reference",severity:"low",category:"encoding_evasion"},{pattern:/\u200b|\u200c|\u200d|\u2060|\ufeff/,name:"zero-width-chars",severity:"medium",category:"encoding_evasion"}],L=1e5;function H(a,r=M){if(a.length>L)throw new Error(`[Directive] Input exceeds maximum length of ${L} characters for injection detection. Truncate input or process in chunks.`);let i=[];for(let{pattern:s,name:c,severity:o,category:d}of r){let m=new RegExp(s.source,s.flags).exec(a);m&&i.push({name:c,category:d,severity:o,match:m[0],position:m.index});}let t={low:10,medium:25,high:50,critical:100},e=i.reduce((s,c)=>s+t[c.severity],0),n=Math.min(100,e);return {detected:i.length>0,patterns:i,riskScore:n}}function ie(a,r=M){let i=a.replace(/\u200b|\u200c|\u200d|\u2060|\ufeff/g,""),t=r.map(d=>`(${d.pattern.source})`);if(t.length===0)return i;let e=r.some(d=>d.pattern.flags.includes("g")),n=r.some(d=>d.pattern.flags.includes("i")),s=r.some(d=>d.pattern.flags.includes("m")),c=`${e?"g":""}${n?"i":""}${s?"m":""}`,o=new RegExp(t.join("|"),c||"gi");return i=i.replace(o,"[REDACTED]"),i}function ae(a={}){let{additionalPatterns:r=[],replacePatterns:i,strictMode:t=false,blockThreshold:e=50,sanitize:n=false,onBlocked:s,ignoreCategories:c=[]}=a,o;if(i?o=i:o=t?[...z]:[...M],o=[...o,...r],c.length>0){let d=new Set(c);o=o.filter(u=>!d.has(u.category));}return d=>{let u=H(d.input,o);if(u.detected&&u.riskScore>=e){if(s?.(d.input,u),n)return {passed:true,transformed:ie(d.input,o)};let m=u.patterns.sort((x,p)=>{let S={critical:0,high:1,medium:2,low:3};return S[x.severity]-S[p.severity]}).slice(0,3).map(x=>x.name).join(", ");return {passed:false,reason:`Prompt injection detected (risk: ${u.riskScore}%, patterns: ${m})`}}return {passed:true}}}function ve(a,r){return `[UNTRUSTED_CONTENT source="${r}"]
|
|
2
2
|
${a}
|
|
3
|
-
[/UNTRUSTED_CONTENT]`}function Se(a){let{baseGuardrail:r=ae({strictMode:true,blockThreshold:25}),additionalPatterns:i=[]}=a,t=/\[UNTRUSTED_CONTENT source="([^"]+)"\]([\s\S]*?)\[\/UNTRUSTED_CONTENT\]/g;return async(e,n)=>{let s=await r(e,n);if(!s.passed)return s;let c=e.input.matchAll(t);for(let o of c){let[,d,u]=o;if(!u)continue;let m=H(u,[...z,...i]);if(m.detected&&m.riskScore>=25)return {passed:false,reason:`Untrusted content from "${d}" contains potential injection (risk: ${m.riskScore}%)`}}return {passed:true}}}function k(a,r){if(a.length!==r.length)throw new Error(`Vector dimensions must match: ${a.length} vs ${r.length}`);let i=0,t=0,e=0;for(let n=0;n<a.length;n++){let s=a[n],c=r[n];i+=s*c,t+=s*s,e+=c*c;}return t=Math.sqrt(t),e=Math.sqrt(e),t===0||e===0?0:i/(t*e)}function se(a,r,i,t){let e=null;for(let n of r){if(t&&n.agentName&&n.agentName!==t)continue;let s=k(a,n.queryEmbedding);s>=i&&(!e||s>e.similarity)&&(e={entry:n,similarity:s});}return e}function oe(){let a=new Map;function r(i){let t=a.get(i);return t||(t=new Map,a.set(i,t)),t}return {async getEntries(i){return Array.from(r(i).values())},async addEntry(i,t){r(i).set(t.id,t);},async updateEntry(i,t,e){let n=r(i),s=n.get(t);s&&n.set(t,{...s,...e});},async removeEntry(i,t){r(i).delete(t);},async clear(i){a.delete(i);}}}function Te(a){let{embedder:r,similarityThreshold:i=.9,maxCacheSize:t=1e3,ttlMs:e=36e5,namespace:n="default",storage:s=oe(),onHit:c,onMiss:o,onError:d,perAgent:u=false}=a,m={totalEntries:0,totalHits:0,totalMisses:0,hitRate:0,avgSimilarityOnHit:0,oldestEntry:null,newestEntry:null},x=0;function p(g){if(m.totalEntries=g.length,m.hitRate=m.totalHits+m.totalMisses>0?m.totalHits/(m.totalHits+m.totalMisses):0,m.avgSimilarityOnHit=m.totalHits>0?x/m.totalHits:0,g.length>0){let w=g.map(v=>v.createdAt);m.oldestEntry=Math.min(...w),m.newestEntry=Math.max(...w);}else m.oldestEntry=null,m.newestEntry=null;}async function S(){let g=await s.getEntries(n),w=Date.now();for(let I of g)w-I.createdAt>e&&await s.removeEntry(n,I.id);let v=await s.getEntries(n);if(v.length>t){let T=v.sort((C,l)=>C.accessedAt-l.accessedAt).slice(0,v.length-t);for(let C of T)await s.removeEntry(n,C.id);}}return {async lookup(g,w){let v=Date.now();try{let I=await r(g),T=await s.getEntries(n),C=se(I,T,i,u?w:void 0);return C?(await s.updateEntry(n,C.entry.id,{accessedAt:Date.now(),accessCount:C.entry.accessCount+1}),m.totalHits++,x+=C.similarity,p(T),c?.(C.entry,C.similarity),{hit:!0,entry:C.entry,similarity:C.similarity,latencyMs:Date.now()-v}):(m.totalMisses++,p(T),o?.(g),{hit:!1,latencyMs:Date.now()-v})}catch(I){return m.totalMisses++,d?.(I instanceof Error?I:new Error(String(I))),{hit:false,latencyMs:Date.now()-v}}},async store(g,w,v,I={}){let T=await r(g),C={id:globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,query:g,queryEmbedding:T,response:w,metadata:I,createdAt:Date.now(),accessedAt:Date.now(),accessCount:0,agentName:u?v:void 0};await s.addEntry(n,C),await S();let l=await s.getEntries(n);p(l);},async invalidate(g){let w=await s.getEntries(n),v=0;for(let T of w)g(T)&&(await s.removeEntry(n,T.id),v++);let I=await s.getEntries(n);return p(I),v},async clear(){await s.clear(n),m={totalEntries:0,totalHits:0,totalMisses:0,hitRate:0,avgSimilarityOnHit:0,oldestEntry:null,newestEntry:null},x=0;},getStats(){return {...m}},async export(){return s.getEntries(n)},async import(g){for(let v of g)await s.addEntry(n,v);await S();let w=await s.getEntries(n);p(w);}}}function Re(a){let{cache:r}=a;return async i=>{let t=await r.lookup(i.input,i.agentName);return t.hit&&t.entry?{passed:false,cacheHit:true,reason:`Cache hit (similarity: ${(t.similarity*100).toFixed(1)}%)`,cachedResponse:t.entry.response,similarity:t.similarity}:{passed:true,cacheHit:false}}}function ke(a=128){return async r=>{let i=new Array(a).fill(0);for(let e=0;e<r.length;e++){let n=r.charCodeAt(e);i[e%a]+=n/256;}let t=Math.sqrt(i.reduce((e,n)=>e+n*n,0));if(t>0)for(let e=0;e<a;e++)i[e]/=t;return i}}function De(a){let{batchSize:r=20,embedBatch:i,maxWaitMs:t=50}=a;if(r<1||!Number.isFinite(r))throw new Error(`[Directive SemanticCache] batchSize must be >= 1, got ${r}`);let e=[],n=null,s=false;async function c(){if(e.length===0)return;let o=e;e=[],n&&(clearTimeout(n),n=null);try{let d=o.map(m=>m.text),u=await i(d);if(u.length!==o.length)throw new Error(`[Directive SemanticCache] embedBatch returned ${u.length} embeddings for ${o.length} texts. The embedBatch function must return exactly one embedding per input text.`);for(let m=0;m<o.length;m++)o[m].resolve(u[m]);}catch(d){let u=d instanceof Error?d:new Error(String(d));for(let m of o)m.reject(u);}}return {async embed(o){if(s)throw new Error("BatchedEmbedder has been destroyed");return new Promise((d,u)=>{e.push({text:o,resolve:d,reject:u}),e.length>=r?c():n||(n=setTimeout(c,t));})},async flush(){await c();},destroy(){s=true,n&&(clearTimeout(n),n=null);let o=e;e=[];let d=new Error("BatchedEmbedder destroyed");for(let u of o)u.reject(d);}}}function Me(){let a=new Map,r=null;function i(t){if(r===null)r=t.length;else if(t.length!==r)throw new Error(`[Directive ANNIndex] Dimension mismatch: expected ${r}, got ${t.length}`)}return {add(t,e){i(e),a.set(t,e);},remove(t){a.delete(t);},search(t,e,n=0){if(r!==null&&t.length!==r)throw new Error(`[Directive ANNIndex] Query dimension mismatch: expected ${r}, got ${t.length}`);let s=[];for(let[c,o]of a){let d=k(t,o);d>=n&&s.push({id:c,similarity:d});}return s.sort((c,o)=>o.similarity-c.similarity),s.slice(0,e)},rebuild(){},size(){return a.size},clear(){a.clear(),r=null;},needsRebuild(){return false}}}function V(a,r){return 1-k(a,r)}function _(a,r){if(a.length===0)return null;let i=Math.floor(r()*a.length),t=a[i],e=a.filter((u,m)=>m!==i);if(e.length===0)return {id:t.id,embedding:t.embedding,mu:0,left:null,right:null};let n=e.map(u=>({item:u,distance:V(t.embedding,u.embedding)}));n.sort((u,m)=>u.distance-m.distance);let s=Math.floor(n.length/2),c=n[s].distance,o=n.slice(0,s).map(u=>u.item),d=n.slice(s).map(u=>u.item);return {id:t.id,embedding:t.embedding,mu:c,left:_(o,r),right:_(d,r)}}function D(a,r,i,t,e,n){if(!a)return;let s=V(r,a.embedding),c=1-s;c>=t&&(e.push({id:a.id,similarity:c}),e.sort((o,d)=>d.similarity-o.similarity),e.length>i&&e.pop(),e.length===i&&(n.value=1-e[e.length-1].similarity)),s<a.mu?(D(a.left,r,i,t,e,n),s+n.value>=a.mu&&D(a.right,r,i,t,e,n)):(D(a.right,r,i,t,e,n),s-n.value<=a.mu&&D(a.left,r,i,t,e,n));}function _e(a={}){let{random:r=Math.random}=a,i=new Map,t=null,e=false,n=null;function s(c){if(n===null)n=c.length;else if(c.length!==n)throw new Error(`[Directive ANNIndex] Dimension mismatch: expected ${n}, got ${c.length}`)}return {add(c,o){s(o),i.set(c,o),e=true;},remove(c){i.delete(c),e=true;},search(c,o,d=0){if(n!==null&&c.length!==n)throw new Error(`[Directive ANNIndex] Query dimension mismatch: expected ${n}, got ${c.length}`);if(e||!t){let x=[];for(let[p,S]of i){let g=k(c,S);g>=d&&x.push({id:p,similarity:g});}return x.sort((p,S)=>S.similarity-p.similarity),x.slice(0,o)}let u=[],m={value:Number.POSITIVE_INFINITY};return D(t,c,o,d,u,m),u},rebuild(){let c=Array.from(i.entries()).map(([o,d])=>({id:o,embedding:d}));t=_(c,r),e=false;},size(){return i.size},clear(){i.clear(),t=null,e=false,n=null;},needsRebuild(){return e}}}exports.A=De;exports.B=Me;exports.C=_e;exports.a=le;exports.b=ue;exports.c=me;exports.d=fe;exports.e=pe;exports.f=ge;exports.g=ye;exports.h=he;exports.i=Ie;exports.j=O;exports.k=ne;exports.l=Pe;exports.m=re;exports.n=xe;exports.o=M;exports.p=z;exports.q=H;exports.r=ie;exports.s=ae;exports.t=ve;exports.u=Se;exports.v=k;exports.w=oe;exports.x=Te;exports.y=Re;exports.z=ke;//# sourceMappingURL=chunk-
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
[/UNTRUSTED_CONTENT]`}function Se(a){let{baseGuardrail:r=ae({strictMode:true,blockThreshold:25}),additionalPatterns:i=[]}=a,t=/\[UNTRUSTED_CONTENT source="([^"]+)"\]([\s\S]*?)\[\/UNTRUSTED_CONTENT\]/g;return async(e,n)=>{let s=await r(e,n);if(!s.passed)return s;let c=e.input.matchAll(t);for(let o of c){let[,d,u]=o;if(!u)continue;let m=H(u,[...z,...i]);if(m.detected&&m.riskScore>=25)return {passed:false,reason:`Untrusted content from "${d}" contains potential injection (risk: ${m.riskScore}%)`}}return {passed:true}}}function k(a,r){if(a.length!==r.length)throw new Error(`Vector dimensions must match: ${a.length} vs ${r.length}`);let i=0,t=0,e=0;for(let n=0;n<a.length;n++){let s=a[n],c=r[n];i+=s*c,t+=s*s,e+=c*c;}return t=Math.sqrt(t),e=Math.sqrt(e),t===0||e===0?0:i/(t*e)}function se(a,r,i,t){let e=null;for(let n of r){if(t&&n.agentName&&n.agentName!==t)continue;let s=k(a,n.queryEmbedding);s>=i&&(!e||s>e.similarity)&&(e={entry:n,similarity:s});}return e}function oe(){let a=new Map;function r(i){let t=a.get(i);return t||(t=new Map,a.set(i,t)),t}return {async getEntries(i){return Array.from(r(i).values())},async addEntry(i,t){r(i).set(t.id,t);},async updateEntry(i,t,e){let n=r(i),s=n.get(t);s&&n.set(t,{...s,...e});},async removeEntry(i,t){r(i).delete(t);},async clear(i){a.delete(i);}}}function Te(a){let{embedder:r,similarityThreshold:i=.9,maxCacheSize:t=1e3,ttlMs:e=36e5,namespace:n="default",storage:s=oe(),onHit:c,onMiss:o,onError:d,perAgent:u=false}=a,m={totalEntries:0,totalHits:0,totalMisses:0,hitRate:0,avgSimilarityOnHit:0,oldestEntry:null,newestEntry:null},x=0;function p(g){if(m.totalEntries=g.length,m.hitRate=m.totalHits+m.totalMisses>0?m.totalHits/(m.totalHits+m.totalMisses):0,m.avgSimilarityOnHit=m.totalHits>0?x/m.totalHits:0,g.length>0){let w=g.map(v=>v.createdAt);m.oldestEntry=Math.min(...w),m.newestEntry=Math.max(...w);}else m.oldestEntry=null,m.newestEntry=null;}async function S(){let g=await s.getEntries(n),w=Date.now();for(let I of g)w-I.createdAt>e&&await s.removeEntry(n,I.id);let v=await s.getEntries(n);if(v.length>t){let T=v.sort((C,l)=>C.accessedAt-l.accessedAt).slice(0,v.length-t);for(let C of T)await s.removeEntry(n,C.id);}}return {async lookup(g,w){let v=Date.now();try{let I=await r(g),T=await s.getEntries(n),C=se(I,T,i,u?w:void 0);return C?(await s.updateEntry(n,C.entry.id,{accessedAt:Date.now(),accessCount:C.entry.accessCount+1}),m.totalHits++,x+=C.similarity,p(T),c?.(C.entry,C.similarity),{hit:!0,entry:C.entry,similarity:C.similarity,latencyMs:Date.now()-v}):(m.totalMisses++,p(T),o?.(g),{hit:!1,latencyMs:Date.now()-v})}catch(I){return m.totalMisses++,d?.(I instanceof Error?I:new Error(String(I))),{hit:false,latencyMs:Date.now()-v}}},async store(g,w,v,I={}){let T=await r(g),C={id:globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,query:g,queryEmbedding:T,response:w,metadata:I,createdAt:Date.now(),accessedAt:Date.now(),accessCount:0,agentName:u?v:void 0};await s.addEntry(n,C),await S();let l=await s.getEntries(n);p(l);},async invalidate(g){let w=await s.getEntries(n),v=0;for(let T of w)g(T)&&(await s.removeEntry(n,T.id),v++);let I=await s.getEntries(n);return p(I),v},async clear(){await s.clear(n),m={totalEntries:0,totalHits:0,totalMisses:0,hitRate:0,avgSimilarityOnHit:0,oldestEntry:null,newestEntry:null},x=0;},getStats(){return {...m}},async export(){return s.getEntries(n)},async import(g){for(let v of g)await s.addEntry(n,v);await S();let w=await s.getEntries(n);p(w);}}}function Re(a){let{cache:r}=a;return async i=>{let t=await r.lookup(i.input,i.agentName);return t.hit&&t.entry?{passed:false,cacheHit:true,reason:`Cache hit (similarity: ${(t.similarity*100).toFixed(1)}%)`,cachedResponse:t.entry.response,similarity:t.similarity}:{passed:true,cacheHit:false}}}function ke(a=128){return async r=>{let i=new Array(a).fill(0);for(let e=0;e<r.length;e++){let n=r.charCodeAt(e);i[e%a]+=n/256;}let t=Math.sqrt(i.reduce((e,n)=>e+n*n,0));if(t>0)for(let e=0;e<a;e++)i[e]/=t;return i}}function De(a){let{batchSize:r=20,embedBatch:i,maxWaitMs:t=50}=a;if(r<1||!Number.isFinite(r))throw new Error(`[Directive SemanticCache] batchSize must be >= 1, got ${r}`);let e=[],n=null,s=false;async function c(){if(e.length===0)return;let o=e;e=[],n&&(clearTimeout(n),n=null);try{let d=o.map(m=>m.text),u=await i(d);if(u.length!==o.length)throw new Error(`[Directive SemanticCache] embedBatch returned ${u.length} embeddings for ${o.length} texts. The embedBatch function must return exactly one embedding per input text.`);for(let m=0;m<o.length;m++)o[m].resolve(u[m]);}catch(d){let u=d instanceof Error?d:new Error(String(d));for(let m of o)m.reject(u);}}return {async embed(o){if(s)throw new Error("BatchedEmbedder has been destroyed");return new Promise((d,u)=>{e.push({text:o,resolve:d,reject:u}),e.length>=r?c():n||(n=setTimeout(c,t));})},async flush(){await c();},destroy(){s=true,n&&(clearTimeout(n),n=null);let o=e;e=[];let d=new Error("BatchedEmbedder destroyed");for(let u of o)u.reject(d);}}}function Me(){let a=new Map,r=null;function i(t){if(r===null)r=t.length;else if(t.length!==r)throw new Error(`[Directive ANNIndex] Dimension mismatch: expected ${r}, got ${t.length}`)}return {add(t,e){i(e),a.set(t,e);},remove(t){a.delete(t);},search(t,e,n=0){if(r!==null&&t.length!==r)throw new Error(`[Directive ANNIndex] Query dimension mismatch: expected ${r}, got ${t.length}`);let s=[];for(let[c,o]of a){let d=k(t,o);d>=n&&s.push({id:c,similarity:d});}return s.sort((c,o)=>o.similarity-c.similarity),s.slice(0,e)},rebuild(){},size(){return a.size},clear(){a.clear(),r=null;},needsRebuild(){return false}}}function V(a,r){return 1-k(a,r)}function _(a,r){if(a.length===0)return null;let i=Math.floor(r()*a.length),t=a[i],e=a.filter((u,m)=>m!==i);if(e.length===0)return {id:t.id,embedding:t.embedding,mu:0,left:null,right:null};let n=e.map(u=>({item:u,distance:V(t.embedding,u.embedding)}));n.sort((u,m)=>u.distance-m.distance);let s=Math.floor(n.length/2),c=n[s].distance,o=n.slice(0,s).map(u=>u.item),d=n.slice(s).map(u=>u.item);return {id:t.id,embedding:t.embedding,mu:c,left:_(o,r),right:_(d,r)}}function D(a,r,i,t,e,n){if(!a)return;let s=V(r,a.embedding),c=1-s;c>=t&&(e.push({id:a.id,similarity:c}),e.sort((o,d)=>d.similarity-o.similarity),e.length>i&&e.pop(),e.length===i&&(n.value=1-e[e.length-1].similarity)),s<a.mu?(D(a.left,r,i,t,e,n),s+n.value>=a.mu&&D(a.right,r,i,t,e,n)):(D(a.right,r,i,t,e,n),s-n.value<=a.mu&&D(a.left,r,i,t,e,n));}function _e(a={}){let{random:r=Math.random}=a,i=new Map,t=null,e=false,n=null;function s(c){if(n===null)n=c.length;else if(c.length!==n)throw new Error(`[Directive ANNIndex] Dimension mismatch: expected ${n}, got ${c.length}`)}return {add(c,o){s(o),i.set(c,o),e=true;},remove(c){i.delete(c),e=true;},search(c,o,d=0){if(n!==null&&c.length!==n)throw new Error(`[Directive ANNIndex] Query dimension mismatch: expected ${n}, got ${c.length}`);if(e||!t){let x=[];for(let[p,S]of i){let g=k(c,S);g>=d&&x.push({id:p,similarity:g});}return x.sort((p,S)=>S.similarity-p.similarity),x.slice(0,o)}let u=[],m={value:Number.POSITIVE_INFINITY};return D(t,c,o,d,u,m),u},rebuild(){let c=Array.from(i.entries()).map(([o,d])=>({id:o,embedding:d}));t=_(c,r),e=false;},size(){return i.size},clear(){i.clear(),t=null,e=false,n=null;},needsRebuild(){return e}}}exports.A=De;exports.B=Me;exports.C=_e;exports.a=le;exports.b=ue;exports.c=me;exports.d=fe;exports.e=pe;exports.f=ge;exports.g=ye;exports.h=he;exports.i=Ie;exports.j=O;exports.k=ne;exports.l=Pe;exports.m=re;exports.n=xe;exports.o=M;exports.p=z;exports.q=H;exports.r=ie;exports.s=ae;exports.t=ve;exports.u=Se;exports.v=k;exports.w=oe;exports.x=Te;exports.y=Re;exports.z=ke;//# sourceMappingURL=chunk-25OLDNZ3.cjs.map
|
|
4
|
+
//# sourceMappingURL=chunk-25OLDNZ3.cjs.map
|