@livekit/agents 1.2.0 → 1.2.1

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 (101) hide show
  1. package/dist/_exceptions.cjs.map +1 -1
  2. package/dist/_exceptions.d.ts.map +1 -1
  3. package/dist/_exceptions.js.map +1 -1
  4. package/dist/beta/workflows/task_group.cjs +7 -4
  5. package/dist/beta/workflows/task_group.cjs.map +1 -1
  6. package/dist/beta/workflows/task_group.d.ts.map +1 -1
  7. package/dist/beta/workflows/task_group.js +7 -4
  8. package/dist/beta/workflows/task_group.js.map +1 -1
  9. package/dist/inference/interruption/http_transport.cjs.map +1 -1
  10. package/dist/inference/interruption/http_transport.d.cts +3 -1
  11. package/dist/inference/interruption/http_transport.d.ts +3 -1
  12. package/dist/inference/interruption/http_transport.d.ts.map +1 -1
  13. package/dist/inference/interruption/http_transport.js.map +1 -1
  14. package/dist/inference/interruption/ws_transport.cjs +37 -32
  15. package/dist/inference/interruption/ws_transport.cjs.map +1 -1
  16. package/dist/inference/interruption/ws_transport.d.ts.map +1 -1
  17. package/dist/inference/interruption/ws_transport.js +37 -32
  18. package/dist/inference/interruption/ws_transport.js.map +1 -1
  19. package/dist/inference/tts.cjs.map +1 -1
  20. package/dist/inference/tts.d.cts +42 -4
  21. package/dist/inference/tts.d.ts +42 -4
  22. package/dist/inference/tts.d.ts.map +1 -1
  23. package/dist/inference/tts.js.map +1 -1
  24. package/dist/inference/tts.test.cjs +72 -0
  25. package/dist/inference/tts.test.cjs.map +1 -1
  26. package/dist/inference/tts.test.js +72 -0
  27. package/dist/inference/tts.test.js.map +1 -1
  28. package/dist/llm/chat_context.cjs +102 -31
  29. package/dist/llm/chat_context.cjs.map +1 -1
  30. package/dist/llm/chat_context.d.ts.map +1 -1
  31. package/dist/llm/chat_context.js +102 -31
  32. package/dist/llm/chat_context.js.map +1 -1
  33. package/dist/llm/chat_context.test.cjs +123 -5
  34. package/dist/llm/chat_context.test.cjs.map +1 -1
  35. package/dist/llm/chat_context.test.js +123 -5
  36. package/dist/llm/chat_context.test.js.map +1 -1
  37. package/dist/llm/fallback_adapter.cjs +2 -0
  38. package/dist/llm/fallback_adapter.cjs.map +1 -1
  39. package/dist/llm/fallback_adapter.d.ts.map +1 -1
  40. package/dist/llm/fallback_adapter.js +2 -0
  41. package/dist/llm/fallback_adapter.js.map +1 -1
  42. package/dist/llm/index.cjs +2 -0
  43. package/dist/llm/index.cjs.map +1 -1
  44. package/dist/llm/index.d.cts +1 -1
  45. package/dist/llm/index.d.ts +1 -1
  46. package/dist/llm/index.d.ts.map +1 -1
  47. package/dist/llm/index.js +2 -0
  48. package/dist/llm/index.js.map +1 -1
  49. package/dist/llm/utils.cjs +89 -0
  50. package/dist/llm/utils.cjs.map +1 -1
  51. package/dist/llm/utils.d.cts +8 -0
  52. package/dist/llm/utils.d.ts +8 -0
  53. package/dist/llm/utils.d.ts.map +1 -1
  54. package/dist/llm/utils.js +88 -0
  55. package/dist/llm/utils.js.map +1 -1
  56. package/dist/llm/utils.test.cjs +90 -0
  57. package/dist/llm/utils.test.cjs.map +1 -1
  58. package/dist/llm/utils.test.js +98 -2
  59. package/dist/llm/utils.test.js.map +1 -1
  60. package/dist/stt/stt.cjs +8 -0
  61. package/dist/stt/stt.cjs.map +1 -1
  62. package/dist/stt/stt.d.cts +8 -0
  63. package/dist/stt/stt.d.ts +8 -0
  64. package/dist/stt/stt.d.ts.map +1 -1
  65. package/dist/stt/stt.js +8 -0
  66. package/dist/stt/stt.js.map +1 -1
  67. package/dist/tts/fallback_adapter.cjs +6 -0
  68. package/dist/tts/fallback_adapter.cjs.map +1 -1
  69. package/dist/tts/fallback_adapter.d.ts.map +1 -1
  70. package/dist/tts/fallback_adapter.js +6 -0
  71. package/dist/tts/fallback_adapter.js.map +1 -1
  72. package/dist/typed_promise.cjs +48 -0
  73. package/dist/typed_promise.cjs.map +1 -0
  74. package/dist/typed_promise.d.cts +24 -0
  75. package/dist/typed_promise.d.ts +24 -0
  76. package/dist/typed_promise.d.ts.map +1 -0
  77. package/dist/typed_promise.js +28 -0
  78. package/dist/typed_promise.js.map +1 -0
  79. package/dist/utils.cjs +2 -2
  80. package/dist/utils.cjs.map +1 -1
  81. package/dist/utils.js +2 -2
  82. package/dist/utils.js.map +1 -1
  83. package/dist/version.cjs +1 -1
  84. package/dist/version.js +1 -1
  85. package/package.json +4 -2
  86. package/src/_exceptions.ts +5 -0
  87. package/src/beta/workflows/task_group.ts +14 -5
  88. package/src/inference/interruption/http_transport.ts +2 -1
  89. package/src/inference/interruption/ws_transport.ts +44 -34
  90. package/src/inference/tts.test.ts +87 -0
  91. package/src/inference/tts.ts +46 -6
  92. package/src/llm/chat_context.test.ts +137 -5
  93. package/src/llm/chat_context.ts +119 -38
  94. package/src/llm/fallback_adapter.ts +5 -2
  95. package/src/llm/index.ts +2 -0
  96. package/src/llm/utils.test.ts +103 -2
  97. package/src/llm/utils.ts +128 -0
  98. package/src/stt/stt.ts +9 -1
  99. package/src/tts/fallback_adapter.ts +9 -2
  100. package/src/typed_promise.ts +67 -0
  101. package/src/utils.ts +2 -2
@@ -538,40 +538,74 @@ class ChatContext {
538
538
  async _summarize(llm, options = {}) {
539
539
  var _a, _b;
540
540
  const { keepLastTurns = 2 } = options;
541
- const toSummarize = [];
542
- for (const item of this._items) {
543
- if (item.type !== "message") continue;
544
- if (item.role !== "user" && item.role !== "assistant") continue;
545
- if (((_a = item.extra) == null ? void 0 : _a.is_summary) === true) continue;
546
- const text = (item.textContent ?? "").trim();
547
- if (text) {
548
- toSummarize.push(item);
541
+ const msgBudget = keepLastTurns * 2;
542
+ let splitIdx = this._items.length;
543
+ if (msgBudget > 0) {
544
+ let msgCount = 0;
545
+ let foundSplit = false;
546
+ for (let i = this._items.length - 1; i >= 0; i -= 1) {
547
+ const item = this._items[i];
548
+ if (item.type === "message" && (item.role === "user" || item.role === "assistant")) {
549
+ msgCount += 1;
550
+ if (msgCount >= msgBudget) {
551
+ splitIdx = i;
552
+ foundSplit = true;
553
+ break;
554
+ }
555
+ }
556
+ }
557
+ if (!foundSplit) {
558
+ return this;
549
559
  }
550
560
  }
551
- if (toSummarize.length === 0) {
561
+ if (splitIdx === 0) {
552
562
  return this;
553
563
  }
554
- const tailN = Math.max(0, Math.min(toSummarize.length, keepLastTurns * 2));
555
- let head;
556
- let tail;
557
- if (tailN === 0) {
558
- head = toSummarize;
559
- tail = [];
560
- } else {
561
- head = toSummarize.slice(0, -tailN);
562
- tail = toSummarize.slice(-tailN);
564
+ const headItems = this._items.slice(0, splitIdx);
565
+ const tailItems = this._items.slice(splitIdx);
566
+ const toSummarize = [];
567
+ for (const item of headItems) {
568
+ if (item.type === "message") {
569
+ if (item.role !== "user" && item.role !== "assistant") continue;
570
+ if (((_a = item.extra) == null ? void 0 : _a.is_summary) === true) continue;
571
+ const text = (item.textContent ?? "").trim();
572
+ if (text) {
573
+ toSummarize.push(item);
574
+ }
575
+ } else if (item.type === "function_call" || item.type === "function_call_output") {
576
+ toSummarize.push(item);
577
+ }
563
578
  }
564
- if (head.length === 0) {
579
+ if (toSummarize.length === 0) {
565
580
  return this;
566
581
  }
567
- const sourceText = head.map((m) => `${m.role}: ${(m.textContent ?? "").trim()}`).join("\n").trim();
582
+ const sourceText = toSummarize.map((item) => {
583
+ if (item.type === "message") {
584
+ return toXml(item.role, (item.textContent ?? "").trim());
585
+ }
586
+ return functionCallItemToMessage(item).textContent ?? "";
587
+ }).join("\n").trim();
568
588
  if (!sourceText) {
569
589
  return this;
570
590
  }
571
591
  const promptCtx = new ChatContext();
572
592
  promptCtx.addMessage({
573
593
  role: "system",
574
- content: "Compress older chat history into a short, faithful summary.\nFocus on user goals, constraints, decisions, key facts/preferences/entities, and pending tasks.\nExclude chit-chat and greetings. Be concise."
594
+ content: [
595
+ "Compress older conversation history into a short, faithful summary.",
596
+ "",
597
+ "The conversation is formatted as XML. Here is how to read it:",
598
+ "- <user>...</user> - something the user said.",
599
+ "- <assistant>...</assistant> - something the assistant said.",
600
+ '- <function_call name="..." call_id="...">...</function_call> - the assistant invoked an action.',
601
+ '- <function_call_output name="..." call_id="...">...</function_call_output> - the result of that action. May contain <error>...</error> if it failed.',
602
+ "",
603
+ "Guidelines:",
604
+ "- Distill the information learned from function call outputs into the summary. Do not mention that a tool or function was called; just preserve the knowledge gained.",
605
+ "- Focus on user goals, constraints, decisions, key facts, preferences, entities, and any pending or unresolved tasks.",
606
+ "- Omit greetings, filler, and chit-chat.",
607
+ "- Be concise."
608
+ ].join("\n")
575
609
  });
576
610
  promptCtx.addMessage({
577
611
  role: "user",
@@ -589,29 +623,25 @@ ${sourceText}`
589
623
  if (!summary) {
590
624
  return this;
591
625
  }
592
- const tailStartTs = tail.length > 0 ? tail[0].createdAt : Infinity;
593
626
  const preserved = [];
594
- for (const it of this._items) {
595
- if ((it.type === "function_call" || it.type === "function_call_output") && it.createdAt < tailStartTs) {
627
+ for (const it of headItems) {
628
+ if (it.type === "message" && (it.role === "user" || it.role === "assistant")) {
596
629
  continue;
597
630
  }
598
- if (it.type === "message" && (it.role === "user" || it.role === "assistant")) {
631
+ if (it.type === "function_call" || it.type === "function_call_output") {
599
632
  continue;
600
633
  }
601
634
  preserved.push(it);
602
635
  }
603
636
  this._items = preserved;
604
- const createdAtHint = tail.length > 0 ? tail[0].createdAt - 1e-3 : head[head.length - 1].createdAt + 1e-3;
637
+ const createdAtHint = tailItems.length > 0 ? tailItems[0].createdAt - 1e-6 : headItems[headItems.length - 1].createdAt + 1e-6;
605
638
  this.addMessage({
606
639
  role: "assistant",
607
- content: `[history summary]
608
- ${summary}`,
640
+ content: toXml("chat_history_summary", summary),
609
641
  createdAt: createdAtHint,
610
642
  extra: { is_summary: true }
611
643
  });
612
- for (const msg of tail) {
613
- this.insert(msg);
614
- }
644
+ this._items.push(...tailItems);
615
645
  return this;
616
646
  }
617
647
  /**
@@ -621,6 +651,47 @@ ${summary}`,
621
651
  return false;
622
652
  }
623
653
  }
654
+ function toAttrsStr(attrs) {
655
+ if (!attrs) {
656
+ return void 0;
657
+ }
658
+ return Object.entries(attrs).map(([key, value]) => `${key}="${String(value)}"`).join(" ");
659
+ }
660
+ function toXml(tagName, content, attrs) {
661
+ const attrsStr = toAttrsStr(attrs);
662
+ if (content) {
663
+ return [attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`, content, `</${tagName}>`].join(
664
+ "\n"
665
+ );
666
+ }
667
+ return attrsStr ? `<${tagName} ${attrsStr} />` : `<${tagName} />`;
668
+ }
669
+ function functionCallItemToMessage(item) {
670
+ if (item.type === "function_call") {
671
+ return new ChatMessage({
672
+ role: "user",
673
+ content: [
674
+ toXml("function_call", item.args, {
675
+ name: item.name,
676
+ call_id: item.callId
677
+ })
678
+ ],
679
+ createdAt: item.createdAt,
680
+ extra: { is_function_call: true }
681
+ });
682
+ }
683
+ return new ChatMessage({
684
+ role: "assistant",
685
+ content: [
686
+ toXml("function_call_output", item.isError ? toXml("error", item.output) : item.output, {
687
+ name: item.name,
688
+ call_id: item.callId
689
+ })
690
+ ],
691
+ createdAt: item.createdAt,
692
+ extra: { is_function_call_output: true }
693
+ });
694
+ }
624
695
  class ReadonlyChatContext extends ChatContext {
625
696
  static errorMsg = "Please use .copy() and agent.update_chat_ctx() to modify the chat context.";
626
697
  constructor(items) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/llm/chat_context.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame, VideoFrame } from '@livekit/rtc-node';\nimport { createImmutableArray, shortuuid } from '../utils.js';\nimport type { LLM } from './llm.js';\nimport { type ProviderFormat, toChatCtx } from './provider_format/index.js';\nimport type { JSONObject, JSONValue, ToolContext } from './tool_context.js';\n\nexport type ChatRole = 'developer' | 'system' | 'user' | 'assistant';\nexport interface ImageContent {\n id: string;\n\n type: 'image_content';\n\n /**\n * Either a string URL or a VideoFrame object.\n */\n image: string | VideoFrame;\n\n inferenceDetail: 'auto' | 'high' | 'low';\n\n inferenceWidth?: number;\n\n inferenceHeight?: number;\n\n mimeType?: string;\n\n _cache: Record<any, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\nexport interface AudioContent {\n type: 'audio_content';\n\n frame: AudioFrame[];\n\n transcript?: string;\n}\n\nexport type ChatContent = ImageContent | AudioContent | string;\n\nexport function createImageContent(params: {\n image: string | VideoFrame;\n id?: string;\n inferenceDetail?: 'auto' | 'high' | 'low';\n inferenceWidth?: number;\n inferenceHeight?: number;\n mimeType?: string;\n}): ImageContent {\n const {\n image,\n id = shortuuid('img_'),\n inferenceDetail = 'auto',\n inferenceWidth,\n inferenceHeight,\n mimeType,\n } = params;\n\n return {\n id,\n type: 'image_content',\n image,\n inferenceDetail,\n inferenceWidth,\n inferenceHeight,\n mimeType,\n _cache: {},\n };\n}\n\nexport function createAudioContent(params: {\n frame: AudioFrame[];\n transcript?: string;\n}): AudioContent {\n const { frame, transcript } = params;\n\n return {\n type: 'audio_content',\n frame,\n transcript,\n };\n}\n\nexport interface MetricsReport {\n startedSpeakingAt?: number;\n stoppedSpeakingAt?: number;\n transcriptionDelay?: number;\n endOfTurnDelay?: number;\n onUserTurnCompletedDelay?: number;\n llmNodeTtft?: number;\n ttsNodeTtfb?: number;\n e2eLatency?: number;\n}\n\nexport class ChatMessage {\n readonly id: string;\n\n readonly type = 'message' as const;\n\n readonly role: ChatRole;\n\n content: ChatContent[];\n\n interrupted: boolean;\n\n transcriptConfidence?: number;\n\n extra: Record<string, unknown>;\n\n metrics: MetricsReport;\n\n hash?: Uint8Array;\n\n createdAt: number;\n\n constructor(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }) {\n const {\n role,\n content,\n id = shortuuid('item_'),\n interrupted = false,\n createdAt = Date.now(),\n transcriptConfidence,\n metrics = {},\n extra = {},\n } = params;\n this.id = id;\n this.role = role;\n this.content = Array.isArray(content) ? content : [content];\n this.interrupted = interrupted;\n this.createdAt = createdAt;\n this.transcriptConfidence = transcriptConfidence;\n this.metrics = metrics;\n this.extra = extra;\n }\n\n static create(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }) {\n return new ChatMessage(params);\n }\n\n /**\n * Returns a single string with all text parts of the message joined by new\n * lines. If no string content is present, returns `null`.\n */\n get textContent(): string | undefined {\n const parts = this.content.filter((c): c is string => typeof c === 'string');\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n\n toJSONContent(): JSONValue[] {\n return this.content.map((c) => {\n if (typeof c === 'string') {\n return c as JSONValue;\n } else if (c.type === 'image_content') {\n return {\n id: c.id,\n type: c.type,\n image: c.image,\n inferenceDetail: c.inferenceDetail,\n inferenceWidth: c.inferenceWidth,\n inferenceHeight: c.inferenceHeight,\n mimeType: c.mimeType,\n } as JSONObject;\n } else {\n return {\n type: c.type,\n transcript: c.transcript,\n } as JSONObject;\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n role: this.role,\n content: this.toJSONContent(),\n interrupted: this.interrupted,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n if (this.transcriptConfidence !== undefined) {\n result.transcriptConfidence = this.transcriptConfidence;\n }\n if (Object.keys(this.metrics).length > 0) {\n result.metrics = { ...this.metrics };\n }\n if (Object.keys(this.extra).length > 0) {\n result.extra = this.extra as JSONValue;\n }\n\n return result;\n }\n}\n\nexport class FunctionCall {\n readonly id: string;\n\n readonly type = 'function_call' as const;\n\n callId: string;\n\n args: string;\n\n name: string;\n\n createdAt: number;\n\n extra: Record<string, unknown>;\n /**\n * Optional grouping identifier for parallel tool calls.\n */\n groupId?: string;\n\n /**\n * Opaque signature for Gemini thinking mode.\n * When using Gemini 3+ models with thinking enabled, this signature must be\n * preserved and returned with function responses to maintain thought context.\n */\n thoughtSignature?: string;\n\n constructor(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n const {\n callId,\n name,\n args,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n extra = {},\n groupId,\n thoughtSignature,\n } = params;\n this.id = id;\n this.callId = callId;\n this.args = args;\n this.name = name;\n this.createdAt = createdAt;\n this.extra = { ...extra };\n this.groupId = groupId;\n this.thoughtSignature =\n thoughtSignature ??\n (typeof this.extra.google === 'object' && this.extra.google !== null\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.extra.google as any).thoughtSignature ||\n (this.extra.google as any).thought_signature\n : undefined);\n }\n\n static create(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n return new FunctionCall(params);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n callId: this.callId,\n name: this.name,\n args: this.args,\n };\n\n if (Object.keys(this.extra).length > 0) {\n result.extra = this.extra as JSONValue;\n }\n\n if (this.groupId) {\n result.groupId = this.groupId;\n }\n\n if (this.thoughtSignature) {\n result.thoughtSignature = this.thoughtSignature;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCallOutput {\n readonly id: string;\n\n readonly type = 'function_call_output' as const;\n\n name = '';\n\n callId: string;\n\n output: string;\n\n isError: boolean;\n\n createdAt: number;\n\n constructor(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n const {\n callId,\n output,\n isError,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n name = '',\n } = params;\n this.id = id;\n this.callId = callId;\n this.output = output;\n this.isError = isError;\n this.name = name;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n return new FunctionCallOutput(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n name: this.name,\n callId: this.callId,\n output: this.output,\n isError: this.isError,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class AgentHandoffItem {\n readonly id: string;\n\n readonly type = 'agent_handoff' as const;\n\n oldAgentId: string | undefined;\n\n newAgentId: string;\n\n createdAt: number;\n\n constructor(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n const { oldAgentId, newAgentId, id = shortuuid('item_'), createdAt = Date.now() } = params;\n this.id = id;\n this.oldAgentId = oldAgentId;\n this.newAgentId = newAgentId;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n return new AgentHandoffItem(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n newAgentId: this.newAgentId,\n };\n\n if (this.oldAgentId !== undefined) {\n result.oldAgentId = this.oldAgentId;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\n// TODO(parity): Add AgentConfigUpdate type to ChatItem union\nexport type ChatItem = ChatMessage | FunctionCall | FunctionCallOutput | AgentHandoffItem;\n\nexport class ChatContext {\n protected _items: ChatItem[];\n\n constructor(items?: ChatItem[]) {\n this._items = items ? items : [];\n }\n\n static empty(): ChatContext {\n return new ChatContext([]);\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n this._items = items;\n }\n\n /**\n * Add a new message to the context and return it.\n */\n addMessage(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }): ChatMessage {\n const msg = new ChatMessage(params);\n if (params.createdAt !== undefined) {\n const idx = this.findInsertionIndex(params.createdAt);\n this._items.splice(idx, 0, msg);\n } else {\n this._items.push(msg);\n }\n return msg;\n }\n\n /**\n * Insert a single item or multiple items based on their `createdAt` field so\n * that the array keeps its chronological order.\n */\n insert(item: ChatItem | ChatItem[]): void {\n const arr = Array.isArray(item) ? item : [item];\n for (const it of arr) {\n const idx = this.findInsertionIndex(it.createdAt);\n this._items.splice(idx, 0, it);\n }\n }\n\n getById(itemId: string): ChatItem | undefined {\n return this._items.find((i) => i.id === itemId);\n }\n\n indexById(itemId: string): number | undefined {\n const idx = this._items.findIndex((i) => i.id === itemId);\n return idx !== -1 ? idx : undefined;\n }\n\n // TODO(parity): Add excludeConfigUpdate option when AgentConfigUpdate is ported\n copy(\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n excludeEmptyMessage?: boolean;\n excludeHandoff?: boolean;\n toolCtx?: ToolContext<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n } = {},\n ): ChatContext {\n const {\n excludeFunctionCall = false,\n excludeInstructions = false,\n excludeEmptyMessage = false,\n excludeHandoff = false,\n toolCtx,\n } = options;\n const items: ChatItem[] = [];\n\n const isToolCallOrOutput = (item: ChatItem): item is FunctionCall | FunctionCallOutput =>\n ['function_call', 'function_call_output'].includes(item.type);\n const isChatMessage = (item: ChatItem): item is ChatMessage => item.type === 'message';\n\n for (const item of this._items) {\n if (excludeFunctionCall && isToolCallOrOutput(item)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n isChatMessage(item) &&\n ['system', 'developer'].includes(item.role)\n ) {\n continue;\n }\n\n if (excludeEmptyMessage && isChatMessage(item) && item.content.length === 0) {\n continue;\n }\n\n if (excludeHandoff && item.type === 'agent_handoff') {\n continue;\n }\n\n if (toolCtx !== undefined && isToolCallOrOutput(item) && toolCtx[item.name] === undefined) {\n continue;\n }\n\n items.push(item);\n }\n\n return new ChatContext(items);\n }\n\n // TODO(parity): Add excludeConfigUpdate option when AgentConfigUpdate is ported\n merge(\n other: ChatContext,\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n } = {},\n ): ChatContext {\n const { excludeFunctionCall = false, excludeInstructions = false } = options;\n const existingIds = new Set(this._items.map((item) => item.id));\n\n for (const item of other.items) {\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n item.type === 'message' &&\n (item.role === 'system' || item.role === 'developer')\n ) {\n continue;\n }\n\n if (existingIds.has(item.id)) {\n continue;\n }\n\n const idx = this.findInsertionIndex(item.createdAt);\n this._items.splice(idx, 0, item);\n existingIds.add(item.id);\n }\n\n return this;\n }\n\n truncate(maxItems: number): ChatContext {\n if (maxItems <= 0) return this;\n\n const instructions = this._items.find((i) => i.type === 'message' && i.role === 'system') as\n | ChatMessage\n | undefined;\n\n let newItems = this._items.slice(-maxItems);\n\n // Ensure the first item is not a function-call artefact.\n while (\n newItems.length > 0 &&\n ['function_call', 'function_call_output'].includes(newItems[0]!.type)\n ) {\n newItems.shift();\n }\n\n if (instructions) {\n // At this point `instructions` is defined, so it is safe to pass to `includes`.\n if (!newItems.includes(instructions)) {\n newItems = [instructions, ...newItems];\n }\n }\n\n // replace the items in place to keep the reference\n this._items.splice(0, this._items.length, ...newItems);\n return this;\n }\n\n toJSON(\n options: {\n excludeImage?: boolean;\n excludeAudio?: boolean;\n excludeTimestamp?: boolean;\n excludeFunctionCall?: boolean;\n } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): JSONObject {\n const {\n excludeImage = true,\n excludeAudio = true,\n excludeTimestamp = true,\n excludeFunctionCall = false,\n } = options;\n\n const items: ChatItem[] = [];\n\n for (const item of this._items) {\n let processedItem = item;\n\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (item.type === 'message') {\n processedItem = ChatMessage.create({\n role: item.role,\n content: item.content,\n id: item.id,\n interrupted: item.interrupted,\n createdAt: item.createdAt,\n transcriptConfidence: item.transcriptConfidence,\n metrics: item.metrics,\n extra: item.extra,\n });\n\n // Filter content based on options\n if (excludeImage) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'image_content');\n });\n }\n\n if (excludeAudio) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'audio_content');\n });\n }\n }\n\n items.push(processedItem);\n }\n\n return {\n items: items.map((item) => item.toJSON(excludeTimestamp)),\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async toProviderFormat(format: ProviderFormat, injectDummyUserMessage: boolean = true) {\n return await toChatCtx(format, this, injectDummyUserMessage);\n }\n\n /**\n * Internal helper used by `truncate` & `addMessage` to find the correct\n * insertion index for a timestamp so the list remains sorted.\n */\n private findInsertionIndex(createdAt: number): number {\n for (let i = this._items.length - 1; i >= 0; i -= 1) {\n const item = this._items[i];\n if (item!.createdAt <= createdAt) {\n return i + 1;\n }\n }\n return 0;\n }\n\n /**\n * Return true if `other` has the same sequence of items with matching\n * essential fields (IDs, types, and payload) as this context.\n *\n * Comparison rules:\n * - Messages: compares the full `content` list, `role` and `interrupted`.\n * - Function calls: compares `name`, `callId`, and `args`.\n * - Function call outputs: compares `name`, `callId`, `output`, and `isError`.\n *\n * Does not consider timestamps or other metadata.\n */\n isEquivalent(other: ChatContext): boolean {\n if (this === other) {\n return true;\n }\n\n if (this.items.length !== other.items.length) {\n return false;\n }\n\n for (let i = 0; i < this.items.length; i++) {\n const a = this.items[i]!;\n const b = other.items[i]!;\n\n if (a.id !== b.id || a.type !== b.type) {\n return false;\n }\n\n if (a.type === 'message' && b.type === 'message') {\n if (\n a.role !== b.role ||\n a.interrupted !== b.interrupted ||\n !this.compareContent(a.content, b.content)\n ) {\n return false;\n }\n } else if (a.type === 'function_call' && b.type === 'function_call') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.args !== b.args ||\n a.thoughtSignature !== b.thoughtSignature ||\n a.groupId !== b.groupId ||\n JSON.stringify(a.extra) !== JSON.stringify(b.extra)\n ) {\n return false;\n }\n } else if (a.type === 'function_call_output' && b.type === 'function_call_output') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.output !== b.output ||\n a.isError !== b.isError\n ) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Compare two content arrays for equality.\n */\n private compareContent(a: ChatContent[], b: ChatContent[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0; i < a.length; i++) {\n const contentA = a[i]!;\n const contentB = b[i]!;\n\n if (typeof contentA === 'string' && typeof contentB === 'string') {\n if (contentA !== contentB) {\n return false;\n }\n continue;\n }\n\n if (typeof contentA !== typeof contentB) {\n return false;\n }\n\n if (typeof contentA === 'object' && typeof contentB === 'object') {\n if (contentA.type === 'image_content' && contentB.type === 'image_content') {\n if (\n contentA.id !== contentB.id ||\n contentA.image !== contentB.image ||\n contentA.inferenceDetail !== contentB.inferenceDetail ||\n contentA.inferenceWidth !== contentB.inferenceWidth ||\n contentA.inferenceHeight !== contentB.inferenceHeight ||\n contentA.mimeType !== contentB.mimeType\n ) {\n return false;\n }\n } else if (contentA.type === 'audio_content' && contentB.type === 'audio_content') {\n if (contentA.frame.length !== contentB.frame.length) {\n return false;\n }\n if (contentA.transcript !== contentB.transcript) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n\n async _summarize(llm: LLM, options: { keepLastTurns?: number } = {}): Promise<ChatContext> {\n const { keepLastTurns = 2 } = options;\n\n const toSummarize: ChatMessage[] = [];\n for (const item of this._items) {\n if (item.type !== 'message') continue;\n if (item.role !== 'user' && item.role !== 'assistant') continue;\n if (item.extra?.is_summary === true) continue;\n\n const text = (item.textContent ?? '').trim();\n if (text) {\n toSummarize.push(item);\n }\n }\n\n if (toSummarize.length === 0) {\n return this;\n }\n\n const tailN = Math.max(0, Math.min(toSummarize.length, keepLastTurns * 2));\n let head: ChatMessage[];\n let tail: ChatMessage[];\n if (tailN === 0) {\n head = toSummarize;\n tail = [];\n } else {\n head = toSummarize.slice(0, -tailN);\n tail = toSummarize.slice(-tailN);\n }\n\n if (head.length === 0) {\n return this;\n }\n\n const sourceText = head\n .map((m) => `${m.role}: ${(m.textContent ?? '').trim()}`)\n .join('\\n')\n .trim();\n\n if (!sourceText) {\n return this;\n }\n\n // TODO: refactor this into LLMStream.collect API.\n const promptCtx = new ChatContext();\n promptCtx.addMessage({\n role: 'system',\n content:\n 'Compress older chat history into a short, faithful summary.\\n' +\n 'Focus on user goals, constraints, decisions, key facts/preferences/entities, and pending tasks.\\n' +\n 'Exclude chit-chat and greetings. Be concise.',\n });\n promptCtx.addMessage({\n role: 'user',\n content: `Conversation to summarize:\\n\\n${sourceText}`,\n });\n\n const chunks: string[] = [];\n for await (const chunk of llm.chat({ chatCtx: promptCtx })) {\n if (chunk.delta?.content) {\n chunks.push(chunk.delta.content);\n }\n }\n\n const summary = chunks.join('').trim();\n if (!summary) {\n return this;\n }\n\n const tailStartTs = tail.length > 0 ? tail[0]!.createdAt : Infinity;\n\n const preserved: ChatItem[] = [];\n for (const it of this._items) {\n if (\n (it.type === 'function_call' || it.type === 'function_call_output') &&\n it.createdAt < tailStartTs\n ) {\n continue;\n }\n\n if (it.type === 'message' && (it.role === 'user' || it.role === 'assistant')) {\n continue;\n }\n\n preserved.push(it);\n }\n\n this._items = preserved;\n\n const createdAtHint =\n tail.length > 0 ? tail[0]!.createdAt - 1e-3 : head[head.length - 1]!.createdAt + 1e-3;\n\n this.addMessage({\n role: 'assistant',\n content: `[history summary]\\n${summary}`,\n createdAt: createdAtHint,\n extra: { is_summary: true },\n });\n\n for (const msg of tail) {\n this.insert(msg);\n }\n\n return this;\n }\n\n /**\n * Indicates whether the context is read-only\n */\n get readonly(): boolean {\n return false;\n }\n}\n\nexport class ReadonlyChatContext extends ChatContext {\n static readonly errorMsg =\n 'Please use .copy() and agent.update_chat_ctx() to modify the chat context.';\n\n constructor(items: ChatItem[]) {\n super(createImmutableArray(items, ReadonlyChatContext.errorMsg));\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n throw new Error(\n `Cannot set items on a read-only chat context. ${ReadonlyChatContext.errorMsg}`,\n );\n }\n\n get readonly(): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAgD;AAEhD,6BAA+C;AAmCxC,SAAS,mBAAmB,QAOlB;AACf,QAAM;AAAA,IACJ;AAAA,IACA,SAAK,wBAAU,MAAM;AAAA,IACrB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,CAAC;AAAA,EACX;AACF;AAEO,SAAS,mBAAmB,QAGlB;AACf,QAAM,EAAE,OAAO,WAAW,IAAI;AAE9B,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AACF;AAaO,MAAM,YAAY;AAAA,EACd;AAAA,EAEA,OAAO;AAAA,EAEP;AAAA,EAET;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,YAAY,QAST;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,SAAK,wBAAU,OAAO;AAAA,MACtB,cAAc;AAAA,MACd,YAAY,KAAK,IAAI;AAAA,MACrB;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AAU,GAAG,SAAS,cAAc;AAC5E;AAAA,MACF;AAEA,gBAAU,KAAK,EAAE;AAAA,IACnB;AAEA,SAAK,SAAS;AAEd,UAAM,gBACJ,KAAK,SAAS,IAAI,KAAK,CAAC,EAAG,YAAY,OAAO,KAAK,KAAK,SAAS,CAAC,EAAG,YAAY;AAEnF,SAAK,WAAW;AAAA,MACd,MAAM;AAAA,MACN,SAAS;AAAA,EAAsB,OAAO;AAAA,MACtC,WAAW;AAAA,MACX,OAAO,EAAE,YAAY,KAAK;AAAA,IAC5B,CAAC;AAED,eAAW,OAAO,MAAM;AACtB,WAAK,OAAO,GAAG;AAAA,IACjB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,WAAoB;AACtB,WAAO;AAAA,EACT;AACF;AAEO,MAAM,4BAA4B,YAAY;AAAA,EACnD,OAAgB,WACd;AAAA,EAEF,YAAY,OAAmB;AAC7B,cAAM,mCAAqB,OAAO,oBAAoB,QAAQ,CAAC;AAAA,EACjE;AAAA,EAEA,IAAI,QAAoB;AACtB,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,MAAM,OAAmB;AAC3B,UAAM,IAAI;AAAA,MACR,iDAAiD,oBAAoB,QAAQ;AAAA,IAC/E;AAAA,EACF;AAAA,EAEA,IAAI,WAAoB;AACtB,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/llm/chat_context.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame, VideoFrame } from '@livekit/rtc-node';\nimport { createImmutableArray, shortuuid } from '../utils.js';\nimport type { LLM } from './llm.js';\nimport { type ProviderFormat, toChatCtx } from './provider_format/index.js';\nimport type { JSONObject, JSONValue, ToolContext } from './tool_context.js';\n\nexport type ChatRole = 'developer' | 'system' | 'user' | 'assistant';\nexport interface ImageContent {\n id: string;\n\n type: 'image_content';\n\n /**\n * Either a string URL or a VideoFrame object.\n */\n image: string | VideoFrame;\n\n inferenceDetail: 'auto' | 'high' | 'low';\n\n inferenceWidth?: number;\n\n inferenceHeight?: number;\n\n mimeType?: string;\n\n _cache: Record<any, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\nexport interface AudioContent {\n type: 'audio_content';\n\n frame: AudioFrame[];\n\n transcript?: string;\n}\n\nexport type ChatContent = ImageContent | AudioContent | string;\n\nexport function createImageContent(params: {\n image: string | VideoFrame;\n id?: string;\n inferenceDetail?: 'auto' | 'high' | 'low';\n inferenceWidth?: number;\n inferenceHeight?: number;\n mimeType?: string;\n}): ImageContent {\n const {\n image,\n id = shortuuid('img_'),\n inferenceDetail = 'auto',\n inferenceWidth,\n inferenceHeight,\n mimeType,\n } = params;\n\n return {\n id,\n type: 'image_content',\n image,\n inferenceDetail,\n inferenceWidth,\n inferenceHeight,\n mimeType,\n _cache: {},\n };\n}\n\nexport function createAudioContent(params: {\n frame: AudioFrame[];\n transcript?: string;\n}): AudioContent {\n const { frame, transcript } = params;\n\n return {\n type: 'audio_content',\n frame,\n transcript,\n };\n}\n\nexport interface MetricsReport {\n startedSpeakingAt?: number;\n stoppedSpeakingAt?: number;\n transcriptionDelay?: number;\n endOfTurnDelay?: number;\n onUserTurnCompletedDelay?: number;\n llmNodeTtft?: number;\n ttsNodeTtfb?: number;\n e2eLatency?: number;\n}\n\nexport class ChatMessage {\n readonly id: string;\n\n readonly type = 'message' as const;\n\n readonly role: ChatRole;\n\n content: ChatContent[];\n\n interrupted: boolean;\n\n transcriptConfidence?: number;\n\n extra: Record<string, unknown>;\n\n metrics: MetricsReport;\n\n hash?: Uint8Array;\n\n createdAt: number;\n\n constructor(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }) {\n const {\n role,\n content,\n id = shortuuid('item_'),\n interrupted = false,\n createdAt = Date.now(),\n transcriptConfidence,\n metrics = {},\n extra = {},\n } = params;\n this.id = id;\n this.role = role;\n this.content = Array.isArray(content) ? content : [content];\n this.interrupted = interrupted;\n this.createdAt = createdAt;\n this.transcriptConfidence = transcriptConfidence;\n this.metrics = metrics;\n this.extra = extra;\n }\n\n static create(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }) {\n return new ChatMessage(params);\n }\n\n /**\n * Returns a single string with all text parts of the message joined by new\n * lines. If no string content is present, returns `null`.\n */\n get textContent(): string | undefined {\n const parts = this.content.filter((c): c is string => typeof c === 'string');\n return parts.length > 0 ? parts.join('\\n') : undefined;\n }\n\n toJSONContent(): JSONValue[] {\n return this.content.map((c) => {\n if (typeof c === 'string') {\n return c as JSONValue;\n } else if (c.type === 'image_content') {\n return {\n id: c.id,\n type: c.type,\n image: c.image,\n inferenceDetail: c.inferenceDetail,\n inferenceWidth: c.inferenceWidth,\n inferenceHeight: c.inferenceHeight,\n mimeType: c.mimeType,\n } as JSONObject;\n } else {\n return {\n type: c.type,\n transcript: c.transcript,\n } as JSONObject;\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n role: this.role,\n content: this.toJSONContent(),\n interrupted: this.interrupted,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n if (this.transcriptConfidence !== undefined) {\n result.transcriptConfidence = this.transcriptConfidence;\n }\n if (Object.keys(this.metrics).length > 0) {\n result.metrics = { ...this.metrics };\n }\n if (Object.keys(this.extra).length > 0) {\n result.extra = this.extra as JSONValue;\n }\n\n return result;\n }\n}\n\nexport class FunctionCall {\n readonly id: string;\n\n readonly type = 'function_call' as const;\n\n callId: string;\n\n args: string;\n\n name: string;\n\n createdAt: number;\n\n extra: Record<string, unknown>;\n /**\n * Optional grouping identifier for parallel tool calls.\n */\n groupId?: string;\n\n /**\n * Opaque signature for Gemini thinking mode.\n * When using Gemini 3+ models with thinking enabled, this signature must be\n * preserved and returned with function responses to maintain thought context.\n */\n thoughtSignature?: string;\n\n constructor(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n const {\n callId,\n name,\n args,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n extra = {},\n groupId,\n thoughtSignature,\n } = params;\n this.id = id;\n this.callId = callId;\n this.args = args;\n this.name = name;\n this.createdAt = createdAt;\n this.extra = { ...extra };\n this.groupId = groupId;\n this.thoughtSignature =\n thoughtSignature ??\n (typeof this.extra.google === 'object' && this.extra.google !== null\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.extra.google as any).thoughtSignature ||\n (this.extra.google as any).thought_signature\n : undefined);\n }\n\n static create(params: {\n callId: string;\n name: string;\n args: string;\n id?: string;\n createdAt?: number;\n extra?: Record<string, unknown>;\n groupId?: string;\n thoughtSignature?: string;\n }) {\n return new FunctionCall(params);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n callId: this.callId,\n name: this.name,\n args: this.args,\n };\n\n if (Object.keys(this.extra).length > 0) {\n result.extra = this.extra as JSONValue;\n }\n\n if (this.groupId) {\n result.groupId = this.groupId;\n }\n\n if (this.thoughtSignature) {\n result.thoughtSignature = this.thoughtSignature;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class FunctionCallOutput {\n readonly id: string;\n\n readonly type = 'function_call_output' as const;\n\n name = '';\n\n callId: string;\n\n output: string;\n\n isError: boolean;\n\n createdAt: number;\n\n constructor(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n const {\n callId,\n output,\n isError,\n id = shortuuid('item_'),\n createdAt = Date.now(),\n name = '',\n } = params;\n this.id = id;\n this.callId = callId;\n this.output = output;\n this.isError = isError;\n this.name = name;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n callId: string;\n output: string;\n isError: boolean;\n id?: string;\n createdAt?: number;\n name?: string;\n }) {\n return new FunctionCallOutput(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n name: this.name,\n callId: this.callId,\n output: this.output,\n isError: this.isError,\n };\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\nexport class AgentHandoffItem {\n readonly id: string;\n\n readonly type = 'agent_handoff' as const;\n\n oldAgentId: string | undefined;\n\n newAgentId: string;\n\n createdAt: number;\n\n constructor(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n const { oldAgentId, newAgentId, id = shortuuid('item_'), createdAt = Date.now() } = params;\n this.id = id;\n this.oldAgentId = oldAgentId;\n this.newAgentId = newAgentId;\n this.createdAt = createdAt;\n }\n\n static create(params: {\n oldAgentId?: string;\n newAgentId: string;\n id?: string;\n createdAt?: number;\n }) {\n return new AgentHandoffItem(params);\n }\n\n toJSON(excludeTimestamp: boolean = false): JSONValue {\n const result: JSONValue = {\n id: this.id,\n type: this.type,\n newAgentId: this.newAgentId,\n };\n\n if (this.oldAgentId !== undefined) {\n result.oldAgentId = this.oldAgentId;\n }\n\n if (!excludeTimestamp) {\n result.createdAt = this.createdAt;\n }\n\n return result;\n }\n}\n\n// TODO(parity): Add AgentConfigUpdate type to ChatItem union\nexport type ChatItem = ChatMessage | FunctionCall | FunctionCallOutput | AgentHandoffItem;\n\nexport class ChatContext {\n protected _items: ChatItem[];\n\n constructor(items?: ChatItem[]) {\n this._items = items ? items : [];\n }\n\n static empty(): ChatContext {\n return new ChatContext([]);\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n this._items = items;\n }\n\n /**\n * Add a new message to the context and return it.\n */\n addMessage(params: {\n role: ChatRole;\n content: ChatContent[] | string;\n id?: string;\n interrupted?: boolean;\n createdAt?: number;\n transcriptConfidence?: number;\n metrics?: MetricsReport;\n extra?: Record<string, unknown>;\n }): ChatMessage {\n const msg = new ChatMessage(params);\n if (params.createdAt !== undefined) {\n const idx = this.findInsertionIndex(params.createdAt);\n this._items.splice(idx, 0, msg);\n } else {\n this._items.push(msg);\n }\n return msg;\n }\n\n /**\n * Insert a single item or multiple items based on their `createdAt` field so\n * that the array keeps its chronological order.\n */\n insert(item: ChatItem | ChatItem[]): void {\n const arr = Array.isArray(item) ? item : [item];\n for (const it of arr) {\n const idx = this.findInsertionIndex(it.createdAt);\n this._items.splice(idx, 0, it);\n }\n }\n\n getById(itemId: string): ChatItem | undefined {\n return this._items.find((i) => i.id === itemId);\n }\n\n indexById(itemId: string): number | undefined {\n const idx = this._items.findIndex((i) => i.id === itemId);\n return idx !== -1 ? idx : undefined;\n }\n\n // TODO(parity): Add excludeConfigUpdate option when AgentConfigUpdate is ported\n copy(\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n excludeEmptyMessage?: boolean;\n excludeHandoff?: boolean;\n toolCtx?: ToolContext<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n } = {},\n ): ChatContext {\n const {\n excludeFunctionCall = false,\n excludeInstructions = false,\n excludeEmptyMessage = false,\n excludeHandoff = false,\n toolCtx,\n } = options;\n const items: ChatItem[] = [];\n\n const isToolCallOrOutput = (item: ChatItem): item is FunctionCall | FunctionCallOutput =>\n ['function_call', 'function_call_output'].includes(item.type);\n const isChatMessage = (item: ChatItem): item is ChatMessage => item.type === 'message';\n\n for (const item of this._items) {\n if (excludeFunctionCall && isToolCallOrOutput(item)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n isChatMessage(item) &&\n ['system', 'developer'].includes(item.role)\n ) {\n continue;\n }\n\n if (excludeEmptyMessage && isChatMessage(item) && item.content.length === 0) {\n continue;\n }\n\n if (excludeHandoff && item.type === 'agent_handoff') {\n continue;\n }\n\n if (toolCtx !== undefined && isToolCallOrOutput(item) && toolCtx[item.name] === undefined) {\n continue;\n }\n\n items.push(item);\n }\n\n return new ChatContext(items);\n }\n\n // TODO(parity): Add excludeConfigUpdate option when AgentConfigUpdate is ported\n merge(\n other: ChatContext,\n options: {\n excludeFunctionCall?: boolean;\n excludeInstructions?: boolean;\n } = {},\n ): ChatContext {\n const { excludeFunctionCall = false, excludeInstructions = false } = options;\n const existingIds = new Set(this._items.map((item) => item.id));\n\n for (const item of other.items) {\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (\n excludeInstructions &&\n item.type === 'message' &&\n (item.role === 'system' || item.role === 'developer')\n ) {\n continue;\n }\n\n if (existingIds.has(item.id)) {\n continue;\n }\n\n const idx = this.findInsertionIndex(item.createdAt);\n this._items.splice(idx, 0, item);\n existingIds.add(item.id);\n }\n\n return this;\n }\n\n truncate(maxItems: number): ChatContext {\n if (maxItems <= 0) return this;\n\n const instructions = this._items.find((i) => i.type === 'message' && i.role === 'system') as\n | ChatMessage\n | undefined;\n\n let newItems = this._items.slice(-maxItems);\n\n // Ensure the first item is not a function-call artefact.\n while (\n newItems.length > 0 &&\n ['function_call', 'function_call_output'].includes(newItems[0]!.type)\n ) {\n newItems.shift();\n }\n\n if (instructions) {\n // At this point `instructions` is defined, so it is safe to pass to `includes`.\n if (!newItems.includes(instructions)) {\n newItems = [instructions, ...newItems];\n }\n }\n\n // replace the items in place to keep the reference\n this._items.splice(0, this._items.length, ...newItems);\n return this;\n }\n\n toJSON(\n options: {\n excludeImage?: boolean;\n excludeAudio?: boolean;\n excludeTimestamp?: boolean;\n excludeFunctionCall?: boolean;\n } = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): JSONObject {\n const {\n excludeImage = true,\n excludeAudio = true,\n excludeTimestamp = true,\n excludeFunctionCall = false,\n } = options;\n\n const items: ChatItem[] = [];\n\n for (const item of this._items) {\n let processedItem = item;\n\n if (excludeFunctionCall && ['function_call', 'function_call_output'].includes(item.type)) {\n continue;\n }\n\n if (item.type === 'message') {\n processedItem = ChatMessage.create({\n role: item.role,\n content: item.content,\n id: item.id,\n interrupted: item.interrupted,\n createdAt: item.createdAt,\n transcriptConfidence: item.transcriptConfidence,\n metrics: item.metrics,\n extra: item.extra,\n });\n\n // Filter content based on options\n if (excludeImage) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'image_content');\n });\n }\n\n if (excludeAudio) {\n processedItem.content = processedItem.content.filter((c) => {\n return !(typeof c === 'object' && c.type === 'audio_content');\n });\n }\n }\n\n items.push(processedItem);\n }\n\n return {\n items: items.map((item) => item.toJSON(excludeTimestamp)),\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async toProviderFormat(format: ProviderFormat, injectDummyUserMessage: boolean = true) {\n return await toChatCtx(format, this, injectDummyUserMessage);\n }\n\n /**\n * Internal helper used by `truncate` & `addMessage` to find the correct\n * insertion index for a timestamp so the list remains sorted.\n */\n private findInsertionIndex(createdAt: number): number {\n for (let i = this._items.length - 1; i >= 0; i -= 1) {\n const item = this._items[i];\n if (item!.createdAt <= createdAt) {\n return i + 1;\n }\n }\n return 0;\n }\n\n /**\n * Return true if `other` has the same sequence of items with matching\n * essential fields (IDs, types, and payload) as this context.\n *\n * Comparison rules:\n * - Messages: compares the full `content` list, `role` and `interrupted`.\n * - Function calls: compares `name`, `callId`, and `args`.\n * - Function call outputs: compares `name`, `callId`, `output`, and `isError`.\n *\n * Does not consider timestamps or other metadata.\n */\n isEquivalent(other: ChatContext): boolean {\n if (this === other) {\n return true;\n }\n\n if (this.items.length !== other.items.length) {\n return false;\n }\n\n for (let i = 0; i < this.items.length; i++) {\n const a = this.items[i]!;\n const b = other.items[i]!;\n\n if (a.id !== b.id || a.type !== b.type) {\n return false;\n }\n\n if (a.type === 'message' && b.type === 'message') {\n if (\n a.role !== b.role ||\n a.interrupted !== b.interrupted ||\n !this.compareContent(a.content, b.content)\n ) {\n return false;\n }\n } else if (a.type === 'function_call' && b.type === 'function_call') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.args !== b.args ||\n a.thoughtSignature !== b.thoughtSignature ||\n a.groupId !== b.groupId ||\n JSON.stringify(a.extra) !== JSON.stringify(b.extra)\n ) {\n return false;\n }\n } else if (a.type === 'function_call_output' && b.type === 'function_call_output') {\n if (\n a.name !== b.name ||\n a.callId !== b.callId ||\n a.output !== b.output ||\n a.isError !== b.isError\n ) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n /**\n * Compare two content arrays for equality.\n */\n private compareContent(a: ChatContent[], b: ChatContent[]): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n for (let i = 0; i < a.length; i++) {\n const contentA = a[i]!;\n const contentB = b[i]!;\n\n if (typeof contentA === 'string' && typeof contentB === 'string') {\n if (contentA !== contentB) {\n return false;\n }\n continue;\n }\n\n if (typeof contentA !== typeof contentB) {\n return false;\n }\n\n if (typeof contentA === 'object' && typeof contentB === 'object') {\n if (contentA.type === 'image_content' && contentB.type === 'image_content') {\n if (\n contentA.id !== contentB.id ||\n contentA.image !== contentB.image ||\n contentA.inferenceDetail !== contentB.inferenceDetail ||\n contentA.inferenceWidth !== contentB.inferenceWidth ||\n contentA.inferenceHeight !== contentB.inferenceHeight ||\n contentA.mimeType !== contentB.mimeType\n ) {\n return false;\n }\n } else if (contentA.type === 'audio_content' && contentB.type === 'audio_content') {\n if (contentA.frame.length !== contentB.frame.length) {\n return false;\n }\n if (contentA.transcript !== contentB.transcript) {\n return false;\n }\n } else {\n return false;\n }\n }\n }\n\n return true;\n }\n\n async _summarize(llm: LLM, options: { keepLastTurns?: number } = {}): Promise<ChatContext> {\n const { keepLastTurns = 2 } = options;\n\n // Split the history into a head/tail over the full item stream so recent\n // tool calls/outputs stay attached to the turns they belong to.\n const msgBudget = keepLastTurns * 2;\n let splitIdx = this._items.length;\n\n if (msgBudget > 0) {\n let msgCount = 0;\n let foundSplit = false;\n for (let i = this._items.length - 1; i >= 0; i -= 1) {\n const item = this._items[i]!;\n if (item.type === 'message' && (item.role === 'user' || item.role === 'assistant')) {\n msgCount += 1;\n if (msgCount >= msgBudget) {\n splitIdx = i;\n foundSplit = true;\n break;\n }\n }\n }\n\n if (!foundSplit) {\n return this;\n }\n }\n\n if (splitIdx === 0) {\n return this;\n }\n\n const headItems = this._items.slice(0, splitIdx);\n const tailItems = this._items.slice(splitIdx);\n\n const toSummarize: Array<ChatMessage | FunctionCall | FunctionCallOutput> = [];\n for (const item of headItems) {\n if (item.type === 'message') {\n if (item.role !== 'user' && item.role !== 'assistant') continue;\n if (item.extra?.is_summary === true) continue;\n\n const text = (item.textContent ?? '').trim();\n if (text) {\n toSummarize.push(item);\n }\n } else if (item.type === 'function_call' || item.type === 'function_call_output') {\n toSummarize.push(item);\n }\n }\n\n if (toSummarize.length === 0) {\n return this;\n }\n\n const sourceText = toSummarize\n .map((item) => {\n if (item.type === 'message') {\n return toXml(item.role, (item.textContent ?? '').trim());\n }\n\n return functionCallItemToMessage(item).textContent ?? '';\n })\n .join('\\n')\n .trim();\n\n if (!sourceText) {\n return this;\n }\n\n // TODO: refactor this into LLMStream.collect API.\n const promptCtx = new ChatContext();\n promptCtx.addMessage({\n role: 'system',\n content: [\n 'Compress older conversation history into a short, faithful summary.',\n '',\n 'The conversation is formatted as XML. Here is how to read it:',\n '- <user>...</user> - something the user said.',\n '- <assistant>...</assistant> - something the assistant said.',\n '- <function_call name=\"...\" call_id=\"...\">...</function_call> - the assistant invoked an action.',\n '- <function_call_output name=\"...\" call_id=\"...\">...</function_call_output> - the result of that action. May contain <error>...</error> if it failed.',\n '',\n 'Guidelines:',\n '- Distill the information learned from function call outputs into the summary. Do not mention that a tool or function was called; just preserve the knowledge gained.',\n '- Focus on user goals, constraints, decisions, key facts, preferences, entities, and any pending or unresolved tasks.',\n '- Omit greetings, filler, and chit-chat.',\n '- Be concise.',\n ].join('\\n'),\n });\n promptCtx.addMessage({\n role: 'user',\n content: `Conversation to summarize:\\n\\n${sourceText}`,\n });\n\n const chunks: string[] = [];\n for await (const chunk of llm.chat({ chatCtx: promptCtx })) {\n if (chunk.delta?.content) {\n chunks.push(chunk.delta.content);\n }\n }\n\n const summary = chunks.join('').trim();\n if (!summary) {\n return this;\n }\n\n const preserved: ChatItem[] = [];\n for (const it of headItems) {\n if (it.type === 'message' && (it.role === 'user' || it.role === 'assistant')) {\n continue;\n }\n\n if (it.type === 'function_call' || it.type === 'function_call_output') {\n continue;\n }\n\n preserved.push(it);\n }\n\n this._items = preserved;\n\n const createdAtHint =\n tailItems.length > 0\n ? tailItems[0]!.createdAt - 1e-6\n : headItems[headItems.length - 1]!.createdAt + 1e-6;\n\n this.addMessage({\n role: 'assistant',\n content: toXml('chat_history_summary', summary),\n createdAt: createdAtHint,\n extra: { is_summary: true },\n });\n\n this._items.push(...tailItems);\n\n return this;\n }\n\n /**\n * Indicates whether the context is read-only\n */\n get readonly(): boolean {\n return false;\n }\n}\n\nfunction toAttrsStr(attrs?: Record<string, unknown>): string | undefined {\n if (!attrs) {\n return undefined;\n }\n\n return Object.entries(attrs)\n .map(([key, value]) => `${key}=\"${String(value)}\"`)\n .join(' ');\n}\n\nfunction toXml(tagName: string, content?: string, attrs?: Record<string, unknown>): string {\n const attrsStr = toAttrsStr(attrs);\n if (content) {\n return [attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`, content, `</${tagName}>`].join(\n '\\n',\n );\n }\n\n return attrsStr ? `<${tagName} ${attrsStr} />` : `<${tagName} />`;\n}\n\nfunction functionCallItemToMessage(item: FunctionCall | FunctionCallOutput): ChatMessage {\n if (item.type === 'function_call') {\n return new ChatMessage({\n role: 'user',\n content: [\n toXml('function_call', item.args, {\n name: item.name,\n call_id: item.callId,\n }),\n ],\n createdAt: item.createdAt,\n extra: { is_function_call: true },\n });\n }\n\n return new ChatMessage({\n role: 'assistant',\n content: [\n toXml('function_call_output', item.isError ? toXml('error', item.output) : item.output, {\n name: item.name,\n call_id: item.callId,\n }),\n ],\n createdAt: item.createdAt,\n extra: { is_function_call_output: true },\n });\n}\n\nexport class ReadonlyChatContext extends ChatContext {\n static readonly errorMsg =\n 'Please use .copy() and agent.update_chat_ctx() to modify the chat context.';\n\n constructor(items: ChatItem[]) {\n super(createImmutableArray(items, ReadonlyChatContext.errorMsg));\n }\n\n get items(): ChatItem[] {\n return this._items;\n }\n\n set items(items: ChatItem[]) {\n throw new Error(\n `Cannot set items on a read-only chat context. ${ReadonlyChatContext.errorMsg}`,\n );\n }\n\n get readonly(): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAgD;AAEhD,6BAA+C;AAmCxC,SAAS,mBAAmB,QAOlB;AACf,QAAM;AAAA,IACJ;AAAA,IACA,SAAK,wBAAU,MAAM;AAAA,IACrB,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ,CAAC;AAAA,EACX;AACF;AAEO,SAAS,mBAAmB,QAGlB;AACf,QAAM,EAAE,OAAO,WAAW,IAAI;AAE9B,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AACF;AAaO,MAAM,YAAY;AAAA,EACd;AAAA,EAEA,OAAO;AAAA,EAEP;AAAA,EAET;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA,YAAY,QAST;AACD,UAAM;AAAA,MACJ;AAAA,MACA;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AAC;QAC9B,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC1B,GACL,WAAW;IA6Bd,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW;IA6BvC,MAAM,CACJ,OAAO,GAAE;QACP,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC1B,GAEL,UAAU;IAoDP,gBAAgB,CAAC,MAAM,EAAE,cAAc,EAAE,sBAAsB,GAAE,OAAc;IAIrF;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAU1B;;;;;;;;;;OAUG;IACH,YAAY,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO;IAmDzC;;OAEG;IACH,OAAO,CAAC,cAAc;IAgDhB,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,WAAW,CAAC;IA0I1F;;OAEG;IACH,IAAI,QAAQ,IAAI,OAAO,CAEtB;CACF;AAmDD,qBAAa,mBAAoB,SAAQ,WAAW;IAClD,MAAM,CAAC,QAAQ,CAAC,QAAQ,gFACuD;gBAEnE,KAAK,EAAE,QAAQ,EAAE;IAI7B,IAAI,KAAK,IAAI,QAAQ,EAAE,CAEtB;IAED,IAAI,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,EAI1B;IAED,IAAI,QAAQ,IAAI,OAAO,CAEtB;CACF"}
@@ -508,40 +508,74 @@ class ChatContext {
508
508
  async _summarize(llm, options = {}) {
509
509
  var _a, _b;
510
510
  const { keepLastTurns = 2 } = options;
511
- const toSummarize = [];
512
- for (const item of this._items) {
513
- if (item.type !== "message") continue;
514
- if (item.role !== "user" && item.role !== "assistant") continue;
515
- if (((_a = item.extra) == null ? void 0 : _a.is_summary) === true) continue;
516
- const text = (item.textContent ?? "").trim();
517
- if (text) {
518
- toSummarize.push(item);
511
+ const msgBudget = keepLastTurns * 2;
512
+ let splitIdx = this._items.length;
513
+ if (msgBudget > 0) {
514
+ let msgCount = 0;
515
+ let foundSplit = false;
516
+ for (let i = this._items.length - 1; i >= 0; i -= 1) {
517
+ const item = this._items[i];
518
+ if (item.type === "message" && (item.role === "user" || item.role === "assistant")) {
519
+ msgCount += 1;
520
+ if (msgCount >= msgBudget) {
521
+ splitIdx = i;
522
+ foundSplit = true;
523
+ break;
524
+ }
525
+ }
526
+ }
527
+ if (!foundSplit) {
528
+ return this;
519
529
  }
520
530
  }
521
- if (toSummarize.length === 0) {
531
+ if (splitIdx === 0) {
522
532
  return this;
523
533
  }
524
- const tailN = Math.max(0, Math.min(toSummarize.length, keepLastTurns * 2));
525
- let head;
526
- let tail;
527
- if (tailN === 0) {
528
- head = toSummarize;
529
- tail = [];
530
- } else {
531
- head = toSummarize.slice(0, -tailN);
532
- tail = toSummarize.slice(-tailN);
534
+ const headItems = this._items.slice(0, splitIdx);
535
+ const tailItems = this._items.slice(splitIdx);
536
+ const toSummarize = [];
537
+ for (const item of headItems) {
538
+ if (item.type === "message") {
539
+ if (item.role !== "user" && item.role !== "assistant") continue;
540
+ if (((_a = item.extra) == null ? void 0 : _a.is_summary) === true) continue;
541
+ const text = (item.textContent ?? "").trim();
542
+ if (text) {
543
+ toSummarize.push(item);
544
+ }
545
+ } else if (item.type === "function_call" || item.type === "function_call_output") {
546
+ toSummarize.push(item);
547
+ }
533
548
  }
534
- if (head.length === 0) {
549
+ if (toSummarize.length === 0) {
535
550
  return this;
536
551
  }
537
- const sourceText = head.map((m) => `${m.role}: ${(m.textContent ?? "").trim()}`).join("\n").trim();
552
+ const sourceText = toSummarize.map((item) => {
553
+ if (item.type === "message") {
554
+ return toXml(item.role, (item.textContent ?? "").trim());
555
+ }
556
+ return functionCallItemToMessage(item).textContent ?? "";
557
+ }).join("\n").trim();
538
558
  if (!sourceText) {
539
559
  return this;
540
560
  }
541
561
  const promptCtx = new ChatContext();
542
562
  promptCtx.addMessage({
543
563
  role: "system",
544
- content: "Compress older chat history into a short, faithful summary.\nFocus on user goals, constraints, decisions, key facts/preferences/entities, and pending tasks.\nExclude chit-chat and greetings. Be concise."
564
+ content: [
565
+ "Compress older conversation history into a short, faithful summary.",
566
+ "",
567
+ "The conversation is formatted as XML. Here is how to read it:",
568
+ "- <user>...</user> - something the user said.",
569
+ "- <assistant>...</assistant> - something the assistant said.",
570
+ '- <function_call name="..." call_id="...">...</function_call> - the assistant invoked an action.',
571
+ '- <function_call_output name="..." call_id="...">...</function_call_output> - the result of that action. May contain <error>...</error> if it failed.',
572
+ "",
573
+ "Guidelines:",
574
+ "- Distill the information learned from function call outputs into the summary. Do not mention that a tool or function was called; just preserve the knowledge gained.",
575
+ "- Focus on user goals, constraints, decisions, key facts, preferences, entities, and any pending or unresolved tasks.",
576
+ "- Omit greetings, filler, and chit-chat.",
577
+ "- Be concise."
578
+ ].join("\n")
545
579
  });
546
580
  promptCtx.addMessage({
547
581
  role: "user",
@@ -559,29 +593,25 @@ ${sourceText}`
559
593
  if (!summary) {
560
594
  return this;
561
595
  }
562
- const tailStartTs = tail.length > 0 ? tail[0].createdAt : Infinity;
563
596
  const preserved = [];
564
- for (const it of this._items) {
565
- if ((it.type === "function_call" || it.type === "function_call_output") && it.createdAt < tailStartTs) {
597
+ for (const it of headItems) {
598
+ if (it.type === "message" && (it.role === "user" || it.role === "assistant")) {
566
599
  continue;
567
600
  }
568
- if (it.type === "message" && (it.role === "user" || it.role === "assistant")) {
601
+ if (it.type === "function_call" || it.type === "function_call_output") {
569
602
  continue;
570
603
  }
571
604
  preserved.push(it);
572
605
  }
573
606
  this._items = preserved;
574
- const createdAtHint = tail.length > 0 ? tail[0].createdAt - 1e-3 : head[head.length - 1].createdAt + 1e-3;
607
+ const createdAtHint = tailItems.length > 0 ? tailItems[0].createdAt - 1e-6 : headItems[headItems.length - 1].createdAt + 1e-6;
575
608
  this.addMessage({
576
609
  role: "assistant",
577
- content: `[history summary]
578
- ${summary}`,
610
+ content: toXml("chat_history_summary", summary),
579
611
  createdAt: createdAtHint,
580
612
  extra: { is_summary: true }
581
613
  });
582
- for (const msg of tail) {
583
- this.insert(msg);
584
- }
614
+ this._items.push(...tailItems);
585
615
  return this;
586
616
  }
587
617
  /**
@@ -591,6 +621,47 @@ ${summary}`,
591
621
  return false;
592
622
  }
593
623
  }
624
+ function toAttrsStr(attrs) {
625
+ if (!attrs) {
626
+ return void 0;
627
+ }
628
+ return Object.entries(attrs).map(([key, value]) => `${key}="${String(value)}"`).join(" ");
629
+ }
630
+ function toXml(tagName, content, attrs) {
631
+ const attrsStr = toAttrsStr(attrs);
632
+ if (content) {
633
+ return [attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`, content, `</${tagName}>`].join(
634
+ "\n"
635
+ );
636
+ }
637
+ return attrsStr ? `<${tagName} ${attrsStr} />` : `<${tagName} />`;
638
+ }
639
+ function functionCallItemToMessage(item) {
640
+ if (item.type === "function_call") {
641
+ return new ChatMessage({
642
+ role: "user",
643
+ content: [
644
+ toXml("function_call", item.args, {
645
+ name: item.name,
646
+ call_id: item.callId
647
+ })
648
+ ],
649
+ createdAt: item.createdAt,
650
+ extra: { is_function_call: true }
651
+ });
652
+ }
653
+ return new ChatMessage({
654
+ role: "assistant",
655
+ content: [
656
+ toXml("function_call_output", item.isError ? toXml("error", item.output) : item.output, {
657
+ name: item.name,
658
+ call_id: item.callId
659
+ })
660
+ ],
661
+ createdAt: item.createdAt,
662
+ extra: { is_function_call_output: true }
663
+ });
664
+ }
594
665
  class ReadonlyChatContext extends ChatContext {
595
666
  static errorMsg = "Please use .copy() and agent.update_chat_ctx() to modify the chat context.";
596
667
  constructor(items) {