@anvia/core 1.0.0-rc.9 → 1.0.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 (50) hide show
  1. package/README.md +99 -77
  2. package/dist/agent/index.d.ts +11 -16
  3. package/dist/agent/index.js +8 -8
  4. package/dist/{agent-XPQBM4rX.d.ts → agent-qRKa3ibC.d.ts} +11 -7
  5. package/dist/{chunk-PISJAAMX.js → chunk-3ZLM6OAZ.js} +318 -114
  6. package/dist/chunk-3ZLM6OAZ.js.map +1 -0
  7. package/dist/{chunk-WZVHZZW6.js → chunk-6BBOCFHV.js} +2 -2
  8. package/dist/{chunk-WTRGYFCD.js → chunk-7PHMK7W4.js} +4 -4
  9. package/dist/{chunk-X4LK4ODN.js → chunk-AHLKV6KP.js} +1 -1
  10. package/dist/chunk-AHLKV6KP.js.map +1 -0
  11. package/dist/chunk-J6LVLV6P.js +13 -0
  12. package/dist/chunk-J6LVLV6P.js.map +1 -0
  13. package/dist/{chunk-KIXN5DGS.js → chunk-LTXABCOO.js} +2 -2
  14. package/dist/{chunk-QOUPWOGW.js → chunk-SPD4XVR7.js} +1 -1
  15. package/dist/{chunk-TC4FILD3.js → chunk-YA7BMX7D.js} +51 -4
  16. package/dist/chunk-YA7BMX7D.js.map +1 -0
  17. package/dist/completion/index.js +2 -2
  18. package/dist/documents/index.js +26 -1
  19. package/dist/documents/index.js.map +1 -1
  20. package/dist/evals/index.d.ts +5 -5
  21. package/dist/evals/index.js +6 -6
  22. package/dist/evals/index.js.map +1 -1
  23. package/dist/extractor/index.js +3 -3
  24. package/dist/index.d.ts +7 -12
  25. package/dist/index.js +22 -20
  26. package/dist/internal/agent.d.ts +4 -9
  27. package/dist/internal/agent.js +8 -8
  28. package/dist/mcp/index.d.ts +3 -17
  29. package/dist/mcp/index.js +1 -15
  30. package/dist/memory/index.d.ts +6 -3
  31. package/dist/memory/index.js +6 -4
  32. package/dist/observability/index.d.ts +2 -2
  33. package/dist/observability/index.js +3 -3
  34. package/dist/pipeline/index.d.ts +6 -11
  35. package/dist/pipeline/index.js +6 -6
  36. package/dist/pipeline/index.js.map +1 -1
  37. package/dist/{types-Sue2hb_L.d.ts → types-CLCLFpAL.d.ts} +23 -15
  38. package/dist/{types-DKOXVTcq.d.ts → types-CSYt7-It.d.ts} +18 -3
  39. package/dist/types-DjqRHeAi.d.ts +31 -0
  40. package/package.json +10 -4
  41. package/dist/chunk-76JLMBVT.js +0 -716
  42. package/dist/chunk-76JLMBVT.js.map +0 -1
  43. package/dist/chunk-PISJAAMX.js.map +0 -1
  44. package/dist/chunk-TC4FILD3.js.map +0 -1
  45. package/dist/chunk-X4LK4ODN.js.map +0 -1
  46. package/dist/client-DTPl0hZv.d.ts +0 -84
  47. /package/dist/{chunk-WZVHZZW6.js.map → chunk-6BBOCFHV.js.map} +0 -0
  48. /package/dist/{chunk-WTRGYFCD.js.map → chunk-7PHMK7W4.js.map} +0 -0
  49. /package/dist/{chunk-KIXN5DGS.js.map → chunk-LTXABCOO.js.map} +0 -0
  50. /package/dist/{chunk-QOUPWOGW.js.map → chunk-SPD4XVR7.js.map} +0 -0
@@ -1,6 +1,3 @@
1
- import {
2
- isSkillTool
3
- } from "./chunk-YK4WAAS4.js";
4
1
  import {
5
2
  assertAgentInteractionResponse,
6
3
  parseAgentContinuation,
@@ -9,7 +6,20 @@ import {
9
6
  } from "./chunk-OJBFDBLG.js";
10
7
  import {
11
8
  isMcpTool
12
- } from "./chunk-76JLMBVT.js";
9
+ } from "./chunk-J6LVLV6P.js";
10
+ import {
11
+ MemoryCompactionConflictError,
12
+ MemoryCompactionError,
13
+ createMemoryCompactionSummary,
14
+ cumulativeCompactedMessageCount,
15
+ resolveMemoryOptions
16
+ } from "./chunk-YA7BMX7D.js";
17
+ import {
18
+ startAgentRunObservers
19
+ } from "./chunk-6BBOCFHV.js";
20
+ import {
21
+ isSkillTool
22
+ } from "./chunk-YK4WAAS4.js";
13
23
  import {
14
24
  isQuestionTool,
15
25
  isToolIndex
@@ -29,16 +39,6 @@ import {
29
39
  toolMayRequireApproval,
30
40
  toolResultContentToText
31
41
  } from "./chunk-EMZKPRE6.js";
32
- import {
33
- MemoryCompactionConflictError,
34
- MemoryCompactionError,
35
- assertPositiveInteger,
36
- createMemoryCompactionSummary,
37
- cumulativeCompactedMessageCount
38
- } from "./chunk-TC4FILD3.js";
39
- import {
40
- startAgentRunObservers
41
- } from "./chunk-WZVHZZW6.js";
42
42
  import {
43
43
  AgentRunBlockedError,
44
44
  AgentRunCancelledError,
@@ -46,7 +46,7 @@ import {
46
46
  AgentStructuredOutputError,
47
47
  AgentToolSuspensionError,
48
48
  MaxTurnsError
49
- } from "./chunk-X4LK4ODN.js";
49
+ } from "./chunk-AHLKV6KP.js";
50
50
  import {
51
51
  mapWithConcurrency
52
52
  } from "./chunk-3RM57ZT2.js";
@@ -60,15 +60,15 @@ import {
60
60
  isProviderTool,
61
61
  isStreamingCompletionModel,
62
62
  textFromAssistantContent
63
- } from "./chunk-WTRGYFCD.js";
63
+ } from "./chunk-7PHMK7W4.js";
64
+ import {
65
+ assertJsonObject
66
+ } from "./chunk-7JLAIN6E.js";
64
67
  import {
65
68
  parseMessage,
66
69
  parseMessages,
67
70
  toProviderJsonSchema
68
71
  } from "./chunk-QGX73TSQ.js";
69
- import {
70
- assertJsonObject
71
- } from "./chunk-7JLAIN6E.js";
72
72
  import {
73
73
  isJsonValue
74
74
  } from "./chunk-3XQGVDU5.js";
@@ -545,7 +545,7 @@ var AgentRunMemory = class {
545
545
  pendingTurnMessages(newMessages) {
546
546
  return this.memoryPolicy() === "turn" ? [...newMessages] : [];
547
547
  }
548
- async prepareHistory(runId, incomingMessageCount, abortSignal) {
548
+ async prepareHistory(runId, incomingMessages, abortSignal) {
549
549
  const memory = this.memory();
550
550
  if (memory === void 0 || this.memoryScope === void 0) {
551
551
  return {
@@ -556,7 +556,7 @@ var AgentRunMemory = class {
556
556
  const preparation = await this.prepareStoredHistory(
557
557
  memory,
558
558
  runId,
559
- incomingMessageCount,
559
+ incomingMessages,
560
560
  abortSignal
561
561
  );
562
562
  const memoryHistory = preparation.history;
@@ -566,6 +566,26 @@ var AgentRunMemory = class {
566
566
  history: chatHistory
567
567
  };
568
568
  }
569
+ async compact(runId, abortSignal) {
570
+ const memory = this.memory();
571
+ const scope = this.memoryScope;
572
+ if (memory === void 0 || scope === void 0) {
573
+ throw new TypeError("Manual memory compaction requires an Agent with configured memory.");
574
+ }
575
+ if (memory.compaction === void 0 || memory.store.compaction === void 0) {
576
+ throw new TypeError("Manual memory compaction requires a configured compaction policy.");
577
+ }
578
+ const preparation = await this.prepareStoredHistory(memory, runId, [], abortSignal, true);
579
+ if (preparation.compaction !== void 0) {
580
+ return { type: "compacted", ...preparation.compaction };
581
+ }
582
+ return {
583
+ type: "skipped",
584
+ reason: "nothing_to_compact",
585
+ originalMessageCount: preparation.history.length,
586
+ originalTokenCount: preparation.originalTokenCount ?? await countTokens(memory.compaction.tokenCounter, preparation.history)
587
+ };
588
+ }
569
589
  async commitAcceptedInput(runId, messages) {
570
590
  const memory = this.memory();
571
591
  if (memory === void 0 || this.memoryScope === void 0 || memory.savePolicy !== "message" || messages.length === 0) {
@@ -635,7 +655,7 @@ var AgentRunMemory = class {
635
655
  memory() {
636
656
  return this.memoryScope === void 0 ? void 0 : this.agent.memory;
637
657
  }
638
- async prepareStoredHistory(memory, runId, incomingMessageCount, abortSignal) {
658
+ async prepareStoredHistory(memory, runId, incomingMessages, abortSignal, force = false) {
639
659
  const scope = this.memoryScope;
640
660
  if (scope === void 0) {
641
661
  return { history: [], usage: Usage.empty() };
@@ -654,14 +674,22 @@ var AgentRunMemory = class {
654
674
  throwIfAborted(abortSignal);
655
675
  const snapshot = await capability.snapshot({ scope });
656
676
  throwIfAborted(abortSignal);
657
- const compactedMessageCount = compactedPrefixLength(
677
+ const selection = await selectCompactionPrefix(
658
678
  snapshot.messages,
659
- incomingMessageCount,
660
- options.trigger.afterMessages,
661
- options.retention.recentUserTurns
679
+ incomingMessages,
680
+ options.trigger.afterTokens,
681
+ options.retention.recentTokens,
682
+ options.tokenCounter,
683
+ force
662
684
  );
685
+ throwIfAborted(abortSignal);
686
+ const compactedMessageCount = selection.compactedMessageCount;
663
687
  if (compactedMessageCount === 0) {
664
- return { history: snapshot.messages, usage };
688
+ return {
689
+ history: snapshot.messages,
690
+ usage,
691
+ originalTokenCount: selection.originalTokenCount
692
+ };
665
693
  }
666
694
  const prefix = snapshot.messages.slice(0, compactedMessageCount);
667
695
  let result;
@@ -677,6 +705,11 @@ var AgentRunMemory = class {
677
705
  if (result.usage !== void 0) {
678
706
  usage = Usage.add(usage, result.usage);
679
707
  }
708
+ if (typeof result?.summary !== "string") {
709
+ throw new MemoryCompactionError("Memory compactor must return a summary string.", {
710
+ usage
711
+ });
712
+ }
680
713
  const summaryText = result.summary.trim();
681
714
  if (summaryText.length === 0) {
682
715
  throw new MemoryCompactionError("Memory compactor returned an empty summary.", {
@@ -687,6 +720,13 @@ var AgentRunMemory = class {
687
720
  summaryText,
688
721
  cumulativeCompactedMessageCount(prefix)
689
722
  );
723
+ const retained = snapshot.messages.slice(compactedMessageCount);
724
+ let resultTokenCount;
725
+ try {
726
+ resultTokenCount = await countTokens(options.tokenCounter, [summary, ...retained]);
727
+ } catch (error) {
728
+ throw remappedCompactorError(error, usage);
729
+ }
690
730
  throwIfAborted(abortSignal);
691
731
  let replacement;
692
732
  try {
@@ -704,7 +744,6 @@ var AgentRunMemory = class {
704
744
  });
705
745
  }
706
746
  if (replacement.status === "committed") {
707
- const retained = snapshot.messages.slice(compactedMessageCount);
708
747
  return {
709
748
  history: [summary, ...retained],
710
749
  usage,
@@ -712,6 +751,10 @@ var AgentRunMemory = class {
712
751
  originalMessageCount: snapshot.messages.length,
713
752
  compactedMessageCount,
714
753
  retainedMessageCount: retained.length,
754
+ originalTokenCount: selection.originalTokenCount,
755
+ compactedTokenCount: selection.compactedTokenCount,
756
+ retainedTokenCount: selection.retainedTokenCount,
757
+ resultTokenCount,
715
758
  attempts: attempt,
716
759
  usage
717
760
  }
@@ -722,17 +765,72 @@ var AgentRunMemory = class {
722
765
  throw new MemoryCompactionConflictError(maxAttempts, usage);
723
766
  }
724
767
  };
725
- function compactedPrefixLength(messages, incomingMessageCount, afterMessages, recentUserTurns) {
726
- if (messages.length + incomingMessageCount <= afterMessages) {
727
- return 0;
768
+ async function selectCompactionPrefix(messages, incomingMessages, afterTokens, recentTokens, tokenCounter, force) {
769
+ const originalTokenCount = await countTokens(tokenCounter, messages);
770
+ const incomingTokenCount = incomingMessages.length === 0 ? 0 : await countTokens(tokenCounter, incomingMessages);
771
+ const none = {
772
+ compactedMessageCount: 0,
773
+ originalTokenCount,
774
+ compactedTokenCount: 0,
775
+ retainedTokenCount: originalTokenCount
776
+ };
777
+ if (!force && originalTokenCount + incomingTokenCount <= afterTokens) {
778
+ return none;
728
779
  }
729
780
  const userMessageIndexes = messages.flatMap(
730
781
  (message, index) => message.role === "user" ? [index] : []
731
782
  );
732
- if (userMessageIndexes.length <= recentUserTurns) {
733
- return 0;
783
+ if (userMessageIndexes.length <= 1) {
784
+ return none;
785
+ }
786
+ const tailTokenCounts = /* @__PURE__ */ new Map();
787
+ const countTail = async (messageIndex) => {
788
+ const cached = tailTokenCounts.get(messageIndex);
789
+ if (cached !== void 0) return cached;
790
+ const count = await countTokens(tokenCounter, messages.slice(messageIndex));
791
+ tailTokenCounts.set(messageIndex, count);
792
+ return count;
793
+ };
794
+ let lower = 0;
795
+ let upper = userMessageIndexes.length - 1;
796
+ let retainedBoundary = upper;
797
+ while (lower <= upper) {
798
+ const middle = Math.floor((lower + upper) / 2);
799
+ const candidate = userMessageIndexes[middle] ?? 0;
800
+ if (await countTail(candidate) <= recentTokens) {
801
+ retainedBoundary = middle;
802
+ upper = middle - 1;
803
+ } else {
804
+ lower = middle + 1;
805
+ }
806
+ }
807
+ const compactedMessageCount = userMessageIndexes[retainedBoundary] ?? 0;
808
+ if (compactedMessageCount === 0) {
809
+ return none;
734
810
  }
735
- return userMessageIndexes[userMessageIndexes.length - recentUserTurns] ?? 0;
811
+ const compactedTokenCount = await countTokens(
812
+ tokenCounter,
813
+ messages.slice(0, compactedMessageCount)
814
+ );
815
+ const retainedTokenCount = tailTokenCounts.get(compactedMessageCount) ?? await countTokens(tokenCounter, messages.slice(compactedMessageCount));
816
+ return {
817
+ compactedMessageCount,
818
+ originalTokenCount,
819
+ compactedTokenCount,
820
+ retainedTokenCount
821
+ };
822
+ }
823
+ async function countTokens(tokenCounter, messages) {
824
+ let count;
825
+ try {
826
+ count = await tokenCounter(messages);
827
+ } catch (error) {
828
+ throw new MemoryCompactionError("Memory token counter failed.", { cause: error });
829
+ }
830
+ if (!Number.isSafeInteger(count) || count < 0) {
831
+ throw new MemoryCompactionError("Memory token counter must return a nonnegative safe integer.");
832
+ }
833
+ return count;
736
834
  }
737
835
  function remappedCompactorError(error, usage) {
738
836
  if (error instanceof MemoryCompactionError) {
@@ -754,6 +852,22 @@ function isEmptyUsage(usage) {
754
852
  return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
755
853
  }
756
854
 
855
+ // src/internal/agent-runtime/memory-scope.ts
856
+ function normalizeMemoryScope(scope, owner = "Agent") {
857
+ if (typeof scope !== "object" || scope === null || Array.isArray(scope)) {
858
+ throw new TypeError(`${owner} session must be an object.`);
859
+ }
860
+ if (typeof scope.sessionId !== "string" || scope.sessionId.trim().length === 0) {
861
+ throw new TypeError(`${owner} sessionId must be a non-empty string.`);
862
+ }
863
+ const normalized = {
864
+ sessionId: scope.sessionId.trim()
865
+ };
866
+ if (scope.userId !== void 0) normalized.userId = scope.userId;
867
+ if (scope.metadata !== void 0) normalized.metadata = scope.metadata;
868
+ return lifecycleSnapshot(normalized);
869
+ }
870
+
757
871
  // src/internal/agent-runtime/retrieval.ts
758
872
  async function fetchContextDocuments(agent, ragText, abortSignal) {
759
873
  const documents = [];
@@ -1915,11 +2029,12 @@ var AgentRun = class _AgentRun {
1915
2029
  }
1916
2030
  cancel(reason) {
1917
2031
  if (this.isTerminal() || this.cancellationError !== void 0) {
1918
- return;
2032
+ return this.cancellationError;
1919
2033
  }
1920
2034
  const messages = this.currentMessages.length === 0 ? [this.promptMessage] : [...this.currentMessages];
1921
2035
  const error = new AgentRunCancelledError([...this.chatHistory, ...messages], reason);
1922
2036
  this.setCancellationError(error);
2037
+ return error;
1923
2038
  }
1924
2039
  setCancellationError(error) {
1925
2040
  this.cancellationError = error;
@@ -1938,7 +2053,7 @@ var AgentRun = class _AgentRun {
1938
2053
  this.throwIfCancelled();
1939
2054
  const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
1940
2055
  runId,
1941
- newMessages.length,
2056
+ newMessages,
1942
2057
  this.abortController.signal
1943
2058
  ) : void 0;
1944
2059
  if (memoryPreparation !== void 0) {
@@ -1972,8 +2087,12 @@ var AgentRun = class _AgentRun {
1972
2087
  if (inputResult.blocked) {
1973
2088
  const text = inputResult.message ?? "The request was blocked by a guardrail.";
1974
2089
  const result = {
1975
- status: "blocked",
2090
+ type: "blocked",
1976
2091
  stage: "input",
2092
+ ...blockedOutcomeDetails(
2093
+ this.guardrailDecisions,
2094
+ "The request was blocked by a guardrail."
2095
+ ),
1977
2096
  runId,
1978
2097
  text,
1979
2098
  usage,
@@ -1985,7 +2104,7 @@ var AgentRun = class _AgentRun {
1985
2104
  if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
1986
2105
  this.runState = "closing";
1987
2106
  await this.runLifecycleFinish(result);
1988
- await runObservers.end(result);
2107
+ await runObservers.end(observerRunEnd(result));
1989
2108
  this.runState = "completed";
1990
2109
  this.disposeAbortLink();
1991
2110
  return result;
@@ -2135,7 +2254,7 @@ var AgentRun = class _AgentRun {
2135
2254
  newMessages,
2136
2255
  runObservers
2137
2256
  );
2138
- if (result.status === "completed") {
2257
+ if (result.type === "response") {
2139
2258
  await this.runRunEndHook(result, newMessages);
2140
2259
  }
2141
2260
  await this.memoryRecorder.commitCompletedRun(
@@ -2145,7 +2264,7 @@ var AgentRun = class _AgentRun {
2145
2264
  pendingTurnMessages
2146
2265
  );
2147
2266
  await this.runLifecycleFinish(result);
2148
- await runObservers.end(result);
2267
+ await runObservers.end(observerRunEnd(result));
2149
2268
  this.runState = "completed";
2150
2269
  this.disposeAbortLink();
2151
2270
  return result;
@@ -2230,7 +2349,7 @@ var AgentRun = class _AgentRun {
2230
2349
  this.throwIfCancelled();
2231
2350
  const memoryPreparation = this.continuationState === void 0 ? await this.memoryRecorder.prepareHistory(
2232
2351
  runId,
2233
- newMessages.length,
2352
+ newMessages,
2234
2353
  this.abortController.signal
2235
2354
  ) : void 0;
2236
2355
  if (memoryPreparation !== void 0) {
@@ -2268,8 +2387,12 @@ var AgentRun = class _AgentRun {
2268
2387
  if (inputResult.blocked) {
2269
2388
  const text = inputResult.message ?? "The request was blocked by a guardrail.";
2270
2389
  const result = {
2271
- status: "blocked",
2390
+ type: "blocked",
2272
2391
  stage: "input",
2392
+ ...blockedOutcomeDetails(
2393
+ this.guardrailDecisions,
2394
+ "The request was blocked by a guardrail."
2395
+ ),
2273
2396
  runId,
2274
2397
  text,
2275
2398
  usage,
@@ -2281,10 +2404,10 @@ var AgentRun = class _AgentRun {
2281
2404
  if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
2282
2405
  this.runState = "closing";
2283
2406
  await this.runLifecycleFinish(result);
2284
- await runObservers.end(result);
2407
+ await runObservers.end(observerRunEnd(result));
2285
2408
  this.runState = "completed";
2286
2409
  this.disposeAbortLink();
2287
- yield { type: "final", result };
2410
+ yield result;
2288
2411
  return;
2289
2412
  }
2290
2413
  }
@@ -2335,7 +2458,7 @@ var AgentRun = class _AgentRun {
2335
2458
  suspension: error,
2336
2459
  uncommittedMessages: []
2337
2460
  });
2338
- yield { type: "final", result };
2461
+ yield result;
2339
2462
  return;
2340
2463
  }
2341
2464
  throw error;
@@ -2540,7 +2663,7 @@ var AgentRun = class _AgentRun {
2540
2663
  suspension: error,
2541
2664
  uncommittedMessages: [assistantMessage]
2542
2665
  });
2543
- yield { type: "final", result };
2666
+ yield result;
2544
2667
  return;
2545
2668
  }
2546
2669
  throw error;
@@ -2831,7 +2954,7 @@ var AgentRun = class _AgentRun {
2831
2954
  args.newMessages,
2832
2955
  args.runObservers
2833
2956
  );
2834
- if (result.status === "completed") {
2957
+ if (result.type === "response") {
2835
2958
  await this.runRunEndHook(result, args.newMessages);
2836
2959
  }
2837
2960
  await this.memoryRecorder.commitCompletedRun(
@@ -2841,10 +2964,10 @@ var AgentRun = class _AgentRun {
2841
2964
  args.pendingTurnMessages
2842
2965
  );
2843
2966
  await this.runLifecycleFinish(result);
2844
- await args.runObservers.end(result);
2967
+ await args.runObservers.end(observerRunEnd(result));
2845
2968
  this.runState = "completed";
2846
2969
  this.disposeAbortLink();
2847
- yield { type: "final", result };
2970
+ yield result;
2848
2971
  }
2849
2972
  async finishSuspension(args) {
2850
2973
  const partialToolMessage = args.suspension.completedResults.length === 0 ? void 0 : { role: "tool", content: [...args.suspension.completedResults] };
@@ -2885,7 +3008,7 @@ var AgentRun = class _AgentRun {
2885
3008
  state: serializeContinuationState(continuationState)
2886
3009
  });
2887
3010
  const result = {
2888
- status: "suspended",
3011
+ type: "interaction",
2889
3012
  runId: args.runId,
2890
3013
  text: latestAssistantText([...this.chatHistory, ...args.newMessages]),
2891
3014
  usage: args.usage,
@@ -2899,7 +3022,7 @@ var AgentRun = class _AgentRun {
2899
3022
  };
2900
3023
  if (this.resumedFrom !== void 0) result.resumedFrom = this.resumedFrom;
2901
3024
  await this.runLifecycleFinish(result);
2902
- await args.runObservers.end(result);
3025
+ await args.runObservers.end(observerRunEnd(result));
2903
3026
  this.runState = "completed";
2904
3027
  this.currentMessages = [...args.newMessages];
2905
3028
  this.disposeAbortLink();
@@ -3113,11 +3236,11 @@ var AgentRun = class _AgentRun {
3113
3236
  if (result.memoryCompaction !== void 0) {
3114
3237
  Object.assign(common, { memoryCompaction: lifecycleSnapshot(result.memoryCompaction) });
3115
3238
  }
3116
- const event = result.status === "completed" ? {
3239
+ const event = result.type === "response" ? {
3117
3240
  ...common,
3118
3241
  status: "completed",
3119
3242
  output: lifecycleSnapshot(result.output)
3120
- } : result.status === "blocked" ? {
3243
+ } : result.type === "blocked" ? {
3121
3244
  ...common,
3122
3245
  status: "blocked",
3123
3246
  stage: result.stage
@@ -3203,11 +3326,19 @@ var AgentRun = class _AgentRun {
3203
3326
  };
3204
3327
  if (this.resumedFrom !== void 0) Object.assign(common, { resumedFrom: this.resumedFrom });
3205
3328
  if (blocked) {
3206
- return { ...common, status: "blocked", stage: "output" };
3329
+ return {
3330
+ ...common,
3331
+ type: "blocked",
3332
+ stage: "output",
3333
+ ...blockedOutcomeDetails(
3334
+ this.guardrailDecisions,
3335
+ "The response was blocked by a guardrail."
3336
+ )
3337
+ };
3207
3338
  }
3208
3339
  return {
3209
3340
  ...common,
3210
- status: "completed",
3341
+ type: "response",
3211
3342
  output: this.parseOutput(text)
3212
3343
  };
3213
3344
  }
@@ -3326,6 +3457,10 @@ var AgentRun = class _AgentRun {
3326
3457
  originalMessageCount: compaction.originalMessageCount,
3327
3458
  compactedMessageCount: compaction.compactedMessageCount,
3328
3459
  retainedMessageCount: compaction.retainedMessageCount,
3460
+ originalTokenCount: compaction.originalTokenCount,
3461
+ compactedTokenCount: compaction.compactedTokenCount,
3462
+ retainedTokenCount: compaction.retainedTokenCount,
3463
+ resultTokenCount: compaction.resultTokenCount,
3329
3464
  attempts: compaction.attempts,
3330
3465
  inputTokens: compaction.usage.inputTokens,
3331
3466
  outputTokens: compaction.usage.outputTokens,
@@ -3701,20 +3836,6 @@ function normalizeSteeringInput(input) {
3701
3836
  }
3702
3837
  return parsedMessages;
3703
3838
  }
3704
- function normalizeMemoryScope(scope) {
3705
- if (typeof scope !== "object" || scope === null) {
3706
- throw new TypeError("Agent session must be an object.");
3707
- }
3708
- if (typeof scope.sessionId !== "string" || scope.sessionId.trim().length === 0) {
3709
- throw new TypeError("Agent sessionId must be a non-empty string.");
3710
- }
3711
- const normalized = {
3712
- sessionId: scope.sessionId.trim()
3713
- };
3714
- if (scope.userId !== void 0) normalized.userId = scope.userId;
3715
- if (scope.metadata !== void 0) normalized.metadata = scope.metadata;
3716
- return lifecycleSnapshot(normalized);
3717
- }
3718
3839
  function normalizeRequestedRunId(runId) {
3719
3840
  if (runId === void 0) {
3720
3841
  return void 0;
@@ -3952,6 +4073,33 @@ function guardrailDecisionAttributes(decision) {
3952
4073
  }
3953
4074
  return attributes;
3954
4075
  }
4076
+ function blockedOutcomeDetails(decisions, fallbackReason) {
4077
+ for (let index = decisions.length - 1; index >= 0; index -= 1) {
4078
+ const decision = decisions[index];
4079
+ if (decision?.applied !== true || decision.action !== "block") continue;
4080
+ return decision.message === void 0 ? { reason: decision.reason ?? fallbackReason } : { reason: decision.reason ?? fallbackReason, message: decision.message };
4081
+ }
4082
+ return { reason: fallbackReason };
4083
+ }
4084
+ function observerRunEnd(outcome) {
4085
+ const common = {
4086
+ runId: outcome.runId,
4087
+ text: outcome.text,
4088
+ usage: outcome.usage,
4089
+ messages: outcome.messages,
4090
+ sources: outcome.sources,
4091
+ providerToolCalls: outcome.providerToolCalls,
4092
+ resumedFrom: outcome.resumedFrom
4093
+ };
4094
+ switch (outcome.type) {
4095
+ case "response":
4096
+ return { ...common, status: "completed", output: outcome.output };
4097
+ case "blocked":
4098
+ return { ...common, status: "blocked", stage: outcome.stage };
4099
+ case "interaction":
4100
+ return { ...common, status: "suspended", interaction: outcome.interaction };
4101
+ }
4102
+ }
3955
4103
 
3956
4104
  // src/agent/agent-stream.ts
3957
4105
  function createAgentStream(run) {
@@ -3960,13 +4108,49 @@ function createAgentStream(run) {
3960
4108
  var DefaultAgentStream = class {
3961
4109
  constructor(run) {
3962
4110
  this.run = run;
4111
+ let resolveResult;
4112
+ let rejectResult;
4113
+ this.resultPromise = new Promise((resolve, reject) => {
4114
+ resolveResult = resolve;
4115
+ rejectResult = reject;
4116
+ });
4117
+ this.resolveResult = resolveResult;
4118
+ this.rejectResult = rejectResult;
4119
+ this.textPromise = this.resultPromise.then((result) => result.text);
4120
+ void this.resultPromise.catch(() => void 0);
4121
+ void this.textPromise.catch(() => void 0);
3963
4122
  }
3964
4123
  run;
3965
4124
  consuming = false;
3966
4125
  completed = false;
4126
+ settled = false;
4127
+ drainScheduled = false;
4128
+ resultPromise;
4129
+ textPromise;
4130
+ resolveResult;
4131
+ rejectResult;
4132
+ get events() {
4133
+ return this;
4134
+ }
4135
+ get textStream() {
4136
+ return {
4137
+ [Symbol.asyncIterator]: () => this.consumeText()
4138
+ };
4139
+ }
4140
+ get text() {
4141
+ this.scheduleDrain();
4142
+ return this.textPromise;
4143
+ }
4144
+ get result() {
4145
+ this.scheduleDrain();
4146
+ return this.resultPromise;
4147
+ }
3967
4148
  steer(input) {
3968
4149
  return this.run.steer(input);
3969
4150
  }
4151
+ cancel(reason = "Agent stream cancelled.") {
4152
+ this.run.cancel(reason);
4153
+ }
3970
4154
  [Symbol.asyncIterator]() {
3971
4155
  return this.consume()[Symbol.asyncIterator]();
3972
4156
  }
@@ -3980,17 +4164,56 @@ var DefaultAgentStream = class {
3980
4164
  this.consuming = true;
3981
4165
  try {
3982
4166
  for await (const event of this.run.events()) {
4167
+ if (isAgentOutcome(event)) {
4168
+ this.settled = true;
4169
+ this.resolveResult(event);
4170
+ } else if (event.type === "error") {
4171
+ this.settled = true;
4172
+ this.rejectResult(event.error);
4173
+ }
3983
4174
  yield event;
3984
4175
  }
3985
4176
  } finally {
3986
4177
  if (!this.completed) {
3987
- this.run.cancel("Agent stream consumer closed the stream.");
4178
+ const cancellation = this.run.cancel("Agent stream consumer closed the stream.");
4179
+ if (!this.settled && cancellation !== void 0) {
4180
+ this.settled = true;
4181
+ this.rejectResult(cancellation);
4182
+ }
3988
4183
  }
3989
4184
  this.consuming = false;
3990
4185
  this.completed = true;
3991
4186
  }
3992
4187
  }
4188
+ async *consumeText() {
4189
+ for await (const event of this.consume()) {
4190
+ if (event.type === "text_delta") yield event.delta;
4191
+ }
4192
+ }
4193
+ scheduleDrain() {
4194
+ if (this.completed || this.consuming || this.drainScheduled) return;
4195
+ this.drainScheduled = true;
4196
+ queueMicrotask(() => {
4197
+ this.drainScheduled = false;
4198
+ if (this.completed || this.consuming) return;
4199
+ void this.drain();
4200
+ });
4201
+ }
4202
+ async drain() {
4203
+ try {
4204
+ for await (const _event of this.consume()) {
4205
+ }
4206
+ } catch (error) {
4207
+ if (!this.settled) {
4208
+ this.settled = true;
4209
+ this.rejectResult(error);
4210
+ }
4211
+ }
4212
+ }
3993
4213
  };
4214
+ function isAgentOutcome(event) {
4215
+ return event.type === "response" || event.type === "interaction" || event.type === "blocked";
4216
+ }
3994
4217
 
3995
4218
  // src/agent/agent-tool.ts
3996
4219
  import { z } from "zod";
@@ -4026,14 +4249,14 @@ function createAgentTool(agent, options) {
4026
4249
  if (event.type === "error") {
4027
4250
  throw event.error;
4028
4251
  }
4029
- if (event.type === "final") {
4030
- if (event.result.status === "suspended") {
4031
- throw new AgentToolSuspensionError(event.result);
4032
- }
4033
- if (event.result.status === "blocked") {
4034
- throw new AgentRunBlockedError(event.result);
4035
- }
4036
- output = event.result.output;
4252
+ if (event.type === "interaction") {
4253
+ throw new AgentToolSuspensionError(event);
4254
+ }
4255
+ if (event.type === "blocked") {
4256
+ throw new AgentRunBlockedError(event);
4257
+ }
4258
+ if (event.type === "response") {
4259
+ output = event.output;
4037
4260
  completed = true;
4038
4261
  }
4039
4262
  }
@@ -4047,10 +4270,10 @@ function createAgentTool(agent, options) {
4047
4270
  maxTurns: options.maxTurns,
4048
4271
  abortSignal: context.abortSignal
4049
4272
  });
4050
- if (response.status === "suspended") {
4273
+ if (response.type === "interaction") {
4051
4274
  throw new AgentToolSuspensionError(response);
4052
4275
  }
4053
- if (response.status === "blocked") {
4276
+ if (response.type === "blocked") {
4054
4277
  throw new AgentRunBlockedError(response);
4055
4278
  }
4056
4279
  return response.output;
@@ -4070,39 +4293,6 @@ function normalizeAgentId(id) {
4070
4293
  return normalized;
4071
4294
  }
4072
4295
 
4073
- // src/memory/options.ts
4074
- function resolveMemoryOptions(options = {}) {
4075
- const resolved = {
4076
- savePolicy: options.savePolicy ?? "message"
4077
- };
4078
- if (options.compaction !== void 0) {
4079
- assertPositiveInteger(
4080
- options.compaction.trigger.afterMessages,
4081
- "compaction.trigger.afterMessages"
4082
- );
4083
- const recentUserTurns = options.compaction.retention?.recentUserTurns ?? 4;
4084
- assertPositiveInteger(recentUserTurns, "compaction.retention.recentUserTurns");
4085
- if (typeof options.compaction.compactor !== "function") {
4086
- throw new TypeError("compaction.compactor must be a function.");
4087
- }
4088
- const conflictRetries = options.compaction.conflictRetries ?? false;
4089
- if (conflictRetries !== false) {
4090
- assertPositiveInteger(conflictRetries.maxAttempts, "compaction.conflictRetries.maxAttempts");
4091
- }
4092
- resolved.compaction = {
4093
- trigger: {
4094
- afterMessages: options.compaction.trigger.afterMessages
4095
- },
4096
- retention: {
4097
- recentUserTurns
4098
- },
4099
- compactor: options.compaction.compactor,
4100
- conflictRetries
4101
- };
4102
- }
4103
- return resolved;
4104
- }
4105
-
4106
4296
  // src/agent/resolve-options.ts
4107
4297
  var resolvedAgentOptions = /* @__PURE__ */ Symbol("resolvedAgentOptions");
4108
4298
  function resolveAgentOptions(options) {
@@ -4535,6 +4725,9 @@ var Agent = class {
4535
4725
  generate(options) {
4536
4726
  return AgentRun.fromAgent(this, options).generate();
4537
4727
  }
4728
+ resume(continuation, response, settings = {}) {
4729
+ return this.generate({ continuation, response, ...settings });
4730
+ }
4538
4731
  stream(options) {
4539
4732
  const run = AgentRun.fromAgent(this, options);
4540
4733
  if (!this.model.capabilities.streaming || !isStreamingCompletionModel(this.model)) {
@@ -4542,6 +4735,17 @@ var Agent = class {
4542
4735
  }
4543
4736
  return createAgentStream(run);
4544
4737
  }
4738
+ compactMemory(options) {
4739
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
4740
+ throw new TypeError("Manual memory compaction requires an options object.");
4741
+ }
4742
+ const scope = normalizeMemoryScope(options.session, "Manual memory compaction");
4743
+ const memory = new AgentRunMemory(this, scope, []);
4744
+ return memory.compact(
4745
+ `manual-memory-compaction:${globalThis.crypto.randomUUID()}`,
4746
+ options.abortSignal
4747
+ );
4748
+ }
4545
4749
  asTool(options) {
4546
4750
  return createAgentTool(this, options);
4547
4751
  }
@@ -4566,4 +4770,4 @@ export {
4566
4770
  markResolvedAgentOptions,
4567
4771
  Agent
4568
4772
  };
4569
- //# sourceMappingURL=chunk-PISJAAMX.js.map
4773
+ //# sourceMappingURL=chunk-3ZLM6OAZ.js.map