@anvia/core 1.0.0-rc.1 → 1.0.0-rc.2

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 (136) hide show
  1. package/README.md +283 -84
  2. package/dist/agent/index.d.ts +26 -18
  3. package/dist/agent/index.js +19 -15
  4. package/dist/agent-yBG8e9Jj.d.ts +153 -0
  5. package/dist/chunk-4WI3VGZK.js +127 -0
  6. package/dist/chunk-4WI3VGZK.js.map +1 -0
  7. package/dist/{chunk-R2LJSQUW.js → chunk-77AIYARB.js} +251 -104
  8. package/dist/chunk-77AIYARB.js.map +1 -0
  9. package/dist/chunk-AI5JMUW7.js +45 -0
  10. package/dist/chunk-AI5JMUW7.js.map +1 -0
  11. package/dist/chunk-BEYBU7VJ.js +53 -0
  12. package/dist/chunk-BEYBU7VJ.js.map +1 -0
  13. package/dist/chunk-CWM7B2OO.js +315 -0
  14. package/dist/chunk-CWM7B2OO.js.map +1 -0
  15. package/dist/{chunk-6WGGTJE6.js → chunk-D37WMSP6.js} +52 -60
  16. package/dist/chunk-D37WMSP6.js.map +1 -0
  17. package/dist/{chunk-IL3ZSNJI.js → chunk-DBSCKTUL.js} +845 -800
  18. package/dist/chunk-DBSCKTUL.js.map +1 -0
  19. package/dist/chunk-EINTGEGY.js +629 -0
  20. package/dist/chunk-EINTGEGY.js.map +1 -0
  21. package/dist/chunk-FMHLROPQ.js +351 -0
  22. package/dist/chunk-FMHLROPQ.js.map +1 -0
  23. package/dist/{chunk-A3UBYTJT.js → chunk-FN7HLLAZ.js} +60 -6
  24. package/dist/chunk-FN7HLLAZ.js.map +1 -0
  25. package/dist/chunk-GKDERULJ.js +50 -0
  26. package/dist/chunk-GKDERULJ.js.map +1 -0
  27. package/dist/{chunk-FNQB2JEH.js → chunk-KIDGIJM7.js} +26 -5
  28. package/dist/chunk-KIDGIJM7.js.map +1 -0
  29. package/dist/chunk-KR3RCCHJ.js +500 -0
  30. package/dist/chunk-KR3RCCHJ.js.map +1 -0
  31. package/dist/{chunk-I6G7BC42.js → chunk-MGNTXGTX.js} +2 -6
  32. package/dist/chunk-MGNTXGTX.js.map +1 -0
  33. package/dist/{chunk-5XKDW36Z.js → chunk-OJH6HWHX.js} +64 -75
  34. package/dist/chunk-OJH6HWHX.js.map +1 -0
  35. package/dist/chunk-QOUPWOGW.js +29 -0
  36. package/dist/chunk-QOUPWOGW.js.map +1 -0
  37. package/dist/chunk-TIZYTPJO.js +208 -0
  38. package/dist/chunk-TIZYTPJO.js.map +1 -0
  39. package/dist/{chunk-DMPUP4R3.js → chunk-XKYYBABH.js} +5 -5
  40. package/dist/client-B8DT1vUG.d.ts +83 -0
  41. package/dist/completion/index.d.ts +5 -4
  42. package/dist/completion/index.js +25 -28
  43. package/dist/{dynamic-tools-i9woysFa.d.ts → dynamic-tools-KwEGRbHp.d.ts} +21 -9
  44. package/dist/embeddings/index.d.ts +11 -9
  45. package/dist/embeddings/index.js +2 -3
  46. package/dist/evals/index.d.ts +44 -24
  47. package/dist/evals/index.js +86 -69
  48. package/dist/evals/index.js.map +1 -1
  49. package/dist/extractor/index.d.ts +23 -26
  50. package/dist/extractor/index.js +7 -8
  51. package/dist/guardrails/index.d.ts +2 -1
  52. package/dist/guardrails/index.js +1 -1
  53. package/dist/image-generation/index.d.ts +18 -16
  54. package/dist/image-generation/index.js +2 -2
  55. package/dist/index.d.ts +24 -22
  56. package/dist/index.js +50 -48
  57. package/dist/internal/agent.d.ts +30 -19
  58. package/dist/internal/agent.js +13 -11
  59. package/dist/loaders/index.d.ts +2 -1
  60. package/dist/mcp/index.d.ts +19 -13
  61. package/dist/mcp/index.js +13 -348
  62. package/dist/mcp/index.js.map +1 -1
  63. package/dist/memory/index.d.ts +20 -6
  64. package/dist/memory/index.js +10 -10
  65. package/dist/message-schema-Cn7ezRfJ.d.ts +52 -0
  66. package/dist/{middleware-KynLg_RW.d.ts → middleware-C7PdmKF7.d.ts} +4 -4
  67. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  68. package/dist/model-listing/index.d.ts +3 -1
  69. package/dist/observability/index.d.ts +19 -5
  70. package/dist/observability/index.js +8 -5
  71. package/dist/observability/index.js.map +1 -1
  72. package/dist/pipeline/index.d.ts +105 -56
  73. package/dist/pipeline/index.js +422 -230
  74. package/dist/pipeline/index.js.map +1 -1
  75. package/dist/{retry-D3Ruy-ba.d.ts → retry-CjvSlKGW.d.ts} +2 -1
  76. package/dist/skills/index.d.ts +5 -4
  77. package/dist/skills/index.js +7 -7
  78. package/dist/speech-generation/index.d.ts +37 -0
  79. package/dist/speech-generation/index.js +8 -0
  80. package/dist/{think-tool-DZqZj2LV.d.ts → think-tool-6H2QNQzQ.d.ts} +1 -1
  81. package/dist/tool/index.d.ts +9 -7
  82. package/dist/tool/index.js +7 -10
  83. package/dist/{tool-C_8GudXn.d.ts → tool--Mz4v1eL.d.ts} +15 -7
  84. package/dist/transcription/index.d.ts +23 -14
  85. package/dist/transcription/index.js +2 -2
  86. package/dist/{index-DxB74ybJ.d.ts → types-3x3mOLHU.d.ts} +94 -64
  87. package/dist/types-BVzM4RsC.d.ts +155 -0
  88. package/dist/types-CQ_ioXWK.d.ts +319 -0
  89. package/dist/types-Cr4uiYo5.d.ts +99 -0
  90. package/dist/{types-DhQfwiZn.d.ts → types-DiJqJejp.d.ts} +1 -1
  91. package/dist/types-Dld1TpWj.d.ts +130 -0
  92. package/dist/vector-store/index.d.ts +33 -34
  93. package/dist/vector-store/index.js +6 -6
  94. package/package.json +6 -10
  95. package/dist/agent-DGYY_onS.d.ts +0 -145
  96. package/dist/audio-generation/index.d.ts +0 -31
  97. package/dist/audio-generation/index.js +0 -8
  98. package/dist/chunk-5XKDW36Z.js.map +0 -1
  99. package/dist/chunk-6WGGTJE6.js.map +0 -1
  100. package/dist/chunk-A3UBYTJT.js.map +0 -1
  101. package/dist/chunk-ADH7NNCS.js +0 -512
  102. package/dist/chunk-ADH7NNCS.js.map +0 -1
  103. package/dist/chunk-DZ3CKYTH.js +0 -267
  104. package/dist/chunk-DZ3CKYTH.js.map +0 -1
  105. package/dist/chunk-FNQB2JEH.js.map +0 -1
  106. package/dist/chunk-I6G7BC42.js.map +0 -1
  107. package/dist/chunk-IL3ZSNJI.js.map +0 -1
  108. package/dist/chunk-J6GNQART.js +0 -122
  109. package/dist/chunk-J6GNQART.js.map +0 -1
  110. package/dist/chunk-M3IOWB4Y.js +0 -280
  111. package/dist/chunk-M3IOWB4Y.js.map +0 -1
  112. package/dist/chunk-QY5GZ7HR.js +0 -39
  113. package/dist/chunk-QY5GZ7HR.js.map +0 -1
  114. package/dist/chunk-R2LJSQUW.js.map +0 -1
  115. package/dist/chunk-RFDVKCIE.js +0 -12
  116. package/dist/chunk-RFDVKCIE.js.map +0 -1
  117. package/dist/chunk-RMUBRRSK.js +0 -34
  118. package/dist/chunk-RMUBRRSK.js.map +0 -1
  119. package/dist/chunk-RXKHOYEH.js +0 -466
  120. package/dist/chunk-RXKHOYEH.js.map +0 -1
  121. package/dist/chunk-XDRSPSR7.js +0 -38
  122. package/dist/chunk-XDRSPSR7.js.map +0 -1
  123. package/dist/chunk-XWUC7CIT.js +0 -1
  124. package/dist/chunk-XWUC7CIT.js.map +0 -1
  125. package/dist/errors-CYKUcU89.d.ts +0 -17
  126. package/dist/json-Zo7K3xmt.d.ts +0 -40
  127. package/dist/types-B3A4YxaA.d.ts +0 -354
  128. package/dist/types-BBEGKB9m.d.ts +0 -119
  129. package/dist/types-DT3nEemY.d.ts +0 -79
  130. package/dist/types-DulRCYdB.d.ts +0 -70
  131. package/dist/types-p55Jc-sr.d.ts +0 -47
  132. package/dist/ui/index.d.ts +0 -107
  133. package/dist/ui/index.js +0 -10
  134. package/dist/ui/index.js.map +0 -1
  135. /package/dist/{chunk-DMPUP4R3.js.map → chunk-XKYYBABH.js.map} +0 -0
  136. /package/dist/{audio-generation → speech-generation}/index.js.map +0 -0
package/README.md CHANGED
@@ -33,7 +33,7 @@ const client = new OpenAIClient({
33
33
  apiKey,
34
34
  });
35
35
 
36
- const model = client.completionModel("gpt-5");
36
+ const model = client.completionModel({ modelId: "gpt-5", api: "responses" });
37
37
 
38
38
  const lookupOrder = createTool({
39
39
  name: "lookup_order",
@@ -44,141 +44,210 @@ const lookupOrder = createTool({
44
44
 
45
45
  const agent = new Agent({
46
46
  id: "support",
47
- model: model,
47
+ model,
48
48
  instructions: "Help customers with order questions.",
49
49
  maxTurns: 4,
50
50
  tools: [lookupOrder],
51
51
  });
52
52
 
53
- const response = await agent.prompt("What is happening with order A123?").send();
54
-
55
- console.log(response.output);
53
+ const result = await agent.generate({ prompt: "What is happening with order A123?" });
54
+ if (result.status === "completed") console.log(result.output);
56
55
  ```
57
56
 
58
57
  ## Direct Completions
59
58
 
60
- Use `createCompletion` when you want a single provider call without agent turns, memory, or
61
- tool execution:
59
+ Use `generateCompletion` for one provider call without Agent turns, memory, or local tool
60
+ execution. The model and input are part of one options object:
62
61
 
63
62
  ```ts
64
- import { createCompletion } from "@anvia/core";
63
+ import { generateCompletion } from "@anvia/core";
65
64
  import { OpenAIClient } from "@anvia/openai";
66
65
 
67
- const model = new OpenAIClient({ apiKey }).completionModel("gpt-5");
66
+ const model = new OpenAIClient({ apiKey }).completionModel({ modelId: "gpt-5", api: "responses" });
68
67
 
69
- const result = await createCompletion(model, {
70
- input: "Summarize Anvia in one sentence.",
68
+ const result = await generateCompletion({
69
+ model,
70
+ prompt: "Summarize Anvia in one sentence.",
71
71
  instructions: "Answer clearly and concisely.",
72
72
  });
73
73
 
74
- console.log(result.text);
74
+ console.log(result.output); // string
75
75
  ```
76
76
 
77
- Use `messages` when you already own the transcript. If `input` is also provided, it is appended as
78
- the final message:
77
+ Use `messages` when the application already owns the transcript. Exactly one of `prompt` or
78
+ `messages` is required:
79
79
 
80
80
  ```ts
81
- import { Message, createCompletion } from "@anvia/core";
81
+ import { generateCompletion, type Message } from "@anvia/core";
82
82
 
83
- const result = await createCompletion(model, {
83
+ const result = await generateCompletion({
84
+ model,
84
85
  messages: [
85
- Message.system("You are concise."),
86
- Message.user("Explain Anvia."),
87
- ],
86
+ { role: "system", content: "You are concise." },
87
+ { role: "user", content: "Explain Anvia." },
88
+ ] satisfies readonly Message[],
88
89
  maxTokens: 300,
89
- params: {
90
+ providerOptions: {
90
91
  reasoning: { effort: "low" },
91
92
  },
92
93
  });
93
94
  ```
94
95
 
95
- Use `createCompletionStream` to receive raw completion stream events from the model:
96
+ Messages are plain, readonly `{ role, content }` objects. Use structural literals with
97
+ `satisfies Message` or `satisfies readonly Message[]`; there is no message factory namespace.
98
+ Multimodal user content uses `text`, `image`, and `file` parts, while assistant tool calls use
99
+ `{ type: "tool-call", toolCallId, toolName, input }`. At external boundaries, validate with
100
+ `parseMessage`, `parseMessages`, `messageSchema`, or an application-specific
101
+ `createMessageSchema({ metadataSchema })`.
102
+
103
+ Add `outputSchema` to the same function for typed, schema-validated output:
96
104
 
97
105
  ```ts
98
- import { createCompletionStream } from "@anvia/core";
106
+ import { generateCompletion } from "@anvia/core";
107
+ import { z } from "zod";
99
108
 
100
- for await (const event of createCompletionStream(model, {
101
- input: "Write a short launch note.",
109
+ const result = await generateCompletion({
110
+ model,
111
+ prompt: "Extract: Acme reports a high-priority checkout failure.",
112
+ outputSchema: z.object({
113
+ customer: z.string(),
114
+ priority: z.enum(["low", "medium", "high"]),
115
+ }),
116
+ });
117
+
118
+ console.log(result.output.priority); // fully typed
119
+ ```
120
+
121
+ `CompletionResult` consistently contains `output`, the original `text`, normalized `content`,
122
+ `usage`, and `rawResponse`, plus optional message, context, source, and provider-tool metadata.
123
+
124
+ Use `streamCompletion` for the streaming form:
125
+
126
+ ```ts
127
+ import { streamCompletion } from "@anvia/core";
128
+
129
+ for await (const event of streamCompletion({
130
+ model,
131
+ prompt: "Write a short launch note.",
102
132
  })) {
103
133
  if (event.type === "text_delta") process.stdout.write(event.delta);
134
+ if (event.type === "final") console.log(event.result.usage);
135
+ if (event.type === "error") console.error(event.error);
104
136
  }
105
137
  ```
106
138
 
107
- React hooks keep `UIMessage[]` state locally, but send core `Message[]` in their request body. Pass
108
- those messages directly to `createCompletionStream`:
139
+ Tool-call deltas are always emitted when a provider supplies them; there is no opt-in flag. A
140
+ high-level stream emits at most one terminal `error` event and then closes. Provider model adapters
141
+ use the lower-level `CompletionModelStreamEvent`, whose terminal event is `{ type: "final",
142
+ response }`; `streamCompletion` normalizes it to `{ type: "final", result }`.
109
143
 
110
- ```ts
111
- import { createCompletionStream } from "@anvia/core";
112
- import type { UIStreamRequest } from "@anvia/core/ui";
144
+ Client requests carry core `Message[]`, so an endpoint can validate and pass them directly:
113
145
 
114
- const body = (await request.json()) as UIStreamRequest;
146
+ ```ts
147
+ import { completionToClientStream, parseClientStreamRequest } from "@anvia/client";
148
+ import { streamCompletion } from "@anvia/core";
149
+ import { createClientStreamResponse } from "@anvia/server";
115
150
 
116
- const events = createCompletionStream(model, {
117
- messages: body.messages,
151
+ const body = parseClientStreamRequest(await request.json());
152
+ const events = completionToClientStream({
153
+ events: streamCompletion({ model, messages: body.messages }),
118
154
  });
155
+ return createClientStreamResponse({ events });
119
156
  ```
120
157
 
121
- Use `createParsedCompletion` when you want a direct completion to return schema-validated data:
158
+ Core does not own UI messages, HTTP transports, or the public wire protocol. Those boundaries live
159
+ in `@anvia/client`, `@anvia/server`, and framework packages such as `@anvia/react`.
160
+
161
+ ## Retries, Provider Options, and Cancellation
162
+
163
+ Direct completion and media calls accept `retries?: RetryOptions | false`. An omitted or `false`
164
+ value makes one provider attempt; `{}` enables the default retry policy. Only retry-safe provider
165
+ calls are repeated.
122
166
 
123
167
  ```ts
124
- import { createParsedCompletion } from "@anvia/core";
125
- import { z } from "zod";
168
+ const controller = new AbortController();
126
169
 
127
- const eventSchema = z.object({
128
- name: z.string(),
129
- date: z.string(),
170
+ const result = await generateCompletion({
171
+ model,
172
+ prompt: "Summarize this incident.",
173
+ retries: { maxAttempts: 3, initialDelayMs: 100, maxDelayMs: 1_000 },
174
+ abortSignal: controller.signal,
175
+ providerOptions: { reasoning: { effort: "medium" } },
130
176
  });
177
+ ```
178
+
179
+ `providerOptions` contains strict JSON passed to an adapter. Canonical Anvia fields such as model,
180
+ input, temperature, tools, dimensions, text, and voice take precedence over conflicting provider
181
+ keys. Cancellation is forwarded to provider SDK calls and is never retried.
182
+
183
+ ## Agents
184
+
185
+ Agents own their default retry policy. A run with no `retries` value inherits the Agent setting;
186
+ `false` disables it for that run; an object replaces it for that run. Retries apply to the current
187
+ provider call only, so completed tools and earlier turns are never replayed.
131
188
 
132
- const event = await createParsedCompletion(model, {
133
- schema: eventSchema,
134
- input: "Alice and Bob are going to a science fair on Friday.",
189
+ ```ts
190
+ const agent = new Agent({
191
+ id: "support",
192
+ model,
193
+ retries: { maxAttempts: 3 },
135
194
  });
136
195
 
137
- console.log(event.data);
196
+ await agent.generate({ prompt: "Try normally." });
197
+ await agent.generate({ prompt: "Do not retry this run.", retries: false });
198
+ await agent.generate({
199
+ prompt: "Use one custom policy.",
200
+ retries: { maxAttempts: 2, initialDelayMs: 0, maxDelayMs: 0 },
201
+ });
138
202
  ```
139
203
 
140
- ## Prompts and Memory
141
-
142
- Use a plain prompt for stateless calls:
204
+ Agent results are discriminated by `status`. Completed results include typed `output` and `text`;
205
+ guardrail blocks return `status: "blocked"`, `stage`, and `text`; tool approval can return
206
+ `status: "approval_required"`.
143
207
 
144
208
  ```ts
145
- await agent.prompt("Summarize this ticket.").send();
209
+ const result = await agent.generate({ prompt: "Help with this request." });
210
+
211
+ if (result.status === "completed") console.log(result.output);
212
+ if (result.status === "blocked") console.log(result.stage, result.text);
146
213
  ```
147
214
 
148
- Use a message array when you already own the transcript. The last message is the active prompt and earlier messages are request history:
215
+ An Agent with `outputSchema` carries that output type through `generate`, `stream`, `asTool`, and
216
+ Pipeline Agent stages. Agent stream finals use the same result shape:
149
217
 
150
218
  ```ts
151
- import { Message } from "@anvia/core";
152
-
153
- await agent
154
- .prompt([
155
- Message.user("My project is named Anvia."),
156
- Message.assistant("Noted."),
157
- Message.user("What is my project named?"),
158
- ])
159
- .send();
219
+ for await (const event of agent.stream({ prompt: "Help with this request." })) {
220
+ if (event.type === "final") {
221
+ if (event.result.status === "completed") console.log(event.result.output);
222
+ else console.log(event.result.stage, event.result.text);
223
+ }
224
+ }
160
225
  ```
161
226
 
162
- Configure durable conversation memory on the agent, then run through a session:
227
+ Pass `abortSignal` on a run to cancel the active provider call, tools, and nested Agent tools.
228
+
229
+ ## Memory
230
+
231
+ Configure durable conversation memory on the Agent, then run through a session:
163
232
 
164
233
  ```ts
165
234
  import { Agent, type MemoryStore, type Message } from "@anvia/core";
166
- import type { MemoryAppendInput, MemoryContext } from "@anvia/core/memory";
235
+ import type { MemoryAppendOptions, MemoryScope } from "@anvia/core/memory";
167
236
 
168
237
  class AppMemoryStore implements MemoryStore {
169
238
  private readonly sessions = new Map<string, Message[]>();
170
239
 
171
- async load(context: MemoryContext): Promise<Message[]> {
172
- return [...(this.sessions.get(context.sessionId) ?? [])];
240
+ async load({ scope }: { scope: MemoryScope }): Promise<Message[]> {
241
+ return [...(this.sessions.get(scope.sessionId) ?? [])];
173
242
  }
174
243
 
175
- async append(input: MemoryAppendInput): Promise<void> {
176
- const current = this.sessions.get(input.context.sessionId) ?? [];
177
- this.sessions.set(input.context.sessionId, [...current, ...input.messages]);
244
+ async append(input: MemoryAppendOptions): Promise<void> {
245
+ const current = this.sessions.get(input.scope.sessionId) ?? [];
246
+ this.sessions.set(input.scope.sessionId, [...current, ...input.messages]);
178
247
  }
179
248
 
180
- async clear(context: MemoryContext): Promise<void> {
181
- this.sessions.delete(context.sessionId);
249
+ async clear({ scope }: { scope: MemoryScope }): Promise<void> {
250
+ this.sessions.delete(scope.sessionId);
182
251
  }
183
252
  }
184
253
 
@@ -189,8 +258,9 @@ const agent = new Agent({
189
258
  memory: { store: memory },
190
259
  });
191
260
 
192
- await agent.session("thread_123", { userId: "user_456" }).prompt("Remember my plan.").send();
193
- await agent.session("thread_123", { userId: "user_456" }).prompt("What is my plan?").send();
261
+ const session = { sessionId: "thread_123", userId: "user_456" };
262
+ await agent.generate({ prompt: "Remember my plan.", session });
263
+ await agent.generate({ prompt: "What is my plan?", session });
194
264
  ```
195
265
 
196
266
  Memory defaults to `savePolicy: "message"`, which saves the user prompt, each completed assistant message, and each completed tool result as soon as they are ready. You can choose `"turn"` or `"run"` at configuration time:
@@ -203,10 +273,52 @@ new Agent({
203
273
  });
204
274
  ```
205
275
 
276
+ Without `session`, the same Agent is stateless. Pass `{ messages }` when the caller already owns a
277
+ complete transcript; transcripts cannot be combined with persisted sessions.
278
+
279
+ Compaction is an explicit Agent policy over a store capability. The adapter persists the summary as
280
+ an ordinary system message with `metadata.anvia.memoryCompaction`, so `load()` and inspectors expose
281
+ exactly what future runs receive:
282
+
283
+ ```ts
284
+ import { createSummaryMemoryCompactor } from "@anvia/core/memory";
285
+
286
+ const compactor = createSummaryMemoryCompactor({
287
+ model: summaryModel,
288
+ maxTokens: 1024,
289
+ retries: { maxAttempts: 2 },
290
+ });
291
+
292
+ const agent = new Agent({
293
+ id: "support",
294
+ model,
295
+ memory: {
296
+ store: memory,
297
+ savePolicy: "message",
298
+ compaction: {
299
+ trigger: { afterMessages: 50 },
300
+ retention: { recentUserTurns: 4 },
301
+ compactor,
302
+ conflictRetries: false,
303
+ },
304
+ },
305
+ });
306
+
307
+ for await (const event of agent.stream({ prompt: "What did we decide?", session })) {
308
+ if (event.type === "memory_compaction") {
309
+ console.log(event.compactedMessageCount, event.usage);
310
+ }
311
+ }
312
+ ```
313
+
314
+ The trigger is a threshold, not a hard storage limit. Summary-provider retries belong to the
315
+ compactor; full snapshot-to-replacement conflict retries are separately opt-in.
316
+
206
317
  ## Structured Extraction
207
318
 
208
319
  ```ts
209
- import { ExtractorBuilder } from "@anvia/core/extractor";
320
+ import { extract } from "@anvia/core/extractor";
321
+ import { z } from "zod";
210
322
 
211
323
  const ticketSchema = z.object({
212
324
  customer: z.string(),
@@ -214,45 +326,132 @@ const ticketSchema = z.object({
214
326
  summary: z.string(),
215
327
  });
216
328
 
217
- const extractor = new ExtractorBuilder(model, ticketSchema).retries(1).build();
218
-
219
- const ticket = await extractor.extract(
220
- "Acme Co. reports checkout failures. Priority is high.",
221
- );
329
+ const { output: ticket } = await extract({
330
+ model,
331
+ text: "Acme Co. reports checkout failures. Priority is high.",
332
+ outputSchema: ticketSchema,
333
+ retries: { maxAttempts: 2 },
334
+ });
222
335
  ```
223
336
 
224
337
  ## Pipelines
225
338
 
226
339
  ```ts
227
- import { PipelineBuilder } from "@anvia/core/pipeline";
340
+ import { Pipeline } from "@anvia/core/pipeline";
228
341
  import { z } from "zod";
229
342
 
230
- const pipeline = new PipelineBuilder(z.string())
231
- .step((input) => `Extract this support ticket:\n\n${input}`)
232
- .prompt(agent)
233
- .extract(extractor)
234
- .build();
343
+ const pipeline = new Pipeline({ id: "support-flow", inputSchema: z.string() })
344
+ .agent({
345
+ id: "draft",
346
+ agent,
347
+ approval: "reject",
348
+ request: ({ input }) => ({ prompt: `Draft a reply for this ticket:\n\n${input}` }),
349
+ })
350
+ .extract({
351
+ id: "parse",
352
+ model,
353
+ outputSchema: ticketSchema,
354
+ text: ({ input }) => input,
355
+ });
356
+
357
+ const { runId, output } = await pipeline.run({
358
+ input: "Customer cannot complete checkout.",
359
+ });
360
+ ```
361
+
362
+ ## Media
363
+
364
+ Media helpers follow the same one-object API and share `providerOptions`, `retries`, and
365
+ `abortSignal`:
235
366
 
236
- const result = await pipeline.run("Customer cannot complete checkout.");
367
+ ```ts
368
+ import { generateImage, generateSpeech, transcribe } from "@anvia/core";
369
+
370
+ const image = await generateImage({
371
+ model: client.imageGenerationModel({ modelId: "gpt-image-1" }),
372
+ prompt: "A compact robot drawing an architecture diagram.",
373
+ width: 1024,
374
+ height: 1024,
375
+ });
376
+ console.log(image.images[0].data);
377
+
378
+ const speech = await generateSpeech({
379
+ model: client.speechGenerationModel({ modelId: "gpt-4o-mini-tts" }),
380
+ text: "Hello from Anvia.",
381
+ voice: "alloy",
382
+ });
383
+
384
+ const transcript = await transcribe({
385
+ model: client.transcriptionModel({ modelId: "gpt-4o-mini-transcribe" }),
386
+ audio: {
387
+ data: speech.audio.data,
388
+ filename: "speech.mp3",
389
+ mediaType: speech.audio.mediaType,
390
+ },
391
+ });
392
+ console.log(transcript.text);
237
393
  ```
238
394
 
395
+ ## MCP
396
+
397
+ MCP clients own connections. Agents receive immutable server registrations and never own or close
398
+ the underlying transport:
399
+
400
+ ```ts
401
+ import { Agent } from "@anvia/core/agent";
402
+ import { McpClient, McpClientGroup } from "@anvia/core/mcp";
403
+
404
+ const filesystem = new McpClient({
405
+ name: "filesystem",
406
+ transport: {
407
+ type: "stdio",
408
+ command: "npx",
409
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "./workspace"],
410
+ },
411
+ });
412
+ const github = new McpClient({
413
+ name: "github",
414
+ transport: {
415
+ type: "streamableHttp",
416
+ url: "https://mcp.example.com/mcp",
417
+ requestInit: { headers: { authorization: `Bearer ${process.env.MCP_TOKEN}` } },
418
+ },
419
+ tools: { prefix: "github_" },
420
+ });
421
+
422
+ const mcp = await McpClientGroup.connect({ clients: [filesystem, github] });
423
+ const agent = new Agent({ id: "assistant", model, mcpServers: mcp.servers });
424
+
425
+ try {
426
+ await agent.generate({ prompt: "Find the issue and update it." });
427
+ } finally {
428
+ await mcp.close();
429
+ }
430
+ ```
431
+
432
+ Construction performs no I/O. `connect()` discovers every tool page once and returns a frozen
433
+ registration snapshot. Reconnect and rebuild the Agent to adopt changed remote tools. Built-in
434
+ Streamable HTTP connections enforce Anvia URL safety and do not accept a custom `fetch`; use the
435
+ explicit caller-owned `custom` transport only when you intentionally own that security boundary.
436
+ MCP server instructions remain inspectable metadata and are not added to Agent instructions.
437
+
239
438
  ## Public Areas
240
439
 
241
- - `agent`: agent runtime and the compatibility `AgentBuilder`
440
+ - `agent`: typed Agent runtime, run results, approvals, retries, and stream events
242
441
  - `tool`: typed tool creation and tool sets
243
- - `completion`: provider-neutral completion request and response types
442
+ - `completion`: direct completion helpers and provider-neutral model contracts
244
443
  - `memory`: durable session memory interfaces and in-memory store
245
444
  - `extractor`: schema-first structured extraction
246
445
  - `pipeline`: typed sequential and parallel workflows
247
446
  - `embeddings`: embedding helpers and document embedding utilities
248
447
  - `vector-store`: in-memory vector search and vector search tools
249
448
  - `streaming`: normalized stream helpers
250
- - `mcp`: MCP server connection helpers
449
+ - `mcp`: lifecycle-owning MCP clients, groups, and immutable Agent registrations
251
450
  - `skills`: local skill loading
252
451
  - `observability`: observer interfaces for runs, generations, and tool calls
253
452
  - `evals`: evaluation helpers and reporters
254
453
  - `loaders`: document loading utilities
255
- - `audio-generation`, `image-generation`, `transcription`: provider-neutral media interfaces
454
+ - `speech-generation`, `image-generation`, `transcription`: provider-neutral media interfaces
256
455
 
257
456
  ## Development
258
457
 
@@ -1,22 +1,26 @@
1
- export { R as RetryContext, a as RetryOptions } from '../retry-D3Ruy-ba.js';
2
- export { A as Agent, a as AgentContextInput, b as AgentMemoryOptions, c as AgentObserverInput, d as AgentOptions, e as AgentSession, f as AgentToolInput, g as AgentToolOptions, C as ContextIndex, h as CreateContextIndexOptions, i as createContextIndex, j as isContextIndex } from '../agent-DGYY_onS.js';
3
- import { M as Message } from '../types-B3A4YxaA.js';
4
- export { A as AgentApprovalDecision, a as AgentApprovalRequiredEvent, b as AgentApprovalRequiredResult, c as AgentChildStreamEvent, d as AgentChildStreamEventWithToolCallDeltas, e as AgentChildStreamEventWithoutToolCallDeltas, f as AgentDeltaEvent, g as AgentErrorEvent, h as AgentErrorStreamEvent, i as AgentFinishEvent, j as AgentInput, k as AgentLifecycle, l as AgentResponse, m as AgentResult, n as AgentRunOptions, o as AgentStartEvent, p as AgentStepFinishEvent, q as AgentStream, r as AgentStreamEvent, s as AgentStreamEventWithToolCallDeltas, t as AgentStreamEventWithoutToolCallDeltas, u as AgentStreamOptions, v as AgentToolApprovalRequest, w as AgentToolCallDeltaEvent, x as AgentToolFinishEvent, y as AgentToolStartEvent } from '../index-DxB74ybJ.js';
5
- import '../guardrails/index.js';
6
- import '../type-utils-CtHVDRn_.js';
7
- import '../types-BBEGKB9m.js';
8
- import '../middleware-KynLg_RW.js';
9
- import '../tool-C_8GudXn.js';
1
+ export { M as ModelCallOptions } from '../model-call-options-CZkSw_xN.js';
2
+ export { R as RetryContext, a as RetryOptions, b as RetrySetting } from '../retry-CjvSlKGW.js';
3
+ export { A as Agent, a as AgentContextInput, b as AgentMemory, c as AgentMemoryOptions, d as AgentOptions, e as AgentToolInput, f as AgentToolOptions, C as CreateHybridVectorContextOptions, g as CreateVectorContextOptions, V as VectorContext, h as VectorContextBaseOptions, i as createVectorContext, j as isVectorContext } from '../agent-yBG8e9Jj.js';
4
+ import { M as Message } from '../types-CQ_ioXWK.js';
5
+ import { c as AgentBlockedResult } from '../types-3x3mOLHU.js';
6
+ export { A as AgentApprovalDecision, a as AgentApprovalRequiredEvent, b as AgentApprovalRequiredResult, d as AgentChildStreamEvent, e as AgentDeltaEvent, f as AgentErrorEvent, g as AgentErrorStreamEvent, h as AgentFinishEvent, i as AgentInput, j as AgentLifecycle, k as AgentMemoryCompactionEvent, l as AgentPrompt, m as AgentResponse, n as AgentResult, o as AgentRunOptions, p as AgentRunSettings, q as AgentStartEvent, r as AgentSteerInput, s as AgentStepFinishEvent, t as AgentStream, u as AgentStreamEvent, v as AgentToolApprovalRequest, w as AgentToolCallDeltaEvent, x as AgentToolFinishEvent, y as AgentToolStartEvent } from '../types-3x3mOLHU.js';
10
7
  import '../zod-schema-C7F4clpm.js';
11
8
  import 'zod';
12
- import '../types-DulRCYdB.js';
13
- import '@modelcontextprotocol/sdk/client/sse.js';
14
- import '@modelcontextprotocol/sdk/client/stdio.js';
9
+ import '../guardrails/index.js';
10
+ import '../type-utils-CtHVDRn_.js';
11
+ import '../client-B8DT1vUG.js';
12
+ import 'node:child_process';
13
+ import 'node:stream';
14
+ import '@modelcontextprotocol/sdk/client/auth.js';
15
15
  import '@modelcontextprotocol/sdk/client/streamableHttp.js';
16
- import '../types-DhQfwiZn.js';
17
- import '../dynamic-tools-i9woysFa.js';
18
- import '../types-p55Jc-sr.js';
19
- import '../types-DT3nEemY.js';
16
+ import '@modelcontextprotocol/sdk/shared/transport.js';
17
+ import '../tool--Mz4v1eL.js';
18
+ import '../middleware-C7PdmKF7.js';
19
+ import '../types-BVzM4RsC.js';
20
+ import '../types-DiJqJejp.js';
21
+ import '../dynamic-tools-KwEGRbHp.js';
22
+ import '../types-Cr4uiYo5.js';
23
+ import '../types-Dld1TpWj.js';
20
24
 
21
25
  declare class MaxTurnsError extends Error {
22
26
  readonly maxTurns: number;
@@ -27,7 +31,11 @@ declare class MaxTurnsError extends Error {
27
31
  declare class AgentRunCancelledError extends Error {
28
32
  readonly chatHistory: Message[];
29
33
  readonly reason: string;
30
- constructor(chatHistory: Message[], reason: string);
34
+ constructor(chatHistory: Message[], reason: string, options?: ErrorOptions);
35
+ }
36
+ declare class AgentRunBlockedError extends Error {
37
+ readonly result: AgentBlockedResult;
38
+ constructor(result: AgentBlockedResult);
31
39
  }
32
40
 
33
- export { AgentRunCancelledError, MaxTurnsError };
41
+ export { AgentBlockedResult, AgentRunBlockedError, AgentRunCancelledError, MaxTurnsError };
@@ -1,26 +1,30 @@
1
1
  import {
2
2
  Agent,
3
+ AgentRunBlockedError,
3
4
  AgentRunCancelledError,
4
5
  MaxTurnsError,
5
- createContextIndex,
6
- isContextIndex
7
- } from "../chunk-IL3ZSNJI.js";
6
+ createVectorContext,
7
+ isVectorContext
8
+ } from "../chunk-DBSCKTUL.js";
8
9
  import "../chunk-YK4WAAS4.js";
9
- import "../chunk-6WGGTJE6.js";
10
- import "../chunk-R2LJSQUW.js";
11
- import "../chunk-5XKDW36Z.js";
12
- import "../chunk-DZ3CKYTH.js";
13
- import "../chunk-I6G7BC42.js";
14
- import "../chunk-M3IOWB4Y.js";
15
- import "../chunk-RFDVKCIE.js";
16
- import "../chunk-ADH7NNCS.js";
17
- import "../chunk-A3UBYTJT.js";
18
- import "../chunk-FNQB2JEH.js";
10
+ import "../chunk-EINTGEGY.js";
11
+ import "../chunk-CQNNSZPG.js";
12
+ import "../chunk-D37WMSP6.js";
13
+ import "../chunk-77AIYARB.js";
14
+ import "../chunk-OJH6HWHX.js";
15
+ import "../chunk-CWM7B2OO.js";
16
+ import "../chunk-FMHLROPQ.js";
17
+ import "../chunk-MGNTXGTX.js";
18
+ import "../chunk-KR3RCCHJ.js";
19
+ import "../chunk-TIZYTPJO.js";
20
+ import "../chunk-KIDGIJM7.js";
21
+ import "../chunk-FN7HLLAZ.js";
19
22
  export {
20
23
  Agent,
24
+ AgentRunBlockedError,
21
25
  AgentRunCancelledError,
22
26
  MaxTurnsError,
23
- createContextIndex,
24
- isContextIndex
27
+ createVectorContext,
28
+ isVectorContext
25
29
  };
26
30
  //# sourceMappingURL=index.js.map