@niadra/sdk 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +160 -68
  2. package/README.md +451 -22
  3. package/dist/ai-sdk.cjs +1037 -0
  4. package/dist/ai-sdk.cjs.map +1 -0
  5. package/dist/ai-sdk.d.cts +118 -0
  6. package/dist/ai-sdk.d.ts +118 -0
  7. package/dist/ai-sdk.js +1030 -0
  8. package/dist/ai-sdk.js.map +1 -0
  9. package/dist/anthropic.cjs +528 -0
  10. package/dist/anthropic.cjs.map +1 -0
  11. package/dist/anthropic.d.cts +35 -0
  12. package/dist/anthropic.d.ts +35 -0
  13. package/dist/anthropic.js +523 -0
  14. package/dist/anthropic.js.map +1 -0
  15. package/dist/bedrock.cjs +392 -0
  16. package/dist/bedrock.cjs.map +1 -0
  17. package/dist/bedrock.d.cts +25 -0
  18. package/dist/bedrock.d.ts +25 -0
  19. package/dist/bedrock.js +388 -0
  20. package/dist/bedrock.js.map +1 -0
  21. package/dist/cli.js +11045 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/client-DsIxZxZk.d.cts +6905 -0
  24. package/dist/client-DsIxZxZk.d.ts +6905 -0
  25. package/dist/cloudflare-agents.cjs +626 -0
  26. package/dist/cloudflare-agents.cjs.map +1 -0
  27. package/dist/cloudflare-agents.d.cts +113 -0
  28. package/dist/cloudflare-agents.d.ts +113 -0
  29. package/dist/cloudflare-agents.js +622 -0
  30. package/dist/cloudflare-agents.js.map +1 -0
  31. package/dist/elevenlabs.cjs +738 -0
  32. package/dist/elevenlabs.cjs.map +1 -0
  33. package/dist/elevenlabs.d.cts +86 -0
  34. package/dist/elevenlabs.d.ts +86 -0
  35. package/dist/elevenlabs.js +733 -0
  36. package/dist/elevenlabs.js.map +1 -0
  37. package/dist/genkit.cjs +323 -0
  38. package/dist/genkit.cjs.map +1 -0
  39. package/dist/genkit.d.cts +67 -0
  40. package/dist/genkit.d.ts +67 -0
  41. package/dist/genkit.js +318 -0
  42. package/dist/genkit.js.map +1 -0
  43. package/dist/google-adk.cjs +705 -0
  44. package/dist/google-adk.cjs.map +1 -0
  45. package/dist/google-adk.d.cts +91 -0
  46. package/dist/google-adk.d.ts +91 -0
  47. package/dist/google-adk.js +701 -0
  48. package/dist/google-adk.js.map +1 -0
  49. package/dist/google-genai.cjs +422 -0
  50. package/dist/google-genai.cjs.map +1 -0
  51. package/dist/google-genai.d.cts +26 -0
  52. package/dist/google-genai.d.ts +26 -0
  53. package/dist/google-genai.js +418 -0
  54. package/dist/google-genai.js.map +1 -0
  55. package/dist/index.cjs +11421 -1895
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +959 -1294
  58. package/dist/index.d.ts +959 -1294
  59. package/dist/index.js +11368 -1896
  60. package/dist/index.js.map +1 -1
  61. package/dist/intercept-0_lJE6k1.d.cts +20 -0
  62. package/dist/intercept-D7qFCaRb.d.ts +20 -0
  63. package/dist/langchain.cjs +1077 -0
  64. package/dist/langchain.cjs.map +1 -0
  65. package/dist/langchain.d.cts +102 -0
  66. package/dist/langchain.d.ts +102 -0
  67. package/dist/langchain.js +1068 -0
  68. package/dist/langchain.js.map +1 -0
  69. package/dist/livekit.cjs +404 -0
  70. package/dist/livekit.cjs.map +1 -0
  71. package/dist/livekit.d.cts +113 -0
  72. package/dist/livekit.d.ts +113 -0
  73. package/dist/livekit.js +398 -0
  74. package/dist/livekit.js.map +1 -0
  75. package/dist/llamaindex.cjs +349 -0
  76. package/dist/llamaindex.cjs.map +1 -0
  77. package/dist/llamaindex.d.cts +92 -0
  78. package/dist/llamaindex.d.ts +92 -0
  79. package/dist/llamaindex.js +344 -0
  80. package/dist/llamaindex.js.map +1 -0
  81. package/dist/mastra.cjs +1082 -0
  82. package/dist/mastra.cjs.map +1 -0
  83. package/dist/mastra.d.cts +86 -0
  84. package/dist/mastra.d.ts +86 -0
  85. package/dist/mastra.js +1075 -0
  86. package/dist/mastra.js.map +1 -0
  87. package/dist/openai-agents.cjs +465 -0
  88. package/dist/openai-agents.cjs.map +1 -0
  89. package/dist/openai-agents.d.cts +75 -0
  90. package/dist/openai-agents.d.ts +75 -0
  91. package/dist/openai-agents.js +459 -0
  92. package/dist/openai-agents.js.map +1 -0
  93. package/dist/retell.cjs +846 -0
  94. package/dist/retell.cjs.map +1 -0
  95. package/dist/retell.d.cts +161 -0
  96. package/dist/retell.d.ts +161 -0
  97. package/dist/retell.js +841 -0
  98. package/dist/retell.js.map +1 -0
  99. package/dist/shared-Bb5B59Bu.d.ts +39 -0
  100. package/dist/shared-DTPWVlWm.d.cts +39 -0
  101. package/dist/strands.cjs +352 -0
  102. package/dist/strands.cjs.map +1 -0
  103. package/dist/strands.d.cts +72 -0
  104. package/dist/strands.d.ts +72 -0
  105. package/dist/strands.js +347 -0
  106. package/dist/strands.js.map +1 -0
  107. package/dist/twilio.cjs +174 -0
  108. package/dist/twilio.cjs.map +1 -0
  109. package/dist/twilio.d.cts +64 -0
  110. package/dist/twilio.d.ts +64 -0
  111. package/dist/twilio.js +167 -0
  112. package/dist/twilio.js.map +1 -0
  113. package/dist/vapi.cjs +661 -0
  114. package/dist/vapi.cjs.map +1 -0
  115. package/dist/vapi.d.cts +78 -0
  116. package/dist/vapi.d.ts +78 -0
  117. package/dist/vapi.js +656 -0
  118. package/dist/vapi.js.map +1 -0
  119. package/dist/voltagent.cjs +509 -0
  120. package/dist/voltagent.cjs.map +1 -0
  121. package/dist/voltagent.d.cts +70 -0
  122. package/dist/voltagent.d.ts +70 -0
  123. package/dist/voltagent.js +503 -0
  124. package/dist/voltagent.js.map +1 -0
  125. package/dist/webhook-1ozGyksG.d.ts +37 -0
  126. package/dist/webhook-CG4om_DK.d.cts +37 -0
  127. package/dist/whatsapp.cjs +214 -0
  128. package/dist/whatsapp.cjs.map +1 -0
  129. package/dist/whatsapp.d.cts +81 -0
  130. package/dist/whatsapp.d.ts +81 -0
  131. package/dist/whatsapp.js +207 -0
  132. package/dist/whatsapp.js.map +1 -0
  133. package/package.json +351 -6
@@ -0,0 +1,352 @@
1
+ 'use strict';
2
+
3
+ var sdk = require('@strands-agents/sdk');
4
+
5
+ // src/integrations/strands.ts
6
+ function providerOf(model, usage) {
7
+ const slash = model.indexOf("/");
8
+ if (slash > 0) return model.slice(0, slash).trim().toLowerCase();
9
+ const name = model.trim().toLowerCase();
10
+ if (name.startsWith("claude") || `.${name}`.includes(".anthropic.")) return "anthropic";
11
+ if (name.startsWith("gemini")) return "google";
12
+ return "openai";
13
+ }
14
+
15
+ // src/context.ts
16
+ function emptyResult(error) {
17
+ return { text: "", suffix: "", variables: {}, pack: null, source: "none", response: null, error, constraints: null, state: null, coordination: null };
18
+ }
19
+
20
+ // src/integrations/shared.ts
21
+ var ATTESTED = { A: "V2", B: "V1", C: "V1" };
22
+ function attestationProof(attestation) {
23
+ if (!attestation) return null;
24
+ const value = attestation.trim().toUpperCase();
25
+ if (value.includes("FAILED") || value.startsWith("NO-")) return null;
26
+ const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];
27
+ const level = letter ? ATTESTED[letter] : void 0;
28
+ return level ? { method: "network_attestation", level } : null;
29
+ }
30
+ function resolveSession(source) {
31
+ if (typeof source !== "function") return source;
32
+ try {
33
+ return source() ?? null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+ function isConversation(session) {
39
+ return "customer" in session && typeof session.customer === "function";
40
+ }
41
+ function errorName(error) {
42
+ return error instanceof Error ? error.name : typeof error;
43
+ }
44
+ var Bridge = class {
45
+ constructor(session, proof, memory = false) {
46
+ this.session = session;
47
+ this.proof = proof;
48
+ this.memory = memory;
49
+ }
50
+ session;
51
+ proof;
52
+ memory;
53
+ proving = null;
54
+ /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */
55
+ begun = false;
56
+ opened = false;
57
+ /**
58
+ * The context and, when enabled, the agent's notes, read side by side within the same budget.
59
+ * Never rejects.
60
+ */
61
+ async read(options = {}) {
62
+ const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);
63
+ const [context, memory] = await Promise.all([
64
+ this.context(options),
65
+ memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve("")
66
+ ]);
67
+ return { context, memory, prefix: [memory, context.text].filter(Boolean).join("\n\n"), suffix: context.suffix };
68
+ }
69
+ get logger() {
70
+ return this.session.logger;
71
+ }
72
+ /**
73
+ * Starts the first read of a call now, in the background, after the proof when one was given (the
74
+ * pack depends on the level it proves): at call start, so the read runs while the call is set up.
75
+ * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.
76
+ */
77
+ begin() {
78
+ const session = this.session;
79
+ if (!isConversation(session)) return;
80
+ const start = () => {
81
+ this.safe("start the first read", () => {
82
+ this.begun = session.begin();
83
+ });
84
+ };
85
+ if (this.proof === void 0 || this.proof === null) start();
86
+ else void this.verifyOnce().then(start);
87
+ }
88
+ /** Verifies once (when a proof was given), then reads the context. Never rejects. */
89
+ async context(options = {}) {
90
+ await this.verifyOnce();
91
+ try {
92
+ const session = this.session;
93
+ if (this.begun && !this.opened && isConversation(session)) {
94
+ this.opened = true;
95
+ await session.ready(options.timeout === void 0 ? {} : { timeout: options.timeout });
96
+ }
97
+ return await this.session.context(options);
98
+ } catch (error) {
99
+ this.logger.warn(`could not read context (${errorName(error)})`);
100
+ return emptyResult(null);
101
+ }
102
+ }
103
+ /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */
104
+ injected(context) {
105
+ if (!context.text && !context.suffix && context.response?.path !== "holdout") return;
106
+ this.safe("mark the injection", () => {
107
+ this.session.markInjected(context);
108
+ });
109
+ }
110
+ customer(text, options = {}) {
111
+ const session = this.session;
112
+ if (!text.trim() || !isConversation(session)) return;
113
+ this.safe("record the customer's turn", () => session.customer(text, options));
114
+ }
115
+ /** Sends the customer's turn so far, while they speak. In the background; never throws. */
116
+ prefetch(text) {
117
+ const session = this.session;
118
+ if (!text.trim() || !isConversation(session)) return;
119
+ this.safe("prefetch the turn", () => session.prefetch(text));
120
+ }
121
+ agent(text, options = {}) {
122
+ if (!text.trim()) return;
123
+ this.safe("record the agent's turn", () => this.session.agent(text, options));
124
+ }
125
+ /** Records a transfer. Tasks have no transfer; the call is ignored for them. */
126
+ async handoff(target, reason) {
127
+ const session = this.session;
128
+ if (!isConversation(session)) return;
129
+ try {
130
+ await session.handoff(reason ? { target, reason } : { target });
131
+ } catch (error) {
132
+ this.logger.warn(`could not record the handoff (${errorName(error)})`);
133
+ }
134
+ }
135
+ async end() {
136
+ try {
137
+ await this.session.end();
138
+ } catch (error) {
139
+ this.logger.warn(`could not end the session (${errorName(error)})`);
140
+ }
141
+ }
142
+ /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */
143
+ tools() {
144
+ let bound;
145
+ try {
146
+ const memory = this.memory;
147
+ bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });
148
+ } catch (error) {
149
+ this.logger.warn(`could not build the tools (${errorName(error)})`);
150
+ return [];
151
+ }
152
+ return bound ? toolSpecs(bound) : [];
153
+ }
154
+ async agentMemory(params, options) {
155
+ try {
156
+ const result = await this.session.agentMemory(params, options.timeout === void 0 ? {} : { timeout: options.timeout });
157
+ return result.text;
158
+ } catch (error) {
159
+ this.logger.warn(`could not read the agent's memory (${errorName(error)})`);
160
+ return "";
161
+ }
162
+ }
163
+ async verifyOnce() {
164
+ if (this.proof === void 0 || this.proof === null) return;
165
+ this.proving ??= this.runVerify();
166
+ await this.proving;
167
+ }
168
+ async runVerify() {
169
+ try {
170
+ const source = this.proof;
171
+ const proof = typeof source === "function" ? await source() : source;
172
+ if (!proof) return;
173
+ await this.session.verify(proof);
174
+ } catch (error) {
175
+ this.logger.warn(`could not record the verification (${errorName(error)})`);
176
+ }
177
+ }
178
+ safe(what, run) {
179
+ try {
180
+ run();
181
+ } catch (error) {
182
+ this.logger.warn(`could not ${what} (${errorName(error)})`);
183
+ }
184
+ }
185
+ };
186
+ function withoutWrite(option) {
187
+ const { write: _, ...params } = option;
188
+ return params;
189
+ }
190
+ function toolSpecs(bound) {
191
+ return bound.definitions.map(({ function: definition }) => ({
192
+ name: definition.name,
193
+ description: definition.description,
194
+ parameters: definition.parameters,
195
+ execute: (args) => bound.call(definition.name, args)
196
+ }));
197
+ }
198
+ function isRecord(value) {
199
+ return typeof value === "object" && value !== null;
200
+ }
201
+ function count(value) {
202
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
203
+ }
204
+
205
+ // src/integrations/strands.ts
206
+ var MODELS = {
207
+ BedrockModel: { provider: "bedrock", cacheApart: true },
208
+ AnthropicModel: { provider: "anthropic", cacheApart: true },
209
+ OpenAIModel: { provider: "openai", cacheApart: false },
210
+ GoogleModel: { provider: "google", cacheApart: false }
211
+ };
212
+ var NiadraPlugin = class {
213
+ constructor(session, options = {}) {
214
+ this.session = session;
215
+ this.options = options;
216
+ }
217
+ session;
218
+ options;
219
+ name = "niadra";
220
+ states = /* @__PURE__ */ new WeakMap();
221
+ initAgent(agent) {
222
+ agent.addMiddleware(sdk.InvokeModelStage.Input, (context) => this.prepare(agent, context));
223
+ agent.addMiddleware(sdk.InvokeModelStage.Output, (result) => {
224
+ this.record(agent, result);
225
+ return result;
226
+ });
227
+ }
228
+ /** The kit bound to a fixed session; none when the session is found per call. */
229
+ getTools() {
230
+ return typeof this.session === "function" ? [] : niadraTools(this.session, this.options.agentMemory === void 0 ? {} : { agentMemory: this.options.agentMemory });
231
+ }
232
+ stateOf(agent) {
233
+ const choice = this.session;
234
+ const session = typeof choice === "function" ? resolveSession(() => choice(agent)) : choice;
235
+ if (!session) return null;
236
+ let state = this.states.get(session);
237
+ if (!state) {
238
+ state = { bridge: new Bridge(session, this.options.verify, this.options.agentMemory), seen: /* @__PURE__ */ new Set(), model: null };
239
+ this.states.set(session, state);
240
+ }
241
+ return state;
242
+ }
243
+ async prepare(agent, context) {
244
+ const state = this.stateOf(agent);
245
+ if (!state) return context;
246
+ try {
247
+ const known = MODELS[context.model.constructor.name];
248
+ const name = context.model.modelId ?? "";
249
+ state.model = name ? { provider: known?.provider ?? providerOf(name), name, cacheApart: known?.cacheApart ?? false } : null;
250
+ const messages = [...context.messages];
251
+ const last = lastUserText(messages);
252
+ if ((this.options.recordCustomer ?? true) && last >= 0) {
253
+ const text = textOf(messages[last]);
254
+ const key = `${String(last)}:${text}`;
255
+ if (!state.seen.has(key)) {
256
+ state.seen.add(key);
257
+ state.bridge.customer(text);
258
+ }
259
+ }
260
+ const read = await state.bridge.read();
261
+ state.bridge.injected(read.context);
262
+ let trailing = context.dynamicTrailingBlocks ?? 0;
263
+ const target = messages[last];
264
+ if (read.suffix && target) {
265
+ const separator = target.content.length > 0 ? "\n\n" : "";
266
+ messages[last] = new sdk.Message({
267
+ role: target.role,
268
+ content: [...target.content, new sdk.TextBlock(`${separator}${read.suffix}`)],
269
+ trackingId: target.trackingId,
270
+ ...target.metadata === void 0 ? {} : { metadata: target.metadata }
271
+ });
272
+ if (last === messages.length - 1) trailing += 1;
273
+ }
274
+ return {
275
+ ...context,
276
+ messages,
277
+ dynamicTrailingBlocks: trailing,
278
+ ...read.prefix ? { systemPrompt: withPrefix(context.systemPrompt, read.prefix) } : {}
279
+ };
280
+ } catch (error) {
281
+ state.bridge.logger.warn(`could not inject context (${errorName(error)})`);
282
+ return context;
283
+ }
284
+ }
285
+ record(agent, { result }) {
286
+ if (!(this.options.recordAgent ?? true)) return;
287
+ const state = this.stateOf(agent);
288
+ if (!state) return;
289
+ try {
290
+ if (result.stopReason === "toolUse" || result.message.content.some((block) => block.type === "toolUseBlock")) return;
291
+ const text = textOf(result.message);
292
+ if (!text) return;
293
+ const usage = state.model ? strandsUsage(result.metadata?.usage, state.model.provider, state.model.name, state.model.cacheApart) : null;
294
+ state.bridge.agent(text, usage ? { usage } : {});
295
+ } catch (error) {
296
+ state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);
297
+ }
298
+ }
299
+ };
300
+ function niadraTools(session, options = {}) {
301
+ return new Bridge(session, void 0, options.agentMemory).tools().map(
302
+ (spec) => sdk.tool({
303
+ name: spec.name,
304
+ description: spec.description,
305
+ inputSchema: spec.parameters,
306
+ callback: async (input) => parsed(await spec.execute(isRecord(input) ? input : {}))
307
+ })
308
+ );
309
+ }
310
+ function strandsUsage(usage, provider, model, cacheApart) {
311
+ if (!isRecord(usage)) return null;
312
+ const input = count(usage.inputTokens);
313
+ if (input === null || !model) return null;
314
+ const read = count(usage.cacheReadInputTokens) ?? 0;
315
+ const written = count(usage.cacheWriteInputTokens) ?? 0;
316
+ const prompt = cacheApart ? input + read + written : Math.max(input, read + written);
317
+ return { provider, model, prompt_tokens: prompt, cached_tokens: read, cache_write_tokens: written };
318
+ }
319
+ function withPrefix(system, prefix) {
320
+ if (system === void 0 || system === "") return prefix;
321
+ if (typeof system === "string") return `${system}
322
+
323
+ ${prefix}`;
324
+ return [...system, new sdk.TextBlock(prefix)];
325
+ }
326
+ function lastUserText(messages) {
327
+ for (let index = messages.length - 1; index >= 0; index--) {
328
+ const message = messages[index];
329
+ if (message?.role !== "user") continue;
330
+ if (message.content.some((block) => block.type === "toolResultBlock")) return -1;
331
+ return textOf(message) ? index : -1;
332
+ }
333
+ return -1;
334
+ }
335
+ function textOf(message) {
336
+ if (!message) return "";
337
+ return message.content.map((block) => block.type === "textBlock" ? block.text : "").filter(Boolean).join("\n");
338
+ }
339
+ function parsed(text) {
340
+ try {
341
+ return JSON.parse(text);
342
+ } catch {
343
+ return text;
344
+ }
345
+ }
346
+
347
+ exports.NiadraPlugin = NiadraPlugin;
348
+ exports.attestationProof = attestationProof;
349
+ exports.niadraTools = niadraTools;
350
+ exports.strandsUsage = strandsUsage;
351
+ //# sourceMappingURL=strands.cjs.map
352
+ //# sourceMappingURL=strands.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/usage.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/strands.ts"],"names":["InvokeModelStage","Message","Text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AQ,EAAA;AAAA,EACnC;AACA,EAAA,OAAO,EAAA;AACT;AAEA,SAAS,OAAO,OAAA,EAAsC;AACpD,EAAA,IAAI,CAAC,SAAS,OAAO,EAAA;AACrB,EAAA,OAAO,QAAQ,OAAA,CACZ,GAAA,CAAI,CAAC,KAAA,KAAW,MAAM,IAAA,KAAS,WAAA,GAAc,KAAA,CAAM,IAAA,GAAO,EAAG,CAAA,CAC7D,MAAA,CAAO,OAAO,CAAA,CACd,KAAK,IAAI,CAAA;AACd;AAEA,SAAS,OAAO,IAAA,EAAyB;AACvC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"strands.cjs","sourcesContent":["/**\n * Reads what a model provider reported for one call: every input token, the ones read from the\n * provider's prompt cache and the ones written to it.\n *\n * Two shapes are understood, from the response or its `usage` (plain objects or class instances):\n *\n * - OpenAI chat completions and compatible gateways: `usage.prompt_tokens` (cached tokens included)\n * and `usage.prompt_tokens_details.cached_tokens`; the Responses API's `input_tokens` with\n * `input_tokens_details.cached_tokens` too. Gateways that pass Anthropic's cache fields through\n * (`cache_read_input_tokens`, `cache_creation_input_tokens`) are read as well.\n * - Anthropic messages: `usage.input_tokens` counts only the uncached rest, so the prompt is\n * `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`.\n *\n * Nothing here throws: a response without usage gives `null`.\n */\n\nimport type { ModelUsage } from \"./types/events.js\";\n\ntype Bag = Record<PropertyKey, unknown>;\n\nconst PROVIDER = /^[a-z0-9][a-z0-9_.-]{0,63}$/;\nconst MODEL = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,127}$/;\n\nfunction get(value: unknown, name: string): unknown {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null\n ? (value as Bag)[name]\n : undefined;\n}\n\nfunction count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/** `prompt_tokens`, `cached_tokens` and `cache_write_tokens` from a provider's usage, or `null`. */\nexport function tokenCounts(\n usage: unknown,\n): Pick<ModelUsage, \"prompt_tokens\" | \"cached_tokens\" | \"cache_write_tokens\"> | null {\n const read = count(get(usage, \"cache_read_input_tokens\")) ?? 0;\n const written = count(get(usage, \"cache_creation_input_tokens\")) ?? 0;\n let prompt = count(get(usage, \"prompt_tokens\"));\n let cached: number;\n if (prompt !== null) {\n const reported = count(get(get(usage, \"prompt_tokens_details\"), \"cached_tokens\"));\n cached = reported !== null && reported > 0 ? reported : read;\n } else {\n const inputs = count(get(usage, \"input_tokens\"));\n if (inputs === null) return null;\n const details = get(usage, \"input_tokens_details\");\n if (details !== undefined && details !== null) {\n // The Responses API counts cached tokens inside `input_tokens`, as chat completions do.\n prompt = inputs;\n cached = count(get(details, \"cached_tokens\")) ?? 0;\n } else {\n prompt = inputs + read + written;\n cached = read;\n }\n }\n // A gateway can report a cache that does not fit its own prompt count; the prompt is at least that.\n return { prompt_tokens: Math.max(prompt, cached + written), cached_tokens: cached, cache_write_tokens: written };\n}\n\n/**\n * Who served the call: the router prefix of `vendor/model` names, else what the name or the usage\n * shape says, else `openai` (the client `wrap()` takes).\n */\nexport function providerOf(model: string, usage?: unknown): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) return model.slice(0, slash).trim().toLowerCase();\n const name = model.trim().toLowerCase();\n if (name.startsWith(\"claude\") || `.${name}`.includes(\".anthropic.\")) return \"anthropic\";\n if (name.startsWith(\"gemini\")) return \"google\";\n if (get(usage, \"prompt_tokens\") === undefined && get(usage, \"cache_read_input_tokens\") !== undefined) {\n return \"anthropic\";\n }\n return \"openai\";\n}\n\n/**\n * The usage of an OpenAI or Anthropic response (or of its bare `usage`, with `options.model`), for\n * the agent's turn: `convo.agent(text, { usage: modelUsage(response) })`. `null` without usage.\n */\nexport function modelUsage(\n response: unknown,\n options: { provider?: string; model?: string } = {},\n): ModelUsage | null {\n try {\n let usage = get(response, \"usage\");\n if (usage === undefined || usage === null || typeof usage !== \"object\") usage = response;\n const counts = tokenCounts(usage);\n const name = options.model ?? get(response, \"model\");\n if (!counts || typeof name !== \"string\" || !MODEL.test(name)) return null;\n const provider = (options.provider ?? providerOf(name, usage)).toLowerCase();\n if (!PROVIDER.test(provider)) return null;\n return { provider, model: name, ...counts };\n } catch {\n return null;\n }\n}\n\n/** A `ModelUsage` as given, or read from a provider's response; `null` when neither works. */\nexport function asModelUsage(value: unknown): ModelUsage | null {\n if (value === undefined || value === null) return null;\n if (isModelUsage(value)) return value;\n return modelUsage(value);\n}\n\n/** A `ModelUsage` the server accepts as it is; anything else is read like a provider's usage. */\nfunction isModelUsage(value: unknown): value is ModelUsage {\n const provider = get(value, \"provider\");\n const model = get(value, \"model\");\n const prompt = count(get(value, \"prompt_tokens\"));\n const cached = get(value, \"cached_tokens\") === undefined ? 0 : count(get(value, \"cached_tokens\"));\n const written = get(value, \"cache_write_tokens\") === undefined ? 0 : count(get(value, \"cache_write_tokens\"));\n return (\n typeof provider === \"string\" &&\n PROVIDER.test(provider) &&\n typeof model === \"string\" &&\n MODEL.test(model) &&\n prompt !== null &&\n cached !== null &&\n written !== null &&\n cached + written <= prompt\n );\n}\n","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * Niadra for Strands Agents for TypeScript (`@strands-agents/sdk` 1.x, AWS): a plugin with the\n * customer's context before every model call and the navigation kit as tools.\n *\n * `new NiadraPlugin(session)` goes in `plugins` of the `Agent`:\n *\n * - an input middleware of `InvokeModelStage` records the customer's newest message once, adds the\n * agent's notes and the customer's pack after your system prompt, and folds the suffix (deltas\n * and live turns) into the last user message, the way Strands' own context injector does. It\n * changes only what goes to the model: nothing of it lands in `agent.messages`.\n * - an output middleware records the final answer with the model's usage (prompt cache reads and\n * writes included); tool-use turns record nothing.\n * - `getTools()` gives the kit as Strands tools bound to the customer, with the canonical schemas.\n *\n * Fail-open: when Niadra is slow or down, the model gets the messages as they came.\n *\n * @example\n * import { Agent, BedrockModel } from \"@strands-agents/sdk\";\n * import { NiadraPlugin } from \"@niadra/sdk/strands\";\n *\n * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: \"web_chat\", conversation_id: chatId });\n * const support = new Agent({\n * model: new BedrockModel({ modelId: \"us.anthropic.claude-sonnet-4-5-20250929-v1:0\" }),\n * systemPrompt: \"You are Acme's support agent.\",\n * plugins: [new NiadraPlugin(convo)],\n * });\n * const result = await support.invoke(\"Where is my replacement?\");\n */\n\nimport { InvokeModelStage, Message, TextBlock, tool } from \"@strands-agents/sdk\";\nimport type { InvokableTool, InvokeModelContext, InvokeModelResult, JSONValue, LocalAgent, Plugin, SystemPrompt } from \"@strands-agents/sdk\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { providerOf } from \"../usage.js\";\nimport { Bridge, count, errorName, isRecord, resolveSession } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\nexport interface NiadraPluginOptions {\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the final answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context, and adds its memory tools. */\n agentMemory?: AgentMemoryOption;\n}\n\n/** Strands' model classes, the provider each serves, and whether its `inputTokens` leaves the cached tokens out. */\nconst MODELS: Record<string, { provider: string; cacheApart: boolean }> = {\n BedrockModel: { provider: \"bedrock\", cacheApart: true },\n AnthropicModel: { provider: \"anthropic\", cacheApart: true },\n OpenAIModel: { provider: \"openai\", cacheApart: false },\n GoogleModel: { provider: \"google\", cacheApart: false },\n};\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n model: { provider: string; name: string; cacheApart: boolean } | null;\n}\n\n/**\n * The Niadra plugin for one agent. Takes the conversation or task (Strands agents usually live for\n * one conversation), or a function of the agent that finds it per model call.\n */\nexport class NiadraPlugin implements Plugin {\n readonly name = \"niadra\";\n private readonly states = new WeakMap<Session, State>();\n\n constructor(\n private readonly session: Session | ((agent: LocalAgent) => Session | null | undefined),\n private readonly options: NiadraPluginOptions = {},\n ) {}\n\n initAgent(agent: LocalAgent): void {\n agent.addMiddleware(InvokeModelStage.Input, (context: InvokeModelContext) => this.prepare(agent, context));\n agent.addMiddleware(InvokeModelStage.Output, (result: InvokeModelResult) => {\n this.record(agent, result);\n return result;\n });\n }\n\n /** The kit bound to a fixed session; none when the session is found per call. */\n getTools(): InvokableTool<unknown, JSONValue>[] {\n return typeof this.session === \"function\" ? [] : niadraTools(this.session, this.options.agentMemory === undefined ? {} : { agentMemory: this.options.agentMemory });\n }\n\n private stateOf(agent: LocalAgent): State | null {\n const choice = this.session;\n const session = typeof choice === \"function\" ? resolveSession(() => choice(agent)) : choice;\n if (!session) return null;\n let state = this.states.get(session);\n if (!state) {\n state = { bridge: new Bridge(session, this.options.verify, this.options.agentMemory), seen: new Set(), model: null };\n this.states.set(session, state);\n }\n return state;\n }\n\n private async prepare(agent: LocalAgent, context: InvokeModelContext): Promise<InvokeModelContext> {\n const state = this.stateOf(agent);\n if (!state) return context;\n try {\n const known = MODELS[context.model.constructor.name];\n const name = context.model.modelId ?? \"\";\n state.model = name ? { provider: known?.provider ?? providerOf(name), name, cacheApart: known?.cacheApart ?? false } : null;\n const messages = [...context.messages];\n const last = lastUserText(messages);\n if ((this.options.recordCustomer ?? true) && last >= 0) {\n const text = textOf(messages[last]);\n const key = `${String(last)}:${text}`;\n if (!state.seen.has(key)) {\n state.seen.add(key);\n state.bridge.customer(text);\n }\n }\n const read = await state.bridge.read();\n state.bridge.injected(read.context);\n let trailing = context.dynamicTrailingBlocks ?? 0;\n const target = messages[last];\n if (read.suffix && target) {\n const separator = target.content.length > 0 ? \"\\n\\n\" : \"\";\n messages[last] = new Message({\n role: target.role,\n content: [...target.content, new TextBlock(`${separator}${read.suffix}`)],\n trackingId: target.trackingId,\n ...(target.metadata === undefined ? {} : { metadata: target.metadata }),\n });\n // The pack's cache point stays before what changes on every call.\n if (last === messages.length - 1) trailing += 1;\n }\n return {\n ...context,\n messages,\n dynamicTrailingBlocks: trailing,\n ...(read.prefix ? { systemPrompt: withPrefix(context.systemPrompt, read.prefix) } : {}),\n };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n return context;\n }\n }\n\n private record(agent: LocalAgent, { result }: InvokeModelResult): void {\n if (!(this.options.recordAgent ?? true)) return;\n const state = this.stateOf(agent);\n if (!state) return;\n try {\n if (result.stopReason === \"toolUse\" || result.message.content.some((block) => block.type === \"toolUseBlock\")) return;\n const text = textOf(result.message);\n if (!text) return;\n const usage = state.model ? strandsUsage(result.metadata?.usage, state.model.provider, state.model.name, state.model.cacheApart) : null;\n state.bridge.agent(text, usage ? { usage } : {});\n } catch (error) {\n state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);\n }\n }\n}\n\n/** The navigation kit as Strands tools, bound to the session's customer, with the canonical JSON Schemas. */\nexport function niadraTools(session: Session, options: { agentMemory?: AgentMemoryOption } = {}): InvokableTool<unknown, JSONValue>[] {\n return new Bridge(session, undefined, options.agentMemory).tools().map((spec) =>\n tool({\n name: spec.name,\n description: spec.description,\n inputSchema: spec.parameters as never,\n callback: async (input: unknown) => parsed(await spec.execute(isRecord(input) ? input : {})),\n }),\n );\n}\n\n/**\n * Strands' usage as a `ModelUsage`. Bedrock and Anthropic count the cached tokens apart from\n * `inputTokens`; the other providers count them inside it.\n */\nexport function strandsUsage(usage: unknown, provider: string, model: string, cacheApart: boolean): ModelUsage | null {\n if (!isRecord(usage)) return null;\n const input = count(usage.inputTokens);\n if (input === null || !model) return null;\n const read = count(usage.cacheReadInputTokens) ?? 0;\n const written = count(usage.cacheWriteInputTokens) ?? 0;\n const prompt = cacheApart ? input + read + written : Math.max(input, read + written);\n return { provider, model, prompt_tokens: prompt, cached_tokens: read, cache_write_tokens: written };\n}\n\nfunction withPrefix(system: SystemPrompt | undefined, prefix: string): SystemPrompt {\n if (system === undefined || system === \"\") return prefix;\n if (typeof system === \"string\") return `${system}\\n\\n${prefix}`;\n return [...system, new TextBlock(prefix)];\n}\n\n/** The last user message with text and no tool result, or -1. */\nfunction lastUserText(messages: readonly Message[]): number {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role !== \"user\") continue;\n if (message.content.some((block) => block.type === \"toolResultBlock\")) return -1;\n return textOf(message) ? index : -1;\n }\n return -1;\n}\n\nfunction textOf(message: Message | undefined): string {\n if (!message) return \"\";\n return message.content\n .map((block) => (block.type === \"textBlock\" ? block.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction parsed(text: string): JSONValue {\n try {\n return JSON.parse(text) as JSONValue;\n } catch {\n return text;\n }\n}\n"]}
@@ -0,0 +1,72 @@
1
+ import { Plugin, LocalAgent, InvokableTool, JSONValue } from '@strands-agents/sdk';
2
+ import { g as ModelUsage } from './client-DsIxZxZk.cjs';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-DTPWVlWm.cjs';
4
+ export { P as Proof, c as attestationProof } from './shared-DTPWVlWm.cjs';
5
+
6
+ /**
7
+ * Niadra for Strands Agents for TypeScript (`@strands-agents/sdk` 1.x, AWS): a plugin with the
8
+ * customer's context before every model call and the navigation kit as tools.
9
+ *
10
+ * `new NiadraPlugin(session)` goes in `plugins` of the `Agent`:
11
+ *
12
+ * - an input middleware of `InvokeModelStage` records the customer's newest message once, adds the
13
+ * agent's notes and the customer's pack after your system prompt, and folds the suffix (deltas
14
+ * and live turns) into the last user message, the way Strands' own context injector does. It
15
+ * changes only what goes to the model: nothing of it lands in `agent.messages`.
16
+ * - an output middleware records the final answer with the model's usage (prompt cache reads and
17
+ * writes included); tool-use turns record nothing.
18
+ * - `getTools()` gives the kit as Strands tools bound to the customer, with the canonical schemas.
19
+ *
20
+ * Fail-open: when Niadra is slow or down, the model gets the messages as they came.
21
+ *
22
+ * @example
23
+ * import { Agent, BedrockModel } from "@strands-agents/sdk";
24
+ * import { NiadraPlugin } from "@niadra/sdk/strands";
25
+ *
26
+ * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: "web_chat", conversation_id: chatId });
27
+ * const support = new Agent({
28
+ * model: new BedrockModel({ modelId: "us.anthropic.claude-sonnet-4-5-20250929-v1:0" }),
29
+ * systemPrompt: "You are Acme's support agent.",
30
+ * plugins: [new NiadraPlugin(convo)],
31
+ * });
32
+ * const result = await support.invoke("Where is my replacement?");
33
+ */
34
+
35
+ interface NiadraPluginOptions {
36
+ /** What your app proved about the user, recorded once before the first context read. */
37
+ verify?: ProofSource;
38
+ /** Records the newest user message as the customer's turn. Defaults to `true`. */
39
+ recordCustomer?: boolean;
40
+ /** Records the final answer as the agent's turn. Defaults to `true`. */
41
+ recordAgent?: boolean;
42
+ /** Puts the agent's own notes before the customer's context, and adds its memory tools. */
43
+ agentMemory?: AgentMemoryOption;
44
+ }
45
+ /**
46
+ * The Niadra plugin for one agent. Takes the conversation or task (Strands agents usually live for
47
+ * one conversation), or a function of the agent that finds it per model call.
48
+ */
49
+ declare class NiadraPlugin implements Plugin {
50
+ private readonly session;
51
+ private readonly options;
52
+ readonly name = "niadra";
53
+ private readonly states;
54
+ constructor(session: Session | ((agent: LocalAgent) => Session | null | undefined), options?: NiadraPluginOptions);
55
+ initAgent(agent: LocalAgent): void;
56
+ /** The kit bound to a fixed session; none when the session is found per call. */
57
+ getTools(): InvokableTool<unknown, JSONValue>[];
58
+ private stateOf;
59
+ private prepare;
60
+ private record;
61
+ }
62
+ /** The navigation kit as Strands tools, bound to the session's customer, with the canonical JSON Schemas. */
63
+ declare function niadraTools(session: Session, options?: {
64
+ agentMemory?: AgentMemoryOption;
65
+ }): InvokableTool<unknown, JSONValue>[];
66
+ /**
67
+ * Strands' usage as a `ModelUsage`. Bedrock and Anthropic count the cached tokens apart from
68
+ * `inputTokens`; the other providers count them inside it.
69
+ */
70
+ declare function strandsUsage(usage: unknown, provider: string, model: string, cacheApart: boolean): ModelUsage | null;
71
+
72
+ export { AgentMemoryOption, NiadraPlugin, type NiadraPluginOptions, ProofSource, Session, niadraTools, strandsUsage };
@@ -0,0 +1,72 @@
1
+ import { Plugin, LocalAgent, InvokableTool, JSONValue } from '@strands-agents/sdk';
2
+ import { g as ModelUsage } from './client-DsIxZxZk.js';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-Bb5B59Bu.js';
4
+ export { P as Proof, c as attestationProof } from './shared-Bb5B59Bu.js';
5
+
6
+ /**
7
+ * Niadra for Strands Agents for TypeScript (`@strands-agents/sdk` 1.x, AWS): a plugin with the
8
+ * customer's context before every model call and the navigation kit as tools.
9
+ *
10
+ * `new NiadraPlugin(session)` goes in `plugins` of the `Agent`:
11
+ *
12
+ * - an input middleware of `InvokeModelStage` records the customer's newest message once, adds the
13
+ * agent's notes and the customer's pack after your system prompt, and folds the suffix (deltas
14
+ * and live turns) into the last user message, the way Strands' own context injector does. It
15
+ * changes only what goes to the model: nothing of it lands in `agent.messages`.
16
+ * - an output middleware records the final answer with the model's usage (prompt cache reads and
17
+ * writes included); tool-use turns record nothing.
18
+ * - `getTools()` gives the kit as Strands tools bound to the customer, with the canonical schemas.
19
+ *
20
+ * Fail-open: when Niadra is slow or down, the model gets the messages as they came.
21
+ *
22
+ * @example
23
+ * import { Agent, BedrockModel } from "@strands-agents/sdk";
24
+ * import { NiadraPlugin } from "@niadra/sdk/strands";
25
+ *
26
+ * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: "web_chat", conversation_id: chatId });
27
+ * const support = new Agent({
28
+ * model: new BedrockModel({ modelId: "us.anthropic.claude-sonnet-4-5-20250929-v1:0" }),
29
+ * systemPrompt: "You are Acme's support agent.",
30
+ * plugins: [new NiadraPlugin(convo)],
31
+ * });
32
+ * const result = await support.invoke("Where is my replacement?");
33
+ */
34
+
35
+ interface NiadraPluginOptions {
36
+ /** What your app proved about the user, recorded once before the first context read. */
37
+ verify?: ProofSource;
38
+ /** Records the newest user message as the customer's turn. Defaults to `true`. */
39
+ recordCustomer?: boolean;
40
+ /** Records the final answer as the agent's turn. Defaults to `true`. */
41
+ recordAgent?: boolean;
42
+ /** Puts the agent's own notes before the customer's context, and adds its memory tools. */
43
+ agentMemory?: AgentMemoryOption;
44
+ }
45
+ /**
46
+ * The Niadra plugin for one agent. Takes the conversation or task (Strands agents usually live for
47
+ * one conversation), or a function of the agent that finds it per model call.
48
+ */
49
+ declare class NiadraPlugin implements Plugin {
50
+ private readonly session;
51
+ private readonly options;
52
+ readonly name = "niadra";
53
+ private readonly states;
54
+ constructor(session: Session | ((agent: LocalAgent) => Session | null | undefined), options?: NiadraPluginOptions);
55
+ initAgent(agent: LocalAgent): void;
56
+ /** The kit bound to a fixed session; none when the session is found per call. */
57
+ getTools(): InvokableTool<unknown, JSONValue>[];
58
+ private stateOf;
59
+ private prepare;
60
+ private record;
61
+ }
62
+ /** The navigation kit as Strands tools, bound to the session's customer, with the canonical JSON Schemas. */
63
+ declare function niadraTools(session: Session, options?: {
64
+ agentMemory?: AgentMemoryOption;
65
+ }): InvokableTool<unknown, JSONValue>[];
66
+ /**
67
+ * Strands' usage as a `ModelUsage`. Bedrock and Anthropic count the cached tokens apart from
68
+ * `inputTokens`; the other providers count them inside it.
69
+ */
70
+ declare function strandsUsage(usage: unknown, provider: string, model: string, cacheApart: boolean): ModelUsage | null;
71
+
72
+ export { AgentMemoryOption, NiadraPlugin, type NiadraPluginOptions, ProofSource, Session, niadraTools, strandsUsage };