@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,75 @@
1
+ import { Session, AgentInputItem, RunContext, Agent, Runner, FunctionTool } from '@openai/agents';
2
+ import { bt as Conversation } from './client-DsIxZxZk.cjs';
3
+ import { a as ProofSource, A as AgentMemoryOption, b as Session$1 } from './shared-DTPWVlWm.cjs';
4
+ export { P as Proof, c as attestationProof } from './shared-DTPWVlWm.cjs';
5
+
6
+ /**
7
+ * Niadra for the OpenAI Agents SDK for JavaScript (`@openai/agents` 0.18).
8
+ *
9
+ * - `NiadraSession` is a `Session` for `run(agent, input, { session })`: it keeps the run's items
10
+ * in the session you give it (a `MemorySession` by default) and records what the customer said
11
+ * and what the agent answered as turns, the same way on every run.
12
+ * - `niadraInstructions(base, conversation)` makes the agent's instructions dynamic: your text,
13
+ * then the agent's notes and the customer's pack, then the suffix.
14
+ * - `niadraTools(conversation)` is the navigation kit as function tools bound to the customer.
15
+ * - `niadraRunHooks(runner, conversation)` records handoffs between agents, and with `turns: true` each run
16
+ * as a turn record: each tool call with its call id, arguments and result, and each model request with
17
+ * its tokens. A run inside a turn in progress (`conversation.turn()` around `runner.run`) records into it.
18
+ * A function wrapped with `tool()` inside a tool takes over its call, which is how a replay answers it:
19
+ * the Runner runs a tool before any hook could answer for it.
20
+ *
21
+ * Fail-open: when Niadra is slow or down, the instructions are yours alone and the run goes on.
22
+ */
23
+
24
+ interface NiadraSessionOptions {
25
+ /** Where the run's items live. Defaults to a new `MemorySession`. */
26
+ inner?: Session;
27
+ /** Records what the customer said. Defaults to `true`. */
28
+ recordCustomer?: boolean;
29
+ /** Records what the agent answered. Defaults to `true`. */
30
+ recordAgent?: boolean;
31
+ }
32
+ /**
33
+ * A `Session` that records the conversation's turns in Niadra while another session keeps the
34
+ * run's items. Pass it to `run()`: `run(agent, input, { session: new NiadraSession(convo) })`.
35
+ */
36
+ declare class NiadraSession implements Session {
37
+ readonly conversation: Session$1;
38
+ private readonly options;
39
+ private readonly inner;
40
+ private readonly bridge;
41
+ constructor(conversation: Session$1, options?: NiadraSessionOptions);
42
+ getSessionId(): Promise<string>;
43
+ getItems(limit?: number): Promise<AgentInputItem[]>;
44
+ addItems(items: AgentInputItem[]): Promise<void>;
45
+ popItem(): Promise<AgentInputItem | undefined>;
46
+ clearSession(): Promise<void>;
47
+ }
48
+ interface NiadraInstructionsOptions {
49
+ /** What your app proved about the user, recorded once before the first context read. */
50
+ verify?: ProofSource;
51
+ /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */
52
+ agentMemory?: AgentMemoryOption;
53
+ }
54
+ type InstructionsFunction = (runContext: RunContext<any>, agent: Agent<any, any>) => string | Promise<string>;
55
+ /**
56
+ * Dynamic instructions: your text, then the agent's notes and the customer's pack, then the
57
+ * suffix. The Agents SDK builds the system prompt from the instructions alone, so the suffix
58
+ * closes it rather than the input. Use as `new Agent({ instructions: niadraInstructions(...) })`.
59
+ */
60
+ declare function niadraInstructions(base: string | InstructionsFunction, session: Session$1, options?: NiadraInstructionsOptions): (...args: Parameters<InstructionsFunction>) => Promise<string>;
61
+ /** The navigation kit as Agents SDK function tools, bound to the session's customer. */
62
+ declare function niadraTools(session: Session$1, options?: {
63
+ agentMemory?: AgentMemoryOption;
64
+ }): FunctionTool[];
65
+ interface NiadraRunHooksOptions {
66
+ /** Records each run as a turn, with its tool calls and model requests. Defaults to `false`. */
67
+ turns?: boolean;
68
+ }
69
+ /**
70
+ * Records each handoff between agents of a run as a handoff to another agent, and with `turns: true` the
71
+ * run's turn record. Returns a function that stops listening.
72
+ */
73
+ declare function niadraRunHooks(runner: Runner, conversation: Conversation, options?: NiadraRunHooksOptions): () => void;
74
+
75
+ export { AgentMemoryOption, type NiadraInstructionsOptions, type NiadraRunHooksOptions, NiadraSession, type NiadraSessionOptions, ProofSource, Session$1 as Session, niadraInstructions, niadraRunHooks, niadraTools };
@@ -0,0 +1,75 @@
1
+ import { Session, AgentInputItem, RunContext, Agent, Runner, FunctionTool } from '@openai/agents';
2
+ import { bt as Conversation } from './client-DsIxZxZk.js';
3
+ import { a as ProofSource, A as AgentMemoryOption, b as Session$1 } from './shared-Bb5B59Bu.js';
4
+ export { P as Proof, c as attestationProof } from './shared-Bb5B59Bu.js';
5
+
6
+ /**
7
+ * Niadra for the OpenAI Agents SDK for JavaScript (`@openai/agents` 0.18).
8
+ *
9
+ * - `NiadraSession` is a `Session` for `run(agent, input, { session })`: it keeps the run's items
10
+ * in the session you give it (a `MemorySession` by default) and records what the customer said
11
+ * and what the agent answered as turns, the same way on every run.
12
+ * - `niadraInstructions(base, conversation)` makes the agent's instructions dynamic: your text,
13
+ * then the agent's notes and the customer's pack, then the suffix.
14
+ * - `niadraTools(conversation)` is the navigation kit as function tools bound to the customer.
15
+ * - `niadraRunHooks(runner, conversation)` records handoffs between agents, and with `turns: true` each run
16
+ * as a turn record: each tool call with its call id, arguments and result, and each model request with
17
+ * its tokens. A run inside a turn in progress (`conversation.turn()` around `runner.run`) records into it.
18
+ * A function wrapped with `tool()` inside a tool takes over its call, which is how a replay answers it:
19
+ * the Runner runs a tool before any hook could answer for it.
20
+ *
21
+ * Fail-open: when Niadra is slow or down, the instructions are yours alone and the run goes on.
22
+ */
23
+
24
+ interface NiadraSessionOptions {
25
+ /** Where the run's items live. Defaults to a new `MemorySession`. */
26
+ inner?: Session;
27
+ /** Records what the customer said. Defaults to `true`. */
28
+ recordCustomer?: boolean;
29
+ /** Records what the agent answered. Defaults to `true`. */
30
+ recordAgent?: boolean;
31
+ }
32
+ /**
33
+ * A `Session` that records the conversation's turns in Niadra while another session keeps the
34
+ * run's items. Pass it to `run()`: `run(agent, input, { session: new NiadraSession(convo) })`.
35
+ */
36
+ declare class NiadraSession implements Session {
37
+ readonly conversation: Session$1;
38
+ private readonly options;
39
+ private readonly inner;
40
+ private readonly bridge;
41
+ constructor(conversation: Session$1, options?: NiadraSessionOptions);
42
+ getSessionId(): Promise<string>;
43
+ getItems(limit?: number): Promise<AgentInputItem[]>;
44
+ addItems(items: AgentInputItem[]): Promise<void>;
45
+ popItem(): Promise<AgentInputItem | undefined>;
46
+ clearSession(): Promise<void>;
47
+ }
48
+ interface NiadraInstructionsOptions {
49
+ /** What your app proved about the user, recorded once before the first context read. */
50
+ verify?: ProofSource;
51
+ /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */
52
+ agentMemory?: AgentMemoryOption;
53
+ }
54
+ type InstructionsFunction = (runContext: RunContext<any>, agent: Agent<any, any>) => string | Promise<string>;
55
+ /**
56
+ * Dynamic instructions: your text, then the agent's notes and the customer's pack, then the
57
+ * suffix. The Agents SDK builds the system prompt from the instructions alone, so the suffix
58
+ * closes it rather than the input. Use as `new Agent({ instructions: niadraInstructions(...) })`.
59
+ */
60
+ declare function niadraInstructions(base: string | InstructionsFunction, session: Session$1, options?: NiadraInstructionsOptions): (...args: Parameters<InstructionsFunction>) => Promise<string>;
61
+ /** The navigation kit as Agents SDK function tools, bound to the session's customer. */
62
+ declare function niadraTools(session: Session$1, options?: {
63
+ agentMemory?: AgentMemoryOption;
64
+ }): FunctionTool[];
65
+ interface NiadraRunHooksOptions {
66
+ /** Records each run as a turn, with its tool calls and model requests. Defaults to `false`. */
67
+ turns?: boolean;
68
+ }
69
+ /**
70
+ * Records each handoff between agents of a run as a handoff to another agent, and with `turns: true` the
71
+ * run's turn record. Returns a function that stops listening.
72
+ */
73
+ declare function niadraRunHooks(runner: Runner, conversation: Conversation, options?: NiadraRunHooksOptions): () => void;
74
+
75
+ export { AgentMemoryOption, type NiadraInstructionsOptions, type NiadraRunHooksOptions, NiadraSession, type NiadraSessionOptions, ProofSource, Session$1 as Session, niadraInstructions, niadraRunHooks, niadraTools };
@@ -0,0 +1,459 @@
1
+ import { MemorySession, tool } from '@openai/agents';
2
+
3
+ // src/integrations/openai-agents.ts
4
+
5
+ // src/ids.ts
6
+ var lastMs = -1;
7
+ var counter = 0;
8
+ function randomBytes(length) {
9
+ const bytes = new Uint8Array(length);
10
+ const webCrypto = globalThis.crypto;
11
+ if (webCrypto?.getRandomValues) {
12
+ webCrypto.getRandomValues(bytes);
13
+ } else {
14
+ for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);
15
+ }
16
+ return bytes;
17
+ }
18
+ function uuidv7(now = Date.now()) {
19
+ let ms = now;
20
+ if (ms <= lastMs) {
21
+ ms = lastMs;
22
+ counter = counter + 1 & 4095;
23
+ if (counter === 0) ms += 1;
24
+ } else {
25
+ counter = (randomBytes(2)[0] ?? 0) & 127;
26
+ }
27
+ lastMs = ms;
28
+ const bytes = randomBytes(16);
29
+ const high = Math.floor(ms / 2 ** 16);
30
+ const low = ms % 2 ** 16;
31
+ bytes[0] = high >>> 24 & 255;
32
+ bytes[1] = high >>> 16 & 255;
33
+ bytes[2] = high >>> 8 & 255;
34
+ bytes[3] = high & 255;
35
+ bytes[4] = low >>> 8 & 255;
36
+ bytes[5] = low & 255;
37
+ bytes[6] = 112 | counter >>> 8 & 15;
38
+ bytes[7] = counter & 255;
39
+ bytes[8] = 128 | (bytes[8] ?? 0) & 63;
40
+ let hex = "";
41
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
42
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
43
+ }
44
+
45
+ // src/capture/tool.ts
46
+ var RECORDED = /* @__PURE__ */ Symbol.for("niadra.tool");
47
+ function recordedTool(fn) {
48
+ return typeof fn === "function" ? fn[RECORDED] ?? null : null;
49
+ }
50
+
51
+ // src/context.ts
52
+ function emptyResult(error) {
53
+ return { text: "", suffix: "", variables: {}, pack: null, source: "none", response: null, error, constraints: null, state: null, coordination: null };
54
+ }
55
+
56
+ // src/integrations/shared.ts
57
+ var ATTESTED = { A: "V2", B: "V1", C: "V1" };
58
+ function attestationProof(attestation) {
59
+ if (!attestation) return null;
60
+ const value = attestation.trim().toUpperCase();
61
+ if (value.includes("FAILED") || value.startsWith("NO-")) return null;
62
+ const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];
63
+ const level = letter ? ATTESTED[letter] : void 0;
64
+ return level ? { method: "network_attestation", level } : null;
65
+ }
66
+ function isConversation(session) {
67
+ return "customer" in session && typeof session.customer === "function";
68
+ }
69
+ function errorName(error) {
70
+ return error instanceof Error ? error.name : typeof error;
71
+ }
72
+ var Bridge = class {
73
+ constructor(session, proof, memory = false) {
74
+ this.session = session;
75
+ this.proof = proof;
76
+ this.memory = memory;
77
+ }
78
+ session;
79
+ proof;
80
+ memory;
81
+ proving = null;
82
+ /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */
83
+ begun = false;
84
+ opened = false;
85
+ /**
86
+ * The context and, when enabled, the agent's notes, read side by side within the same budget.
87
+ * Never rejects.
88
+ */
89
+ async read(options = {}) {
90
+ const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);
91
+ const [context, memory] = await Promise.all([
92
+ this.context(options),
93
+ memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve("")
94
+ ]);
95
+ return { context, memory, prefix: [memory, context.text].filter(Boolean).join("\n\n"), suffix: context.suffix };
96
+ }
97
+ get logger() {
98
+ return this.session.logger;
99
+ }
100
+ /**
101
+ * Starts the first read of a call now, in the background, after the proof when one was given (the
102
+ * pack depends on the level it proves): at call start, so the read runs while the call is set up.
103
+ * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.
104
+ */
105
+ begin() {
106
+ const session = this.session;
107
+ if (!isConversation(session)) return;
108
+ const start = () => {
109
+ this.safe("start the first read", () => {
110
+ this.begun = session.begin();
111
+ });
112
+ };
113
+ if (this.proof === void 0 || this.proof === null) start();
114
+ else void this.verifyOnce().then(start);
115
+ }
116
+ /** Verifies once (when a proof was given), then reads the context. Never rejects. */
117
+ async context(options = {}) {
118
+ await this.verifyOnce();
119
+ try {
120
+ const session = this.session;
121
+ if (this.begun && !this.opened && isConversation(session)) {
122
+ this.opened = true;
123
+ await session.ready(options.timeout === void 0 ? {} : { timeout: options.timeout });
124
+ }
125
+ return await this.session.context(options);
126
+ } catch (error) {
127
+ this.logger.warn(`could not read context (${errorName(error)})`);
128
+ return emptyResult(null);
129
+ }
130
+ }
131
+ /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */
132
+ injected(context) {
133
+ if (!context.text && !context.suffix && context.response?.path !== "holdout") return;
134
+ this.safe("mark the injection", () => {
135
+ this.session.markInjected(context);
136
+ });
137
+ }
138
+ customer(text, options = {}) {
139
+ const session = this.session;
140
+ if (!text.trim() || !isConversation(session)) return;
141
+ this.safe("record the customer's turn", () => session.customer(text, options));
142
+ }
143
+ /** Sends the customer's turn so far, while they speak. In the background; never throws. */
144
+ prefetch(text) {
145
+ const session = this.session;
146
+ if (!text.trim() || !isConversation(session)) return;
147
+ this.safe("prefetch the turn", () => session.prefetch(text));
148
+ }
149
+ agent(text, options = {}) {
150
+ if (!text.trim()) return;
151
+ this.safe("record the agent's turn", () => this.session.agent(text, options));
152
+ }
153
+ /** Records a transfer. Tasks have no transfer; the call is ignored for them. */
154
+ async handoff(target, reason) {
155
+ const session = this.session;
156
+ if (!isConversation(session)) return;
157
+ try {
158
+ await session.handoff(reason ? { target, reason } : { target });
159
+ } catch (error) {
160
+ this.logger.warn(`could not record the handoff (${errorName(error)})`);
161
+ }
162
+ }
163
+ async end() {
164
+ try {
165
+ await this.session.end();
166
+ } catch (error) {
167
+ this.logger.warn(`could not end the session (${errorName(error)})`);
168
+ }
169
+ }
170
+ /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */
171
+ tools() {
172
+ let bound;
173
+ try {
174
+ const memory = this.memory;
175
+ bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });
176
+ } catch (error) {
177
+ this.logger.warn(`could not build the tools (${errorName(error)})`);
178
+ return [];
179
+ }
180
+ return bound ? toolSpecs(bound) : [];
181
+ }
182
+ async agentMemory(params, options) {
183
+ try {
184
+ const result = await this.session.agentMemory(params, options.timeout === void 0 ? {} : { timeout: options.timeout });
185
+ return result.text;
186
+ } catch (error) {
187
+ this.logger.warn(`could not read the agent's memory (${errorName(error)})`);
188
+ return "";
189
+ }
190
+ }
191
+ async verifyOnce() {
192
+ if (this.proof === void 0 || this.proof === null) return;
193
+ this.proving ??= this.runVerify();
194
+ await this.proving;
195
+ }
196
+ async runVerify() {
197
+ try {
198
+ const source = this.proof;
199
+ const proof = typeof source === "function" ? await source() : source;
200
+ if (!proof) return;
201
+ await this.session.verify(proof);
202
+ } catch (error) {
203
+ this.logger.warn(`could not record the verification (${errorName(error)})`);
204
+ }
205
+ }
206
+ safe(what, run) {
207
+ try {
208
+ run();
209
+ } catch (error) {
210
+ this.logger.warn(`could not ${what} (${errorName(error)})`);
211
+ }
212
+ }
213
+ };
214
+ function withoutWrite(option) {
215
+ const { write: _, ...params } = option;
216
+ return params;
217
+ }
218
+ function toolSpecs(bound) {
219
+ return bound.definitions.map(({ function: definition }) => ({
220
+ name: definition.name,
221
+ description: definition.description,
222
+ parameters: definition.parameters,
223
+ execute: (args) => bound.call(definition.name, args)
224
+ }));
225
+ }
226
+ function isRecord(value) {
227
+ return typeof value === "object" && value !== null;
228
+ }
229
+ function count(value) {
230
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
231
+ }
232
+ var TurnHooks = class _TurnHooks {
233
+ constructor(adapter, enabled) {
234
+ this.adapter = adapter;
235
+ this.enabled = enabled;
236
+ }
237
+ adapter;
238
+ enabled;
239
+ /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */
240
+ static MAX_OPEN = 100;
241
+ frames = /* @__PURE__ */ new Map();
242
+ calls = /* @__PURE__ */ new Map();
243
+ /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */
244
+ open(session, key, params = {}) {
245
+ if (!this.enabled) return void 0;
246
+ const held = this.frames.get(key);
247
+ if (held !== void 0) return held.frame;
248
+ try {
249
+ const active = session.activeTurn();
250
+ if (active !== void 0 && !this.owns(active)) {
251
+ this.frames.set(key, { frame: active, own: false });
252
+ return active;
253
+ }
254
+ const frame = session.openTurn({ ...params, adapter: this.adapter });
255
+ this.frames.set(key, { frame, own: true });
256
+ if (this.frames.size > _TurnHooks.MAX_OPEN) {
257
+ const [oldest] = this.frames.keys();
258
+ if (oldest !== void 0) {
259
+ this.frames.get(oldest)?.frame.incomplete();
260
+ this.close(oldest);
261
+ }
262
+ }
263
+ return frame;
264
+ } catch (error) {
265
+ session.logger.warn(`could not open the turn (${errorName(error)})`);
266
+ return void 0;
267
+ }
268
+ }
269
+ /** The turn of `key`, else the session's turn in progress. */
270
+ frame(session, key) {
271
+ if (!this.enabled) return void 0;
272
+ const held = key === void 0 ? void 0 : this.frames.get(key);
273
+ const frame = held?.frame ?? session.activeTurn();
274
+ return frame === void 0 || frame.closed ? void 0 : frame;
275
+ }
276
+ has(key) {
277
+ return this.frames.has(key);
278
+ }
279
+ owns(frame) {
280
+ for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;
281
+ return false;
282
+ }
283
+ /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */
284
+ close(key, error) {
285
+ const held = this.frames.get(key);
286
+ if (held === void 0) return;
287
+ this.frames.delete(key);
288
+ for (const [callKey, call] of this.calls) {
289
+ if (call.frame !== held.frame) continue;
290
+ this.calls.delete(callKey);
291
+ if (held.own) call.failed(error ?? "error");
292
+ }
293
+ if (held.own) held.frame.close(error);
294
+ }
295
+ /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */
296
+ toolStart(session, callKey, name, args, options = {}) {
297
+ const frame = this.frame(session, options.frameKey);
298
+ if (frame === void 0) return;
299
+ try {
300
+ this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));
301
+ } catch {
302
+ frame.incomplete();
303
+ }
304
+ }
305
+ /**
306
+ * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the
307
+ * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function
308
+ * wrapped with `tool()`, which answers itself.
309
+ */
310
+ replayed(session, name, args, fn, frameKey) {
311
+ const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();
312
+ if (frame?.playback == null || fn !== void 0 && recordedTool(fn) !== null) return null;
313
+ return frame.playback.answer(name, args, false);
314
+ }
315
+ toolEnd(callKey, result, error) {
316
+ const call = this.calls.get(callKey);
317
+ if (call === void 0) return;
318
+ this.calls.delete(callKey);
319
+ try {
320
+ if (error !== void 0) call.failed(error);
321
+ else call.result(result);
322
+ } catch {
323
+ call.frame.incomplete();
324
+ }
325
+ }
326
+ /** A model call that ended, with its tokens when the framework reported them. */
327
+ model(session, model, tokens = {}, frameKey) {
328
+ const frame = this.frame(session, frameKey);
329
+ if (frame === void 0) return;
330
+ try {
331
+ frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });
332
+ } catch {
333
+ frame.incomplete();
334
+ }
335
+ }
336
+ };
337
+
338
+ // src/integrations/openai-agents.ts
339
+ var NiadraSession = class {
340
+ constructor(conversation, options = {}) {
341
+ this.conversation = conversation;
342
+ this.options = options;
343
+ this.inner = options.inner ?? new MemorySession({ sessionId: conversation.id });
344
+ this.bridge = new Bridge(conversation);
345
+ }
346
+ conversation;
347
+ options;
348
+ inner;
349
+ bridge;
350
+ getSessionId() {
351
+ return this.inner.getSessionId();
352
+ }
353
+ getItems(limit) {
354
+ return this.inner.getItems(limit);
355
+ }
356
+ async addItems(items) {
357
+ await this.inner.addItems(items);
358
+ for (const item of items) {
359
+ if (!isRecord(item)) continue;
360
+ if (item.role === "user" && (this.options.recordCustomer ?? true)) this.bridge.customer(textOf(item.content));
361
+ if (item.role === "assistant" && (this.options.recordAgent ?? true)) this.bridge.agent(textOf(item.content));
362
+ }
363
+ }
364
+ popItem() {
365
+ return this.inner.popItem();
366
+ }
367
+ clearSession() {
368
+ return this.inner.clearSession();
369
+ }
370
+ };
371
+ function niadraInstructions(base, session, options = {}) {
372
+ const bridge = new Bridge(session, options.verify, options.agentMemory);
373
+ return async (runContext, agent) => {
374
+ const own = typeof base === "function" ? await base(runContext, agent) : base;
375
+ const read = await bridge.read();
376
+ bridge.injected(read.context);
377
+ return [own, read.prefix, read.suffix].filter(Boolean).join("\n\n");
378
+ };
379
+ }
380
+ function niadraTools(session, options = {}) {
381
+ return new Bridge(session, void 0, options.agentMemory).tools().map(
382
+ (spec) => tool({
383
+ name: spec.name,
384
+ description: spec.description,
385
+ // The canonical schemas have optional fields, so the tool is not strict.
386
+ parameters: spec.parameters,
387
+ strict: false,
388
+ execute: async (input) => spec.execute(isRecord(input) ? input : {})
389
+ })
390
+ );
391
+ }
392
+ function niadraRunHooks(runner, conversation, options = {}) {
393
+ const bridge = new Bridge(conversation);
394
+ const hooks = new TurnHooks("openai-agents", options.turns ?? false);
395
+ const keys = /* @__PURE__ */ new WeakMap();
396
+ const keyOf = (context) => {
397
+ let key = keys.get(context);
398
+ if (key === void 0) {
399
+ key = uuidv7();
400
+ keys.set(context, key);
401
+ }
402
+ return key;
403
+ };
404
+ const onHandoff = (_context, from, to) => {
405
+ void bridge.handoff("agent", `${from.name} to ${to.name}`);
406
+ };
407
+ const onStart = (context, agent) => {
408
+ hooks.open(conversation, keyOf(context), { agent: agent.name });
409
+ };
410
+ const onToolStart = (context, _agent, tool2, details) => {
411
+ const call = isRecord(details.toolCall) ? details.toolCall : {};
412
+ const callId = typeof call.callId === "string" ? call.callId : null;
413
+ hooks.toolStart(conversation, callId ?? uuidv7(), tool2.name, parsed(call.arguments), { frameKey: keyOf(context), callId });
414
+ };
415
+ const onToolEnd = (_context, _agent, _tool, result, details) => {
416
+ const call = isRecord(details.toolCall) ? details.toolCall : {};
417
+ if (typeof call.callId === "string") hooks.toolEnd(call.callId, result);
418
+ };
419
+ const onEnd = (context, agent) => {
420
+ const key = keyOf(context);
421
+ const model = typeof agent.model === "string" ? agent.model : null;
422
+ const usage = isRecord(context) && isRecord(context.usage) ? context.usage : {};
423
+ const entries = Array.isArray(usage.requestUsageEntries) ? usage.requestUsageEntries : [];
424
+ for (const entry of entries) {
425
+ const details = isRecord(entry.inputTokensDetails) ? entry.inputTokensDetails : {};
426
+ hooks.model(conversation, model, { in: count(entry.inputTokens), out: count(entry.outputTokens), cached: count(details.cached_tokens) ?? 0 }, key);
427
+ }
428
+ hooks.close(key);
429
+ };
430
+ runner.on("agent_handoff", onHandoff);
431
+ runner.on("agent_start", onStart);
432
+ runner.on("agent_tool_start", onToolStart);
433
+ runner.on("agent_tool_end", onToolEnd);
434
+ runner.on("agent_end", onEnd);
435
+ return () => {
436
+ runner.off("agent_handoff", onHandoff);
437
+ runner.off("agent_start", onStart);
438
+ runner.off("agent_tool_start", onToolStart);
439
+ runner.off("agent_tool_end", onToolEnd);
440
+ runner.off("agent_end", onEnd);
441
+ };
442
+ }
443
+ function parsed(text) {
444
+ if (typeof text !== "string") return text;
445
+ try {
446
+ return JSON.parse(text);
447
+ } catch {
448
+ return text;
449
+ }
450
+ }
451
+ function textOf(content) {
452
+ if (typeof content === "string") return content;
453
+ if (!Array.isArray(content)) return "";
454
+ return content.map((part) => isRecord(part) && (part.type === "input_text" || part.type === "output_text") && typeof part.text === "string" ? part.text : "").join("");
455
+ }
456
+
457
+ export { NiadraSession, attestationProof, niadraInstructions, niadraRunHooks, niadraTools };
458
+ //# sourceMappingURL=openai-agents.js.map
459
+ //# sourceMappingURL=openai-agents.js.map