@niadra/sdk 0.1.1 → 0.9.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/CHANGELOG.md +200 -62
- package/README.md +462 -24
- package/dist/ai-sdk.cjs +1036 -0
- package/dist/ai-sdk.cjs.map +1 -0
- package/dist/ai-sdk.d.cts +118 -0
- package/dist/ai-sdk.d.ts +118 -0
- package/dist/ai-sdk.js +1029 -0
- package/dist/ai-sdk.js.map +1 -0
- package/dist/anthropic.cjs +528 -0
- package/dist/anthropic.cjs.map +1 -0
- package/dist/anthropic.d.cts +35 -0
- package/dist/anthropic.d.ts +35 -0
- package/dist/anthropic.js +523 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/bedrock.cjs +392 -0
- package/dist/bedrock.cjs.map +1 -0
- package/dist/bedrock.d.cts +25 -0
- package/dist/bedrock.d.ts +25 -0
- package/dist/bedrock.js +388 -0
- package/dist/bedrock.js.map +1 -0
- package/dist/cli.js +11101 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-B_ip8T2o.d.cts +6960 -0
- package/dist/client-B_ip8T2o.d.ts +6960 -0
- package/dist/cloudflare-agents.cjs +626 -0
- package/dist/cloudflare-agents.cjs.map +1 -0
- package/dist/cloudflare-agents.d.cts +113 -0
- package/dist/cloudflare-agents.d.ts +113 -0
- package/dist/cloudflare-agents.js +622 -0
- package/dist/cloudflare-agents.js.map +1 -0
- package/dist/elevenlabs.cjs +738 -0
- package/dist/elevenlabs.cjs.map +1 -0
- package/dist/elevenlabs.d.cts +86 -0
- package/dist/elevenlabs.d.ts +86 -0
- package/dist/elevenlabs.js +733 -0
- package/dist/elevenlabs.js.map +1 -0
- package/dist/genkit.cjs +323 -0
- package/dist/genkit.cjs.map +1 -0
- package/dist/genkit.d.cts +67 -0
- package/dist/genkit.d.ts +67 -0
- package/dist/genkit.js +318 -0
- package/dist/genkit.js.map +1 -0
- package/dist/google-adk.cjs +705 -0
- package/dist/google-adk.cjs.map +1 -0
- package/dist/google-adk.d.cts +91 -0
- package/dist/google-adk.d.ts +91 -0
- package/dist/google-adk.js +701 -0
- package/dist/google-adk.js.map +1 -0
- package/dist/google-genai.cjs +422 -0
- package/dist/google-genai.cjs.map +1 -0
- package/dist/google-genai.d.cts +26 -0
- package/dist/google-genai.d.ts +26 -0
- package/dist/google-genai.js +418 -0
- package/dist/google-genai.js.map +1 -0
- package/dist/index.cjs +11494 -1910
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +957 -1294
- package/dist/index.d.ts +957 -1294
- package/dist/index.js +11441 -1911
- package/dist/index.js.map +1 -1
- package/dist/intercept-CBaPK_-k.d.ts +20 -0
- package/dist/intercept-CxmBLfoj.d.cts +20 -0
- package/dist/langchain.cjs +1076 -0
- package/dist/langchain.cjs.map +1 -0
- package/dist/langchain.d.cts +102 -0
- package/dist/langchain.d.ts +102 -0
- package/dist/langchain.js +1067 -0
- package/dist/langchain.js.map +1 -0
- package/dist/livekit.cjs +404 -0
- package/dist/livekit.cjs.map +1 -0
- package/dist/livekit.d.cts +113 -0
- package/dist/livekit.d.ts +113 -0
- package/dist/livekit.js +398 -0
- package/dist/livekit.js.map +1 -0
- package/dist/llamaindex.cjs +349 -0
- package/dist/llamaindex.cjs.map +1 -0
- package/dist/llamaindex.d.cts +92 -0
- package/dist/llamaindex.d.ts +92 -0
- package/dist/llamaindex.js +344 -0
- package/dist/llamaindex.js.map +1 -0
- package/dist/mastra.cjs +1081 -0
- package/dist/mastra.cjs.map +1 -0
- package/dist/mastra.d.cts +86 -0
- package/dist/mastra.d.ts +86 -0
- package/dist/mastra.js +1074 -0
- package/dist/mastra.js.map +1 -0
- package/dist/openai-agents.cjs +465 -0
- package/dist/openai-agents.cjs.map +1 -0
- package/dist/openai-agents.d.cts +75 -0
- package/dist/openai-agents.d.ts +75 -0
- package/dist/openai-agents.js +459 -0
- package/dist/openai-agents.js.map +1 -0
- package/dist/retell.cjs +846 -0
- package/dist/retell.cjs.map +1 -0
- package/dist/retell.d.cts +161 -0
- package/dist/retell.d.ts +161 -0
- package/dist/retell.js +841 -0
- package/dist/retell.js.map +1 -0
- package/dist/shared-BLkAbvuf.d.ts +39 -0
- package/dist/shared-DEkF2Y_z.d.cts +39 -0
- package/dist/strands.cjs +352 -0
- package/dist/strands.cjs.map +1 -0
- package/dist/strands.d.cts +72 -0
- package/dist/strands.d.ts +72 -0
- package/dist/strands.js +347 -0
- package/dist/strands.js.map +1 -0
- package/dist/twilio.cjs +174 -0
- package/dist/twilio.cjs.map +1 -0
- package/dist/twilio.d.cts +64 -0
- package/dist/twilio.d.ts +64 -0
- package/dist/twilio.js +167 -0
- package/dist/twilio.js.map +1 -0
- package/dist/vapi.cjs +661 -0
- package/dist/vapi.cjs.map +1 -0
- package/dist/vapi.d.cts +78 -0
- package/dist/vapi.d.ts +78 -0
- package/dist/vapi.js +656 -0
- package/dist/vapi.js.map +1 -0
- package/dist/voltagent.cjs +509 -0
- package/dist/voltagent.cjs.map +1 -0
- package/dist/voltagent.d.cts +70 -0
- package/dist/voltagent.d.ts +70 -0
- package/dist/voltagent.js +503 -0
- package/dist/voltagent.js.map +1 -0
- package/dist/webhook-BaraTaA9.d.ts +37 -0
- package/dist/webhook-CuR0Wckd.d.cts +37 -0
- package/dist/whatsapp.cjs +214 -0
- package/dist/whatsapp.cjs.map +1 -0
- package/dist/whatsapp.d.cts +81 -0
- package/dist/whatsapp.d.ts +81 -0
- package/dist/whatsapp.js +207 -0
- package/dist/whatsapp.js.map +1 -0
- package/package.json +351 -6
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var agents = require('@openai/agents');
|
|
4
|
+
|
|
5
|
+
// src/integrations/openai-agents.ts
|
|
6
|
+
|
|
7
|
+
// src/ids.ts
|
|
8
|
+
var lastMs = -1;
|
|
9
|
+
var counter = 0;
|
|
10
|
+
function randomBytes(length) {
|
|
11
|
+
const bytes = new Uint8Array(length);
|
|
12
|
+
const webCrypto = globalThis.crypto;
|
|
13
|
+
if (webCrypto?.getRandomValues) {
|
|
14
|
+
webCrypto.getRandomValues(bytes);
|
|
15
|
+
} else {
|
|
16
|
+
for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
17
|
+
}
|
|
18
|
+
return bytes;
|
|
19
|
+
}
|
|
20
|
+
function uuidv7(now = Date.now()) {
|
|
21
|
+
let ms = now;
|
|
22
|
+
if (ms <= lastMs) {
|
|
23
|
+
ms = lastMs;
|
|
24
|
+
counter = counter + 1 & 4095;
|
|
25
|
+
if (counter === 0) ms += 1;
|
|
26
|
+
} else {
|
|
27
|
+
counter = (randomBytes(2)[0] ?? 0) & 127;
|
|
28
|
+
}
|
|
29
|
+
lastMs = ms;
|
|
30
|
+
const bytes = randomBytes(16);
|
|
31
|
+
const high = Math.floor(ms / 2 ** 16);
|
|
32
|
+
const low = ms % 2 ** 16;
|
|
33
|
+
bytes[0] = high >>> 24 & 255;
|
|
34
|
+
bytes[1] = high >>> 16 & 255;
|
|
35
|
+
bytes[2] = high >>> 8 & 255;
|
|
36
|
+
bytes[3] = high & 255;
|
|
37
|
+
bytes[4] = low >>> 8 & 255;
|
|
38
|
+
bytes[5] = low & 255;
|
|
39
|
+
bytes[6] = 112 | counter >>> 8 & 15;
|
|
40
|
+
bytes[7] = counter & 255;
|
|
41
|
+
bytes[8] = 128 | (bytes[8] ?? 0) & 63;
|
|
42
|
+
let hex = "";
|
|
43
|
+
for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
|
|
44
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/capture/tool.ts
|
|
48
|
+
var RECORDED = /* @__PURE__ */ Symbol.for("niadra.tool");
|
|
49
|
+
function recordedTool(fn) {
|
|
50
|
+
return typeof fn === "function" ? fn[RECORDED] ?? null : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/context.ts
|
|
54
|
+
function emptyResult(error) {
|
|
55
|
+
return { text: "", suffix: "", variables: {}, pack: null, source: "none", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/integrations/shared.ts
|
|
59
|
+
var ATTESTED = { A: "V2", B: "V1", C: "V1" };
|
|
60
|
+
function attestationProof(attestation) {
|
|
61
|
+
if (!attestation) return null;
|
|
62
|
+
const value = attestation.trim().toUpperCase();
|
|
63
|
+
if (value.includes("FAILED") || value.startsWith("NO-")) return null;
|
|
64
|
+
const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];
|
|
65
|
+
const level = letter ? ATTESTED[letter] : void 0;
|
|
66
|
+
return level ? { method: "network_attestation", level } : null;
|
|
67
|
+
}
|
|
68
|
+
function isConversation(session) {
|
|
69
|
+
return "customer" in session && typeof session.customer === "function";
|
|
70
|
+
}
|
|
71
|
+
function errorName(error) {
|
|
72
|
+
return error instanceof Error ? error.name : typeof error;
|
|
73
|
+
}
|
|
74
|
+
var Bridge = class {
|
|
75
|
+
constructor(session, proof, memory = false) {
|
|
76
|
+
this.session = session;
|
|
77
|
+
this.proof = proof;
|
|
78
|
+
this.memory = memory;
|
|
79
|
+
}
|
|
80
|
+
session;
|
|
81
|
+
proof;
|
|
82
|
+
memory;
|
|
83
|
+
proving = null;
|
|
84
|
+
/** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */
|
|
85
|
+
begun = false;
|
|
86
|
+
opened = false;
|
|
87
|
+
/**
|
|
88
|
+
* The context and, when enabled, the agent's notes, read side by side within the same budget.
|
|
89
|
+
* Never rejects.
|
|
90
|
+
*/
|
|
91
|
+
async read(options = {}) {
|
|
92
|
+
const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);
|
|
93
|
+
const [context, memory] = await Promise.all([
|
|
94
|
+
this.context(options),
|
|
95
|
+
memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve("")
|
|
96
|
+
]);
|
|
97
|
+
return { context, memory, prefix: [memory, context.text].filter(Boolean).join("\n\n"), suffix: context.suffix };
|
|
98
|
+
}
|
|
99
|
+
get logger() {
|
|
100
|
+
return this.session.logger;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Starts the first read of a call now, in the background, after the proof when one was given (the
|
|
104
|
+
* pack depends on the level it proves): at call start, so the read runs while the call is set up.
|
|
105
|
+
* The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.
|
|
106
|
+
*/
|
|
107
|
+
begin() {
|
|
108
|
+
const session = this.session;
|
|
109
|
+
if (!isConversation(session)) return;
|
|
110
|
+
const start = () => {
|
|
111
|
+
this.safe("start the first read", () => {
|
|
112
|
+
this.begun = session.begin();
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
if (this.proof === void 0 || this.proof === null) start();
|
|
116
|
+
else void this.verifyOnce().then(start);
|
|
117
|
+
}
|
|
118
|
+
/** Verifies once (when a proof was given), then reads the context. Never rejects. */
|
|
119
|
+
async context(options = {}) {
|
|
120
|
+
await this.verifyOnce();
|
|
121
|
+
try {
|
|
122
|
+
const session = this.session;
|
|
123
|
+
if (this.begun && !this.opened && isConversation(session)) {
|
|
124
|
+
this.opened = true;
|
|
125
|
+
await session.ready(options.timeout === void 0 ? {} : { timeout: options.timeout });
|
|
126
|
+
}
|
|
127
|
+
return await this.session.context(options);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
this.logger.warn(`could not read context (${errorName(error)})`);
|
|
130
|
+
return emptyResult(null);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */
|
|
134
|
+
injected(context) {
|
|
135
|
+
if (!context.text && !context.suffix && context.response?.path !== "holdout") return;
|
|
136
|
+
this.safe("mark the injection", () => {
|
|
137
|
+
this.session.markInjected(context);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
customer(text, options = {}) {
|
|
141
|
+
const session = this.session;
|
|
142
|
+
if (!text.trim() || !isConversation(session)) return;
|
|
143
|
+
this.safe("record the customer's turn", () => session.customer(text, options));
|
|
144
|
+
}
|
|
145
|
+
/** Sends the customer's turn so far, while they speak. In the background; never throws. */
|
|
146
|
+
prefetch(text) {
|
|
147
|
+
const session = this.session;
|
|
148
|
+
if (!text.trim() || !isConversation(session)) return;
|
|
149
|
+
this.safe("prefetch the turn", () => session.prefetch(text));
|
|
150
|
+
}
|
|
151
|
+
agent(text, options = {}) {
|
|
152
|
+
if (!text.trim()) return;
|
|
153
|
+
this.safe("record the agent's turn", () => this.session.agent(text, options));
|
|
154
|
+
}
|
|
155
|
+
/** Records a transfer. Tasks have no transfer; the call is ignored for them. */
|
|
156
|
+
async handoff(target, reason) {
|
|
157
|
+
const session = this.session;
|
|
158
|
+
if (!isConversation(session)) return;
|
|
159
|
+
try {
|
|
160
|
+
await session.handoff(reason ? { target, reason } : { target });
|
|
161
|
+
} catch (error) {
|
|
162
|
+
this.logger.warn(`could not record the handoff (${errorName(error)})`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async end() {
|
|
166
|
+
try {
|
|
167
|
+
await this.session.end();
|
|
168
|
+
} catch (error) {
|
|
169
|
+
this.logger.warn(`could not end the session (${errorName(error)})`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */
|
|
173
|
+
tools() {
|
|
174
|
+
let bound;
|
|
175
|
+
try {
|
|
176
|
+
const memory = this.memory;
|
|
177
|
+
bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });
|
|
178
|
+
} catch (error) {
|
|
179
|
+
this.logger.warn(`could not build the tools (${errorName(error)})`);
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
return bound ? toolSpecs(bound) : [];
|
|
183
|
+
}
|
|
184
|
+
async agentMemory(params, options) {
|
|
185
|
+
try {
|
|
186
|
+
const result = await this.session.agentMemory(params, options.timeout === void 0 ? {} : { timeout: options.timeout });
|
|
187
|
+
return result.text;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
this.logger.warn(`could not read the agent's memory (${errorName(error)})`);
|
|
190
|
+
return "";
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async verifyOnce() {
|
|
194
|
+
if (this.proof === void 0 || this.proof === null) return;
|
|
195
|
+
this.proving ??= this.runVerify();
|
|
196
|
+
await this.proving;
|
|
197
|
+
}
|
|
198
|
+
async runVerify() {
|
|
199
|
+
try {
|
|
200
|
+
const source = this.proof;
|
|
201
|
+
const proof = typeof source === "function" ? await source() : source;
|
|
202
|
+
if (!proof) return;
|
|
203
|
+
await this.session.verify(proof);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
this.logger.warn(`could not record the verification (${errorName(error)})`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
safe(what, run) {
|
|
209
|
+
try {
|
|
210
|
+
run();
|
|
211
|
+
} catch (error) {
|
|
212
|
+
this.logger.warn(`could not ${what} (${errorName(error)})`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
function withoutWrite(option) {
|
|
217
|
+
const { write: _, ...params } = option;
|
|
218
|
+
return params;
|
|
219
|
+
}
|
|
220
|
+
function toolSpecs(bound) {
|
|
221
|
+
return bound.definitions.map(({ function: definition }) => ({
|
|
222
|
+
name: definition.name,
|
|
223
|
+
description: definition.description,
|
|
224
|
+
parameters: definition.parameters,
|
|
225
|
+
execute: (args) => bound.call(definition.name, args)
|
|
226
|
+
}));
|
|
227
|
+
}
|
|
228
|
+
function isRecord(value) {
|
|
229
|
+
return typeof value === "object" && value !== null;
|
|
230
|
+
}
|
|
231
|
+
function count(value) {
|
|
232
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
|
233
|
+
}
|
|
234
|
+
var TurnHooks = class _TurnHooks {
|
|
235
|
+
constructor(adapter, enabled) {
|
|
236
|
+
this.adapter = adapter;
|
|
237
|
+
this.enabled = enabled;
|
|
238
|
+
}
|
|
239
|
+
adapter;
|
|
240
|
+
enabled;
|
|
241
|
+
/** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */
|
|
242
|
+
static MAX_OPEN = 100;
|
|
243
|
+
frames = /* @__PURE__ */ new Map();
|
|
244
|
+
calls = /* @__PURE__ */ new Map();
|
|
245
|
+
/** The turn of the run `key`: the session's turn in progress, or a new one of its own. */
|
|
246
|
+
open(session, key, params = {}) {
|
|
247
|
+
if (!this.enabled) return void 0;
|
|
248
|
+
const held = this.frames.get(key);
|
|
249
|
+
if (held !== void 0) return held.frame;
|
|
250
|
+
try {
|
|
251
|
+
const active = session.activeTurn();
|
|
252
|
+
if (active !== void 0 && !this.owns(active)) {
|
|
253
|
+
this.frames.set(key, { frame: active, own: false });
|
|
254
|
+
return active;
|
|
255
|
+
}
|
|
256
|
+
const frame = session.openTurn({ ...params, adapter: this.adapter });
|
|
257
|
+
this.frames.set(key, { frame, own: true });
|
|
258
|
+
if (this.frames.size > _TurnHooks.MAX_OPEN) {
|
|
259
|
+
const [oldest] = this.frames.keys();
|
|
260
|
+
if (oldest !== void 0) {
|
|
261
|
+
this.frames.get(oldest)?.frame.incomplete();
|
|
262
|
+
this.close(oldest);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return frame;
|
|
266
|
+
} catch (error) {
|
|
267
|
+
session.logger.warn(`could not open the turn (${errorName(error)})`);
|
|
268
|
+
return void 0;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** The turn of `key`, else the session's turn in progress. */
|
|
272
|
+
frame(session, key) {
|
|
273
|
+
if (!this.enabled) return void 0;
|
|
274
|
+
const held = key === void 0 ? void 0 : this.frames.get(key);
|
|
275
|
+
const frame = held?.frame ?? session.activeTurn();
|
|
276
|
+
return frame === void 0 || frame.closed ? void 0 : frame;
|
|
277
|
+
}
|
|
278
|
+
has(key) {
|
|
279
|
+
return this.frames.has(key);
|
|
280
|
+
}
|
|
281
|
+
owns(frame) {
|
|
282
|
+
for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
/** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */
|
|
286
|
+
close(key, error) {
|
|
287
|
+
const held = this.frames.get(key);
|
|
288
|
+
if (held === void 0) return;
|
|
289
|
+
this.frames.delete(key);
|
|
290
|
+
for (const [callKey, call] of this.calls) {
|
|
291
|
+
if (call.frame !== held.frame) continue;
|
|
292
|
+
this.calls.delete(callKey);
|
|
293
|
+
if (held.own) call.failed(error ?? "error");
|
|
294
|
+
}
|
|
295
|
+
if (held.own) held.frame.close(error);
|
|
296
|
+
}
|
|
297
|
+
/** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */
|
|
298
|
+
toolStart(session, callKey, name, args, options = {}) {
|
|
299
|
+
const frame = this.frame(session, options.frameKey);
|
|
300
|
+
if (frame === void 0) return;
|
|
301
|
+
try {
|
|
302
|
+
this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));
|
|
303
|
+
} catch {
|
|
304
|
+
frame.incomplete();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the
|
|
309
|
+
* same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function
|
|
310
|
+
* wrapped with `tool()`, which answers itself.
|
|
311
|
+
*/
|
|
312
|
+
replayed(session, name, args, fn, frameKey) {
|
|
313
|
+
const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();
|
|
314
|
+
if (frame?.playback == null || fn !== void 0 && recordedTool(fn) !== null) return null;
|
|
315
|
+
return frame.playback.answer(name, args, false);
|
|
316
|
+
}
|
|
317
|
+
toolEnd(callKey, result, error) {
|
|
318
|
+
const call = this.calls.get(callKey);
|
|
319
|
+
if (call === void 0) return;
|
|
320
|
+
this.calls.delete(callKey);
|
|
321
|
+
try {
|
|
322
|
+
if (error !== void 0) call.failed(error);
|
|
323
|
+
else call.result(result);
|
|
324
|
+
} catch {
|
|
325
|
+
call.frame.incomplete();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/** A model call that ended, with its tokens when the framework reported them. */
|
|
329
|
+
model(session, model, tokens = {}, frameKey) {
|
|
330
|
+
const frame = this.frame(session, frameKey);
|
|
331
|
+
if (frame === void 0) return;
|
|
332
|
+
try {
|
|
333
|
+
frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });
|
|
334
|
+
} catch {
|
|
335
|
+
frame.incomplete();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// src/integrations/openai-agents.ts
|
|
341
|
+
var NiadraSession = class {
|
|
342
|
+
constructor(conversation, options = {}) {
|
|
343
|
+
this.conversation = conversation;
|
|
344
|
+
this.options = options;
|
|
345
|
+
this.inner = options.inner ?? new agents.MemorySession({ sessionId: conversation.id });
|
|
346
|
+
this.bridge = new Bridge(conversation);
|
|
347
|
+
}
|
|
348
|
+
conversation;
|
|
349
|
+
options;
|
|
350
|
+
inner;
|
|
351
|
+
bridge;
|
|
352
|
+
getSessionId() {
|
|
353
|
+
return this.inner.getSessionId();
|
|
354
|
+
}
|
|
355
|
+
getItems(limit) {
|
|
356
|
+
return this.inner.getItems(limit);
|
|
357
|
+
}
|
|
358
|
+
async addItems(items) {
|
|
359
|
+
await this.inner.addItems(items);
|
|
360
|
+
for (const item of items) {
|
|
361
|
+
if (!isRecord(item)) continue;
|
|
362
|
+
if (item.role === "user" && (this.options.recordCustomer ?? true)) this.bridge.customer(textOf(item.content));
|
|
363
|
+
if (item.role === "assistant" && (this.options.recordAgent ?? true)) this.bridge.agent(textOf(item.content));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
popItem() {
|
|
367
|
+
return this.inner.popItem();
|
|
368
|
+
}
|
|
369
|
+
clearSession() {
|
|
370
|
+
return this.inner.clearSession();
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
function niadraInstructions(base, session, options = {}) {
|
|
374
|
+
const bridge = new Bridge(session, options.verify, options.agentMemory);
|
|
375
|
+
return async (runContext, agent) => {
|
|
376
|
+
const own = typeof base === "function" ? await base(runContext, agent) : base;
|
|
377
|
+
const read = await bridge.read();
|
|
378
|
+
bridge.injected(read.context);
|
|
379
|
+
return [own, read.prefix, read.suffix].filter(Boolean).join("\n\n");
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
function niadraTools(session, options = {}) {
|
|
383
|
+
return new Bridge(session, void 0, options.agentMemory).tools().map(
|
|
384
|
+
(spec) => agents.tool({
|
|
385
|
+
name: spec.name,
|
|
386
|
+
description: spec.description,
|
|
387
|
+
// The canonical schemas have optional fields, so the tool is not strict.
|
|
388
|
+
parameters: spec.parameters,
|
|
389
|
+
strict: false,
|
|
390
|
+
execute: async (input) => spec.execute(isRecord(input) ? input : {})
|
|
391
|
+
})
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
function niadraRunHooks(runner, conversation, options = {}) {
|
|
395
|
+
const bridge = new Bridge(conversation);
|
|
396
|
+
const hooks = new TurnHooks("openai-agents", options.turns ?? false);
|
|
397
|
+
const keys = /* @__PURE__ */ new WeakMap();
|
|
398
|
+
const keyOf = (context) => {
|
|
399
|
+
let key = keys.get(context);
|
|
400
|
+
if (key === void 0) {
|
|
401
|
+
key = uuidv7();
|
|
402
|
+
keys.set(context, key);
|
|
403
|
+
}
|
|
404
|
+
return key;
|
|
405
|
+
};
|
|
406
|
+
const onHandoff = (_context, from, to) => {
|
|
407
|
+
void bridge.handoff("agent", `${from.name} to ${to.name}`);
|
|
408
|
+
};
|
|
409
|
+
const onStart = (context, agent) => {
|
|
410
|
+
hooks.open(conversation, keyOf(context), { agent: agent.name });
|
|
411
|
+
};
|
|
412
|
+
const onToolStart = (context, _agent, tool2, details) => {
|
|
413
|
+
const call = isRecord(details.toolCall) ? details.toolCall : {};
|
|
414
|
+
const callId = typeof call.callId === "string" ? call.callId : null;
|
|
415
|
+
hooks.toolStart(conversation, callId ?? uuidv7(), tool2.name, parsed(call.arguments), { frameKey: keyOf(context), callId });
|
|
416
|
+
};
|
|
417
|
+
const onToolEnd = (_context, _agent, _tool, result, details) => {
|
|
418
|
+
const call = isRecord(details.toolCall) ? details.toolCall : {};
|
|
419
|
+
if (typeof call.callId === "string") hooks.toolEnd(call.callId, result);
|
|
420
|
+
};
|
|
421
|
+
const onEnd = (context, agent) => {
|
|
422
|
+
const key = keyOf(context);
|
|
423
|
+
const model = typeof agent.model === "string" ? agent.model : null;
|
|
424
|
+
const usage = isRecord(context) && isRecord(context.usage) ? context.usage : {};
|
|
425
|
+
const entries = Array.isArray(usage.requestUsageEntries) ? usage.requestUsageEntries : [];
|
|
426
|
+
for (const entry of entries) {
|
|
427
|
+
const details = isRecord(entry.inputTokensDetails) ? entry.inputTokensDetails : {};
|
|
428
|
+
hooks.model(conversation, model, { in: count(entry.inputTokens), out: count(entry.outputTokens), cached: count(details.cached_tokens) ?? 0 }, key);
|
|
429
|
+
}
|
|
430
|
+
hooks.close(key);
|
|
431
|
+
};
|
|
432
|
+
runner.on("agent_handoff", onHandoff);
|
|
433
|
+
runner.on("agent_start", onStart);
|
|
434
|
+
runner.on("agent_tool_start", onToolStart);
|
|
435
|
+
runner.on("agent_tool_end", onToolEnd);
|
|
436
|
+
runner.on("agent_end", onEnd);
|
|
437
|
+
return () => {
|
|
438
|
+
runner.off("agent_handoff", onHandoff);
|
|
439
|
+
runner.off("agent_start", onStart);
|
|
440
|
+
runner.off("agent_tool_start", onToolStart);
|
|
441
|
+
runner.off("agent_tool_end", onToolEnd);
|
|
442
|
+
runner.off("agent_end", onEnd);
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
function parsed(text) {
|
|
446
|
+
if (typeof text !== "string") return text;
|
|
447
|
+
try {
|
|
448
|
+
return JSON.parse(text);
|
|
449
|
+
} catch {
|
|
450
|
+
return text;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function textOf(content) {
|
|
454
|
+
if (typeof content === "string") return content;
|
|
455
|
+
if (!Array.isArray(content)) return "";
|
|
456
|
+
return content.map((part) => isRecord(part) && (part.type === "input_text" || part.type === "output_text") && typeof part.text === "string" ? part.text : "").join("");
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
exports.NiadraSession = NiadraSession;
|
|
460
|
+
exports.attestationProof = attestationProof;
|
|
461
|
+
exports.niadraInstructions = niadraInstructions;
|
|
462
|
+
exports.niadraRunHooks = niadraRunHooks;
|
|
463
|
+
exports.niadraTools = niadraTools;
|
|
464
|
+
//# sourceMappingURL=openai-agents.cjs.map
|
|
465
|
+
//# sourceMappingURL=openai-agents.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ids.ts","../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/openai-agents.ts"],"names":["MemorySession","tool"],"mappings":";;;;;;;AAAA,IAAI,MAAA,GAAS,EAAA;AACb,IAAI,OAAA,GAAU,CAAA;AAEd,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,MAAM,CAAA;AACnC,EAAA,MAAM,YAAa,UAAA,CAChB,MAAA;AACH,EAAA,IAAI,WAAW,eAAA,EAAiB;AAC9B,IAAA,SAAA,CAAU,gBAAgB,KAAK,CAAA;AAAA,EACjC,CAAA,MAAO;AAEL,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,EAAQ,CAAA,EAAA,EAAK,KAAA,CAAM,CAAC,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,GAAG,CAAA;AAAA,EAC5E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A,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAGA,SAAS,OAAO,OAAA,EAA0B;AACxC,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,EAAU,OAAO,OAAA;AACxC,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,OAAO,GAAG,OAAO,EAAA;AACpC,EAAA,OAAQ,OAAA,CACL,IAAI,CAAC,IAAA,KAAU,SAAS,IAAI,CAAA,KAAM,IAAA,CAAK,IAAA,KAAS,YAAA,IAAgB,IAAA,CAAK,SAAS,aAAA,CAAA,IAAkB,OAAO,KAAK,IAAA,KAAS,QAAA,GAAW,KAAK,IAAA,GAAO,EAAG,CAAA,CAC/I,IAAA,CAAK,EAAE,CAAA;AACZ","file":"openai-agents.cjs","sourcesContent":["let lastMs = -1;\nlet counter = 0;\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n const webCrypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } })\n .crypto;\n if (webCrypto?.getRandomValues) {\n webCrypto.getRandomValues(bytes);\n } else {\n // Node 18 hides Web Crypto behind a flag; idempotency keys need uniqueness, not secrecy.\n for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\n/**\n * A UUIDv7 (RFC 9562): time-ordered, so keys minted by one process sort in the order the\n * events happened. A 12-bit counter keeps keys monotonic within the same millisecond.\n */\nexport function uuidv7(now: number = Date.now()): string {\n let ms = now;\n if (ms <= lastMs) {\n ms = lastMs;\n counter = (counter + 1) & 0xfff;\n if (counter === 0) ms += 1;\n } else {\n counter = (randomBytes(2)[0] ?? 0) & 0x7f;\n }\n lastMs = ms;\n\n const bytes = randomBytes(16);\n const high = Math.floor(ms / 2 ** 16);\n const low = ms % 2 ** 16;\n bytes[0] = (high >>> 24) & 0xff;\n bytes[1] = (high >>> 16) & 0xff;\n bytes[2] = (high >>> 8) & 0xff;\n bytes[3] = high & 0xff;\n bytes[4] = (low >>> 8) & 0xff;\n bytes[5] = low & 0xff;\n bytes[6] = 0x70 | ((counter >>> 8) & 0x0f);\n bytes[7] = counter & 0xff;\n bytes[8] = 0x80 | ((bytes[8] ?? 0) & 0x3f);\n\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(16).padStart(2, \"0\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * `tool()`: records each call of a function tool in the turn it runs in, whatever the framework.\n *\n * ```ts\n * const quote = niadra.tool(\"quote\", async (plan: string) => pricing.quote(plan), {\n * provenance: (r) => [{ ref: `health_quote:op:${r.id}`, fields: r.prices }],\n * });\n * ```\n *\n * Inside a turn, a call records its arguments when it starts (the single argument, or the list of them),\n * its result or its failure when it ends, its latency, and the call it was made in. `provenance` turns a\n * result into the objects it showed, each `{ref, fields, provenance}`: without provenance an observation is\n * for display only. `ui` gives the form of the result the interface got, when it differs from the one the\n * model saw. Outside a turn, the tool runs untouched and nothing is recorded. The recording never fails the\n * tool: a provenance function that throws marks the turn incomplete, and the tool's own result and errors\n * pass through unchanged. An async generator is recorded piece by piece, and its result is the list of\n * pieces once it is consumed.\n *\n * When the space binds the tool (its `tool-bindings` document, which the SDK profile serves this source by the\n * tool's name), a call in a turn that read the constraints block records what it did with the block: the hard\n * constraints its arguments sent, and over the objects its result shows, how many were checked, broke one, or\n * lacked the field. Nothing is changed. A binding lives in the space's configuration, never in code.\n *\n * With `maskOutput: true`, the fields the key may not read never reach the model (`capture/mask.ts`); the record\n * keeps what the model saw. Left unset, the binding's `capabilities.mask_output` decides.\n *\n * In a replay (`replay/`) the call answers from the record when its arguments match a recorded call of the\n * tool; otherwise it runs only when `dryRun: true` says running it again is safe, and answers `undefined` (a\n * divergence) when not.\n */\n\nimport { parseBinding, relaxed, resultItems } from \"../constraints/binding.js\";\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport { honored, render } from \"../constraints/render.js\";\nimport type { CallCapture, Observation, TurnFrame } from \"./frame.js\";\nimport { currentTurn } from \"./frame.js\";\nimport { protect } from \"./mask.js\";\nimport type { Access, OnUnknown } from \"./mask.js\";\n\nexport interface ToolOptions<A extends unknown[], R> {\n /** The objects a result showed, each `{ref, fields, provenance}`. */\n provenance?: (result: Awaited<R>) => Observation | readonly Observation[] | null | undefined;\n /** The form of the result the interface got, when it differs from the model's. */\n ui?: (result: Awaited<R>) => unknown;\n /** What the record keeps as the arguments; by default the single argument, or the list of them. */\n args?: (...args: A) => unknown;\n /** A replay may run the tool for real when the record has no answer for it. */\n dryRun?: boolean;\n /** The provider's id of the call, when the framework passes it to the tool. */\n callId?: (...args: A) => string | null | undefined;\n /** The turn to record in when the async context does not carry one (a framework that runs tools elsewhere). */\n frame?: () => TurnFrame | null | undefined;\n /** The bindings the SDK profile serves, by tool name; by default the client's (`niadra.tool`) or the turn's. */\n served?: (tool: string) => RawBinding | null;\n /** Keeps the fields this key may not read from the model; left unset, the binding's capability decides. */\n maskOutput?: boolean;\n /** With no profile ever read: `pass` (the default) lets the result through, `block` withholds it. */\n onUnknown?: OnUnknown;\n /** The fields each type hides; by default the SDK profile of the client (`niadra.tool`) or of the turn. */\n access?: Access;\n}\n\n/** What `tool()` knows of the function it wraps, for the runners that call it again. */\nexport interface RecordedTool {\n name: string;\n dryRun: boolean;\n provenance: ((result: never) => Observation | readonly Observation[] | null | undefined) | null;\n}\n\nconst RECORDED = Symbol.for(\"niadra.tool\");\n\n/** The `tool()` of `fn`, if it is one. */\nexport function recordedTool(fn: unknown): RecordedTool | null {\n return typeof fn === \"function\" ? ((fn as unknown as Record<symbol, RecordedTool | undefined>)[RECORDED] ?? null) : null;\n}\n\nconst isAsyncFunction = (fn: unknown): boolean => Object.prototype.toString.call(fn) === \"[object AsyncFunction]\";\n\nfunction isAsyncIterator(value: unknown): value is AsyncGenerator {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { next?: unknown }).next === \"function\" &&\n Symbol.asyncIterator in value\n );\n}\n\nfunction found(frame: (() => TurnFrame | null | undefined) | undefined): TurnFrame | undefined {\n try {\n return frame?.() ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction thenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n}\n\n/** Records the calls of `fn` as the tool `name`. See the module. */\nexport function tool<A extends unknown[], R>(\n name: string,\n fn: (...args: A) => R,\n options: ToolOptions<A, R> = {},\n): (...args: A) => R {\n const isAsync = isAsyncFunction(fn);\n\n /** The binding the SDK profile serves for the tool's name. */\n function bindingOf(frame: TurnFrame | undefined): RawBinding | null {\n return (options.served ?? frame?.profile.bindings)?.(name) ?? null;\n }\n\n /** Whether the output is masked: `maskOutput` when the code says it, else the binding's capability. */\n function masks(frame: TurnFrame | undefined): boolean {\n return options.maskOutput ?? bindingOf(frame)?.capabilities?.mask_output ?? false;\n }\n\n /** The result as the model may get it. */\n function shield(result: unknown, frame: TurnFrame | undefined): unknown {\n if (!masks(frame)) return result;\n const access = options.access ?? frame?.profile.fieldAccess ?? ((): null => null);\n return protect(result, access(), typesOf(result), options.onUnknown ?? \"pass\");\n }\n\n function typesOf(result: unknown): string[] | null {\n if (!options.provenance) return null;\n try {\n const found = options.provenance(result as Awaited<R>);\n const items = found == null ? [] : Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.map((o) => o.ref.split(\":\")[0] ?? \"\");\n } catch {\n return null;\n }\n }\n\n function end(call: CallCapture, result: unknown, model: unknown = result): void {\n const observations = observed(call, result);\n let shown: unknown;\n if (options.ui) {\n try {\n shown = options.ui(result as Awaited<R>);\n } catch {\n call.frame.incomplete();\n }\n }\n call.result(model, { ui: shown, observations });\n }\n\n function observed(call: CallCapture, result: unknown): Observation[] {\n if (!options.provenance) return [];\n try {\n const found = options.provenance(result as Awaited<R>);\n if (found == null) return [];\n const items = Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.filter((o) => typeof o.ref === \"string\" && typeof o.fields === \"object\");\n } catch {\n call.frame.incomplete();\n return [];\n }\n }\n\n async function* pieces(call: CallCapture, source: AsyncGenerator): AsyncGenerator {\n const kept: unknown[] = [];\n try {\n for await (const piece of source) {\n const shown = shield(piece, call.frame);\n kept.push(shown);\n yield shown;\n }\n } catch (error) {\n call.failed(error);\n throw error;\n }\n end(call, kept);\n }\n\n const wrapped = function (this: unknown, ...args: A): R {\n const frame = currentTurn() ?? found(options.frame);\n if (frame === undefined || frame.closed) {\n if (!masks(frame)) return fn.apply(this, args);\n const out = fn.apply(this, args);\n if (isAsyncIterator(out)) return maskedPieces(out, frame) as R;\n return (thenable(out) ? Promise.resolve(out).then((v) => shield(v, frame)) : shield(out, frame)) as R;\n }\n let recorded: unknown;\n let callId: string | null | undefined;\n try {\n recorded = options.args ? options.args(...args) : args.length === 1 ? args[0] : args;\n callId = options.callId?.(...args);\n } catch {\n recorded = args;\n }\n const call = frame.adopt(name, recorded) ?? frame.toolCall(name, recorded, typeof callId === \"string\" && callId ? { callId } : {});\n const binding = bindingOf(frame);\n if (binding !== null && frame.constraints !== null) call.measure = measure(frame, binding, recorded);\n if (frame.playback !== null) call.played = frame.playback.answer(name, recorded, options.dryRun ?? false);\n if (call.played !== null && !call.played.live) {\n const value = call.played.value;\n end(call, value);\n return (isAsync ? Promise.resolve(value) : value) as R;\n }\n let result: R;\n try {\n result = call.run(() => fn.apply(this, args));\n } catch (error) {\n call.failed(error);\n throw error;\n }\n if (isAsyncIterator(result)) return pieces(call, result) as R;\n if (thenable(result)) {\n return Promise.resolve(result).then(\n (value) => {\n const shown = shield(value, frame);\n end(call, value, shown);\n return shown;\n },\n (error: unknown) => {\n call.failed(error);\n throw error;\n },\n ) as R;\n }\n const shown = shield(result, frame);\n end(call, result, shown);\n return shown as R;\n };\n\n async function* maskedPieces(source: AsyncGenerator, frame: TurnFrame | undefined): AsyncGenerator {\n for await (const piece of source) yield shield(piece, frame);\n }\n\n Object.defineProperty(wrapped, \"name\", { value: fn.name || name });\n const marker: RecordedTool = {\n name,\n dryRun: options.dryRun ?? false,\n provenance: (options.provenance ?? null),\n };\n Object.defineProperty(wrapped, RECORDED, { value: marker });\n return wrapped;\n}\n\n/** How the call's result honored the block its arguments were rendered against; `null` when it does not apply. */\nfunction measure(frame: TurnFrame, raw: RawBinding, args: unknown): ((result: unknown) => Record<string, unknown> | null) | null {\n const block = frame.constraints;\n if (block === null) return null;\n const given = typeof args === \"object\" && args !== null && !Array.isArray(args) ? (args as Record<string, unknown>) : {};\n const rendering = render(block, parseBinding(raw, frame.profile.families?.() ?? {}), { args: given });\n if (!rendering.applies) return null;\n return (result) => {\n const seen = honored(block, rendering.hardSent, resultItems(raw, result));\n return {\n constraints: block.version,\n hard_sent: [...rendering.hardSent],\n results_checked: seen.resultsChecked,\n violations: seen.violations,\n unverifiable: seen.unverifiable,\n ...(relaxed(raw, result) ? { relaxed: \"declared\" } : {}),\n };\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 /**\n * How long ago Niadra sent or confirmed the pack served, in milliseconds: 0 for an answer just received,\n * growing while a cached pack is served (`cache`, `stale`, or `fallback` with Niadra down), and `null` when\n * there is no pack.\n */\n ageMs: number | null;\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 ageMs: number | null = 0,\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, ageMs, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", ageMs: null, 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 the OpenAI Agents SDK for JavaScript (`@openai/agents` 0.18).\n *\n * - `NiadraSession` is a `Session` for `run(agent, input, { session })`: it keeps the run's items\n * in the session you give it (a `MemorySession` by default) and records what the customer said\n * and what the agent answered as turns, the same way on every run.\n * - `niadraInstructions(base, conversation)` makes the agent's instructions dynamic: your text,\n * then the agent's notes and the customer's pack, then the suffix.\n * - `niadraTools(conversation)` is the navigation kit as function tools bound to the customer.\n * - `niadraRunHooks(runner, conversation)` records handoffs between agents, and with `turns: true` each run\n * as a turn record: each tool call with its call id, arguments and result, and each model request with\n * its tokens. A run inside a turn in progress (`conversation.turn()` around `runner.run`) records into it.\n * A function wrapped with `tool()` inside a tool takes over its call, which is how a replay answers it:\n * the Runner runs a tool before any hook could answer for it.\n *\n * Fail-open: when Niadra is slow or down, the instructions are yours alone and the run goes on.\n */\n\nimport { MemorySession, tool } from \"@openai/agents\";\nimport type { Agent, AgentInputItem, FunctionTool, RunContext, Runner, Session as AgentsSession } from \"@openai/agents\";\nimport type { Conversation } from \"../conversation.js\";\nimport { uuidv7 } from \"../ids.js\";\nimport { Bridge, TurnHooks, count, isRecord } 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 NiadraSessionOptions {\n /** Where the run's items live. Defaults to a new `MemorySession`. */\n inner?: AgentsSession;\n /** Records what the customer said. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records what the agent answered. Defaults to `true`. */\n recordAgent?: boolean;\n}\n\n/**\n * A `Session` that records the conversation's turns in Niadra while another session keeps the\n * run's items. Pass it to `run()`: `run(agent, input, { session: new NiadraSession(convo) })`.\n */\nexport class NiadraSession implements AgentsSession {\n private readonly inner: AgentsSession;\n private readonly bridge: Bridge;\n\n constructor(\n readonly conversation: Session,\n private readonly options: NiadraSessionOptions = {},\n ) {\n this.inner = options.inner ?? new MemorySession({ sessionId: conversation.id });\n this.bridge = new Bridge(conversation);\n }\n\n getSessionId(): Promise<string> {\n return this.inner.getSessionId();\n }\n\n getItems(limit?: number): Promise<AgentInputItem[]> {\n return this.inner.getItems(limit);\n }\n\n async addItems(items: AgentInputItem[]): Promise<void> {\n await this.inner.addItems(items);\n for (const item of items as unknown[]) {\n if (!isRecord(item)) continue;\n if (item.role === \"user\" && (this.options.recordCustomer ?? true)) this.bridge.customer(textOf(item.content));\n if (item.role === \"assistant\" && (this.options.recordAgent ?? true)) this.bridge.agent(textOf(item.content));\n }\n }\n\n popItem(): Promise<AgentInputItem | undefined> {\n return this.inner.popItem();\n }\n\n clearSession(): Promise<void> {\n return this.inner.clearSession();\n }\n}\n\nexport interface NiadraInstructionsOptions {\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */\n agentMemory?: AgentMemoryOption;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- the same shape as the SDK's own `instructions`,\n which takes an agent of any context and output type. */\ntype InstructionsFunction = (runContext: RunContext<any>, agent: Agent<any, any>) => string | Promise<string>;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/**\n * Dynamic instructions: your text, then the agent's notes and the customer's pack, then the\n * suffix. The Agents SDK builds the system prompt from the instructions alone, so the suffix\n * closes it rather than the input. Use as `new Agent({ instructions: niadraInstructions(...) })`.\n */\nexport function niadraInstructions(\n base: string | InstructionsFunction,\n session: Session,\n options: NiadraInstructionsOptions = {},\n): (...args: Parameters<InstructionsFunction>) => Promise<string> {\n const bridge = new Bridge(session, options.verify, options.agentMemory);\n return async (runContext, agent) => {\n const own = typeof base === \"function\" ? await base(runContext, agent) : base;\n const read = await bridge.read();\n bridge.injected(read.context);\n return [own, read.prefix, read.suffix].filter(Boolean).join(\"\\n\\n\");\n };\n}\n\n/** The navigation kit as Agents SDK function tools, bound to the session's customer. */\nexport function niadraTools(session: Session, options: { agentMemory?: AgentMemoryOption } = {}): FunctionTool[] {\n return new Bridge(session, undefined, options.agentMemory).tools().map((spec) =>\n tool({\n name: spec.name,\n description: spec.description,\n // The canonical schemas have optional fields, so the tool is not strict.\n parameters: spec.parameters as never,\n strict: false,\n execute: async (input: unknown) => spec.execute(isRecord(input) ? input : {}),\n }) as unknown as FunctionTool,\n );\n}\n\nexport interface NiadraRunHooksOptions {\n /** Records each run as a turn, with its tool calls and model requests. Defaults to `false`. */\n turns?: boolean;\n}\n\n/**\n * Records each handoff between agents of a run as a handoff to another agent, and with `turns: true` the\n * run's turn record. Returns a function that stops listening.\n */\nexport function niadraRunHooks(runner: Runner, conversation: Conversation, options: NiadraRunHooksOptions = {}): () => void {\n const bridge = new Bridge(conversation);\n const hooks = new TurnHooks(\"openai-agents\", options.turns ?? false);\n const keys = new WeakMap<object, string>();\n const keyOf = (context: object): string => {\n let key = keys.get(context);\n if (key === undefined) {\n key = uuidv7();\n keys.set(context, key);\n }\n return key;\n };\n const onHandoff = (_context: unknown, from: { name: string }, to: { name: string }): void => {\n void bridge.handoff(\"agent\", `${from.name} to ${to.name}`);\n };\n const onStart = (context: object, agent: { name: string }): void => {\n hooks.open(conversation, keyOf(context), { agent: agent.name });\n };\n const onToolStart = (context: object, _agent: unknown, tool: { name: string }, details: { toolCall: unknown }): void => {\n const call = isRecord(details.toolCall) ? details.toolCall : {};\n const callId = typeof call.callId === \"string\" ? call.callId : null;\n hooks.toolStart(conversation, callId ?? uuidv7(), tool.name, parsed(call.arguments), { frameKey: keyOf(context), callId });\n };\n const onToolEnd = (_context: object, _agent: unknown, _tool: unknown, result: string, details: { toolCall: unknown }): void => {\n const call = isRecord(details.toolCall) ? details.toolCall : {};\n if (typeof call.callId === \"string\") hooks.toolEnd(call.callId, result);\n };\n const onEnd = (context: object, agent: { model?: unknown }): void => {\n const key = keyOf(context);\n const model = typeof agent.model === \"string\" ? agent.model : null;\n const usage = isRecord(context) && isRecord(context.usage) ? context.usage : {};\n const entries = Array.isArray(usage.requestUsageEntries) ? (usage.requestUsageEntries as Record<string, unknown>[]) : [];\n for (const entry of entries) {\n const details = isRecord(entry.inputTokensDetails) ? entry.inputTokensDetails : {};\n hooks.model(conversation, model, { in: count(entry.inputTokens), out: count(entry.outputTokens), cached: count(details.cached_tokens) ?? 0 }, key);\n }\n hooks.close(key);\n };\n runner.on(\"agent_handoff\", onHandoff);\n runner.on(\"agent_start\", onStart as never);\n runner.on(\"agent_tool_start\", onToolStart as never);\n runner.on(\"agent_tool_end\", onToolEnd as never);\n runner.on(\"agent_end\", onEnd as never);\n return () => {\n runner.off(\"agent_handoff\", onHandoff);\n runner.off(\"agent_start\", onStart as never);\n runner.off(\"agent_tool_start\", onToolStart as never);\n runner.off(\"agent_tool_end\", onToolEnd as never);\n runner.off(\"agent_end\", onEnd as never);\n };\n}\n\nfunction parsed(text: unknown): unknown {\n if (typeof text !== \"string\") return text;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n\n/** The text of a user or assistant item: a string, or its `input_text` and `output_text` parts. */\nfunction textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return (content as unknown[])\n .map((part) => (isRecord(part) && (part.type === \"input_text\" || part.type === \"output_text\") && typeof part.text === \"string\" ? part.text : \"\"))\n .join(\"\");\n}\n"]}
|