@anvia/core 1.0.0-rc.10 → 1.0.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -58,7 +58,7 @@ const agent = new Agent({
58
58
  });
59
59
 
60
60
  const result = await agent.generate({ prompt: "What is happening with order A123?" });
61
- if (result.status === "completed") console.log(result.output);
61
+ if (result.type === "response") console.log(result.output);
62
62
  ```
63
63
 
64
64
  ## Direct Completions
@@ -229,7 +229,7 @@ rather than recursively accumulating failed attempts. Truncated output and reaso
229
229
  parse and schema repairs include only a bounded, text-only preview of the latest failed response.
230
230
  The correction asks for shorter raw JSON matching the schema, without Markdown or commentary.
231
231
  Transport failures and structured-output failures therefore cannot exceed `maxAttempts` in total.
232
- Completed Agent results expose the last generation's `finishReason` and `providerFinishReason`, and
232
+ Agent response outcomes expose the last generation's `finishReason` and `providerFinishReason`, and
233
233
  the same fields remain attached to each assistant message's Anvia generation metadata.
234
234
 
235
235
  Malformed, incomplete, or non-JSON provider tool arguments fail with
@@ -256,30 +256,35 @@ exists; its message never contains the rejected model response. The `completion.
256
256
  event records the same safe diagnostics and whether failed output was omitted or previewed, never
257
257
  the model output itself.
258
258
 
259
- Agent results are discriminated by `status`. Completed results include typed `output` and `text`;
260
- guardrail blocks return `status: "blocked"`, `stage`, and `text`; tool approvals and first-class
261
- questions return a JSON-safe `status: "suspended"` result.
259
+ Agent outcomes are discriminated by `type`. Successful responses include typed `output` and `text`;
260
+ guardrail blocks return `type: "blocked"`, `stage`, `reason`, and an optional `message`; tool
261
+ approvals and first-class questions return a JSON-safe `type: "interaction"` outcome.
262
262
 
263
263
  ```ts
264
- const result = await agent.generate({ prompt: "Help with this request." });
265
-
266
- if (result.status === "completed") console.log(result.output);
267
- if (result.status === "blocked") console.log(result.stage, result.text);
268
- if (result.status === "suspended") {
269
- const resumed = await agent.generate({
270
- continuation: result.continuation,
271
- response:
272
- result.interaction.type === "tool-approval"
273
- ? { type: "tool-approval", approved: true }
264
+ const outcome = await agent.generate({ prompt: "Help with this request." });
265
+
266
+ switch (outcome.type) {
267
+ case "response":
268
+ console.log(outcome.output);
269
+ break;
270
+ case "blocked":
271
+ console.log(outcome.stage, outcome.reason);
272
+ break;
273
+ case "interaction": {
274
+ const response =
275
+ outcome.interaction.type === "tool-approval"
276
+ ? { type: "tool-approval" as const, approved: true }
274
277
  : {
275
- type: "tool-question",
276
- answers: result.interaction.questions.map((question) => ({
278
+ type: "tool-question" as const,
279
+ answers: outcome.interaction.questions.map((question) => ({
277
280
  questionId: question.id,
278
281
  value: "application-provided answer",
279
282
  })),
280
- },
281
- });
282
- console.log(resumed.status, resumed.resumedFrom);
283
+ };
284
+ const resumed = await agent.resume(outcome.continuation, response);
285
+ console.log(resumed.type, resumed.resumedFrom);
286
+ break;
287
+ }
283
288
  }
284
289
  ```
285
290
 
@@ -300,17 +305,27 @@ import {
300
305
  ```
301
306
 
302
307
  An Agent with `outputSchema` carries that output type through `generate`, `stream`, `asTool`, and
303
- Pipeline Agent stages. Agent stream finals use the same result shape:
308
+ Pipeline Agent stages. `stream()` returns a handle with one event consumer plus final-value
309
+ promises, steering, and cancellation. Terminal agent events are the flattened outcomes themselves;
310
+ there is no extra `final.result` wrapper:
304
311
 
305
312
  ```ts
306
- for await (const event of agent.stream({ prompt: "Help with this request." })) {
307
- if (event.type === "final") {
308
- if (event.result.status === "completed") console.log(event.result.output);
309
- else console.log(event.result.stage, event.result.text);
310
- }
313
+ const stream = agent.stream({ prompt: "Help with this request." });
314
+
315
+ for await (const event of stream.events) {
316
+ if (event.type === "text_delta") process.stdout.write(event.delta);
317
+ if (event.type === "response") console.log(event.output);
318
+ if (event.type === "interaction") console.log(event.interaction);
319
+ if (event.type === "blocked") console.log(event.reason);
311
320
  }
321
+
322
+ const outcome = await stream.result;
323
+ console.log(outcome.type, await stream.text);
312
324
  ```
313
325
 
326
+ Use `stream.textStream` instead of `stream.events` when only text deltas are needed. Event and text
327
+ iteration share one underlying stream and therefore cannot be consumed independently.
328
+
314
329
  Pass `abortSignal` on a run to cancel the active provider call, tools, and nested Agent tools.
315
330
 
316
331
  ## Memory
@@ -383,8 +398,8 @@ const agent = new Agent({
383
398
  store: memory,
384
399
  savePolicy: "message",
385
400
  compaction: {
386
- trigger: { afterMessages: 50 },
387
- retention: { recentUserTurns: 4 },
401
+ trigger: { afterTokens: 32_000 },
402
+ retention: { recentTokens: 8_000 },
388
403
  compactor,
389
404
  conflictRetries: false,
390
405
  },
@@ -393,13 +408,50 @@ const agent = new Agent({
393
408
 
394
409
  for await (const event of agent.stream({ prompt: "What did we decide?", session })) {
395
410
  if (event.type === "memory_compaction") {
396
- console.log(event.compactedMessageCount, event.usage);
411
+ console.log({
412
+ messages: event.compactedMessageCount,
413
+ beforeTokens: event.originalTokenCount,
414
+ afterTokens: event.resultTokenCount,
415
+ usage: event.usage,
416
+ });
397
417
  }
398
418
  }
399
419
  ```
400
420
 
401
- The trigger is a threshold, not a hard storage limit. Summary-provider retries belong to the
402
- compactor; full snapshot-to-replacement conflict retries are separately opt-in.
421
+ The trigger includes the stored transcript and the incoming user message. Retention keeps as many
422
+ recent complete user-led turns as fit the configured budget; the newest complete turn is always
423
+ kept and never split, even when it exceeds that budget. When `retention` is omitted, it defaults to
424
+ 25% of `afterTokens`.
425
+
426
+ The built-in token counter is a lightweight provider-neutral estimate. Pass `tokenCounter` when you
427
+ have a model-specific tokenizer or counting service. A custom counter may be async, can be called
428
+ multiple times, and must return deterministic, monotonic, nonnegative safe integers:
429
+
430
+ ```ts
431
+ compaction: {
432
+ trigger: { afterTokens: 32_000 },
433
+ retention: { recentTokens: 8_000 },
434
+ tokenCounter: (messages) => tokenizer.count(messages),
435
+ compactor,
436
+ }
437
+ ```
438
+
439
+ You can force the configured policy without starting an Agent run. The result makes a no-op
440
+ explicit rather than throwing:
441
+
442
+ ```ts
443
+ const result = await agent.compactMemory({ session });
444
+
445
+ if (result.type === "compacted") {
446
+ console.log(result.originalTokenCount, result.resultTokenCount);
447
+ } else {
448
+ console.log(result.reason); // "nothing_to_compact"
449
+ }
450
+ ```
451
+
452
+ The automatic trigger is a threshold, not a hard storage limit. Summary-provider retries belong to
453
+ the compactor; full snapshot-to-replacement conflict retries are separately opt-in. A streamed
454
+ `memory_compaction` event is emitted only after the store atomically commits the replacement.
403
455
 
404
456
  ## Structured Extraction
405
457
 
@@ -1,22 +1,22 @@
1
1
  export { M as ModelCallOptions } from '../model-call-options-CZkSw_xN.js';
2
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-DWzW9SoH.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-qRKa3ibC.js';
4
4
  import { M as Message, U as Usage, C as CompletionFinishReason } from '../types-DgvozfPc.js';
5
- import { A as AgentBlockedResult, t as AgentSuspendedResult } from '../types-Sue2hb_L.js';
6
- export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, g as AgentLifecycle, h as AgentMemoryCompactionEvent, i as AgentPrompt, j as AgentResponse, k as AgentResult, l as AgentRunOptions, m as AgentRunSettings, n as AgentStartEvent, o as AgentSteerInput, p as AgentSteerReceipt, q as AgentStepFinishEvent, r as AgentStream, s as AgentStreamEvent, u as AgentToolCallDeltaEvent, v as AgentToolFinishEvent, w as AgentToolStartEvent } from '../types-Sue2hb_L.js';
5
+ import { A as AgentBlockedOutcome, g as AgentInteractionOutcome } from '../types-CLCLFpAL.js';
6
+ export { a as AgentChildStreamEvent, b as AgentDeltaEvent, c as AgentErrorEvent, d as AgentErrorStreamEvent, e as AgentFinishEvent, f as AgentInput, h as AgentLifecycle, i as AgentMemoryCompactionEvent, j as AgentMemoryCompactionOptions, k as AgentOutcome, l as AgentPrompt, m as AgentResponse, n as AgentRunOptions, o as AgentRunSettings, p as AgentStartEvent, q as AgentSteerInput, r as AgentSteerReceipt, s as AgentStepFinishEvent, t as AgentStream, u as AgentStreamEvent, v as AgentToolCallDeltaEvent, w as AgentToolFinishEvent, x as AgentToolStartEvent } from '../types-CLCLFpAL.js';
7
7
  import '../zod-schema-C7F4clpm.js';
8
8
  import 'zod';
9
9
  import '../types-DhkodEft.js';
10
10
  import '../type-utils-CtHVDRn_.js';
11
11
  import '../types-DjqRHeAi.js';
12
12
  import '../tool-BpqpoRSE.js';
13
+ import '../types-CSYt7-It.js';
13
14
  import '../middleware-kcF8AusP.js';
14
- import '../types-DKOXVTcq.js';
15
+ import './interactions/index.js';
15
16
  import '../types-DC1U1XwW.js';
16
17
  import '../dynamic-tools-aIZlg5x1.js';
17
18
  import '../types-Cr4uiYo5.js';
18
19
  import '../types-CXNE592e.js';
19
- import './interactions/index.js';
20
20
 
21
21
  type AgentStructuredOutputPhase = "truncated" | "content-filter" | "parse" | "schema";
22
22
  type AgentStructuredOutputFormat = "raw" | "json-fence" | "unlabeled-fence";
@@ -57,15 +57,15 @@ declare class AgentRunCancelledError extends Error {
57
57
  constructor(chatHistory: Message[], reason: string, options?: ErrorOptions);
58
58
  }
59
59
  declare class AgentRunBlockedError extends Error {
60
- readonly result: AgentBlockedResult;
61
- constructor(result: AgentBlockedResult);
60
+ readonly result: AgentBlockedOutcome;
61
+ constructor(result: AgentBlockedOutcome);
62
62
  }
63
63
  declare class AgentStreamClosedError extends Error {
64
64
  constructor();
65
65
  }
66
66
  declare class AgentToolSuspensionError extends Error {
67
- readonly result: AgentSuspendedResult;
68
- constructor(result: AgentSuspendedResult);
67
+ readonly result: AgentInteractionOutcome;
68
+ constructor(result: AgentInteractionOutcome);
69
69
  }
70
70
 
71
- export { AgentBlockedResult, AgentRunBlockedError, AgentRunCancelledError, AgentStreamClosedError, AgentStructuredOutputError, type AgentStructuredOutputFormat, type AgentStructuredOutputPhase, AgentSuspendedResult, AgentToolSuspensionError, MaxTurnsError };
71
+ export { AgentBlockedOutcome, AgentInteractionOutcome, AgentRunBlockedError, AgentRunCancelledError, AgentStreamClosedError, AgentStructuredOutputError, type AgentStructuredOutputFormat, type AgentStructuredOutputPhase, AgentToolSuspensionError, MaxTurnsError };
@@ -2,10 +2,10 @@ import {
2
2
  Agent,
3
3
  createVectorContext,
4
4
  isVectorContext
5
- } from "../chunk-VX3HS6PE.js";
5
+ } from "../chunk-3ZLM6OAZ.js";
6
6
  import "../chunk-OJBFDBLG.js";
7
7
  import "../chunk-J6LVLV6P.js";
8
- import "../chunk-5C6B6ZRH.js";
8
+ import "../chunk-YA7BMX7D.js";
9
9
  import "../chunk-6BBOCFHV.js";
10
10
  import "../chunk-YK4WAAS4.js";
11
11
  import "../chunk-SJMSS5SI.js";
@@ -17,7 +17,7 @@ import {
17
17
  AgentStructuredOutputError,
18
18
  AgentToolSuspensionError,
19
19
  MaxTurnsError
20
- } from "../chunk-X4LK4ODN.js";
20
+ } from "../chunk-AHLKV6KP.js";
21
21
  import "../chunk-ZA564323.js";
22
22
  import "../chunk-3RM57ZT2.js";
23
23
  import "../chunk-D4PACGPA.js";
@@ -3,10 +3,11 @@ import { D as Document, c as CompletionModel, P as ProviderTool, J as JsonObject
3
3
  import { Z as ZodSchema } from './zod-schema-C7F4clpm.js';
4
4
  import { d as GuardrailPolicyInput, c as GuardrailPolicy } from './types-DhkodEft.js';
5
5
  import { a as McpServer } from './types-DjqRHeAi.js';
6
- import { g as AgentLifecycle, E as AgentObservabilityOptions, l as AgentRunOptions, k as AgentResult, r as AgentStream, s as AgentStreamEvent } from './types-Sue2hb_L.js';
6
+ import { E as MemoryStore, z as MemorySavePolicy, F as MemoryTokenCounter, n as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, y as MemoryOptions, k as MemoryCompactionResult } from './types-CSYt7-It.js';
7
+ import { h as AgentLifecycle, F as AgentObservabilityOptions, n as AgentRunOptions, k as AgentOutcome, o as AgentRunSettings, t as AgentStream, j as AgentMemoryCompactionOptions } from './types-CLCLFpAL.js';
7
8
  import { A as AgentMiddleware } from './middleware-kcF8AusP.js';
8
9
  import { A as AnyTool, T as Tool, c as ToolCallContext, N as NormalizedToolOutput } from './tool-BpqpoRSE.js';
9
- import { D as MemoryStore, y as MemorySavePolicy, m as MemoryCompactor, d as MemoryCompactionConflictRetryOptions, x as MemoryOptions } from './types-DKOXVTcq.js';
10
+ import { AgentContinuation, AgentInteractionResponse } from './agent/interactions/index.js';
10
11
  import { a as SkillSet } from './types-DC1U1XwW.js';
11
12
  import { T as ToolIndex } from './dynamic-tools-aIZlg5x1.js';
12
13
  import { E as EmbeddingModel, c as SparseEmbeddingModel } from './types-Cr4uiYo5.js';
@@ -74,11 +75,12 @@ type AgentMemory = {
74
75
  savePolicy: MemorySavePolicy;
75
76
  compaction?: {
76
77
  trigger: {
77
- afterMessages: number;
78
+ afterTokens: number;
78
79
  };
79
80
  retention: {
80
- recentUserTurns: number;
81
+ recentTokens: number;
81
82
  };
83
+ tokenCounter: MemoryTokenCounter;
82
84
  compactor: MemoryCompactor;
83
85
  conflictRetries: false | MemoryCompactionConflictRetryOptions;
84
86
  } | undefined;
@@ -138,8 +140,10 @@ declare class Agent<Output = string, M extends CompletionModel = CompletionModel
138
140
  readonly middlewares: readonly AgentMiddleware[];
139
141
  readonly memory: AgentMemory | undefined;
140
142
  constructor(options: AgentOptions<Output, M, ContextDocument>);
141
- generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentResult<Output>>;
142
- stream(options: AgentRunOptions<Output, RawResponseOf<M>>): AgentStream<AgentStreamEvent<Output, RawResponseOf<M>>>;
143
+ generate(options: AgentRunOptions<Output, RawResponseOf<M>>): Promise<AgentOutcome<Output>>;
144
+ resume(continuation: AgentContinuation, response: AgentInteractionResponse, settings?: AgentRunSettings<Output, RawResponseOf<M>>): Promise<AgentOutcome<Output>>;
145
+ stream(options: AgentRunOptions<Output, RawResponseOf<M>>): AgentStream<Output, RawResponseOf<M>>;
146
+ compactMemory(options: AgentMemoryCompactionOptions): Promise<MemoryCompactionResult>;
143
147
  asTool(options: AgentToolOptions): Tool<{
144
148
  prompt: string;
145
149
  }, Output>;