@yolk-sdk/agent 0.1.0-canary.32 → 0.1.0-canary.35

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 (148) hide show
  1. package/README.md +30 -1
  2. package/dist/compaction/transformer.d.mts.map +1 -1
  3. package/dist/compaction/transformer.mjs.map +1 -1
  4. package/dist/protocol/content.d.mts +14 -1
  5. package/dist/protocol/content.d.mts.map +1 -1
  6. package/dist/protocol/content.mjs +26 -7
  7. package/dist/protocol/content.mjs.map +1 -1
  8. package/dist/protocol/index.d.mts +2 -2
  9. package/dist/protocol/index.d.mts.map +1 -1
  10. package/dist/protocol/index.mjs +2 -2
  11. package/dist/protocol/message.d.mts.map +1 -1
  12. package/dist/protocol/message.mjs.map +1 -1
  13. package/dist/protocol/tool.d.mts.map +1 -1
  14. package/dist/protocol/tool.mjs.map +1 -1
  15. package/dist/providers/anthropic/claude-provider.d.mts.map +1 -1
  16. package/dist/providers/anthropic/claude-provider.mjs +3 -3
  17. package/dist/providers/anthropic/claude-provider.mjs.map +1 -1
  18. package/dist/providers/anthropic/claude.d.mts.map +1 -1
  19. package/dist/providers/anthropic/claude.mjs.map +1 -1
  20. package/dist/providers/openai/codex-provider.d.mts.map +1 -1
  21. package/dist/providers/openai/codex-provider.mjs +2 -2
  22. package/dist/providers/openai/codex-provider.mjs.map +1 -1
  23. package/dist/providers/openai/provider.d.mts.map +1 -1
  24. package/dist/providers/openai/provider.mjs +2 -2
  25. package/dist/providers/openai/provider.mjs.map +1 -1
  26. package/dist/providers/openai/realtime/client-codec.d.mts +12 -0
  27. package/dist/providers/openai/realtime/client-codec.d.mts.map +1 -0
  28. package/dist/providers/openai/realtime/client-codec.mjs +26 -0
  29. package/dist/providers/openai/realtime/client-codec.mjs.map +1 -0
  30. package/dist/providers/openai/realtime/events.d.mts +135 -0
  31. package/dist/providers/openai/realtime/events.d.mts.map +1 -0
  32. package/dist/providers/openai/realtime/events.mjs +240 -0
  33. package/dist/providers/openai/realtime/events.mjs.map +1 -0
  34. package/dist/providers/openai/realtime/index.d.mts +5 -0
  35. package/dist/providers/openai/realtime/index.mjs +5 -0
  36. package/dist/providers/openai/realtime/session-config.d.mts +91 -0
  37. package/dist/providers/openai/realtime/session-config.d.mts.map +1 -0
  38. package/dist/providers/openai/realtime/session-config.mjs +129 -0
  39. package/dist/providers/openai/realtime/session-config.mjs.map +1 -0
  40. package/dist/providers/openai/realtime/to-voice.d.mts +14 -0
  41. package/dist/providers/openai/realtime/to-voice.d.mts.map +1 -0
  42. package/dist/providers/openai/realtime/to-voice.mjs +53 -0
  43. package/dist/providers/openai/realtime/to-voice.mjs.map +1 -0
  44. package/dist/providers/openai/speech.d.mts +34 -0
  45. package/dist/providers/openai/speech.d.mts.map +1 -0
  46. package/dist/providers/openai/speech.mjs +127 -0
  47. package/dist/providers/openai/speech.mjs.map +1 -0
  48. package/dist/providers/provider-error.d.mts.map +1 -1
  49. package/dist/providers/provider-error.mjs.map +1 -1
  50. package/dist/providers/transcript.d.mts.map +1 -1
  51. package/dist/providers/transcript.mjs.map +1 -1
  52. package/dist/react/use-agent-chat.d.mts.map +1 -1
  53. package/dist/react/use-agent-chat.mjs.map +1 -1
  54. package/dist/runtime/run-runtime.mjs.map +1 -1
  55. package/dist/skillset/merge.d.mts +2 -2
  56. package/dist/tools/registry.d.mts.map +1 -1
  57. package/dist/tools/registry.mjs.map +1 -1
  58. package/dist/tools/task.d.mts.map +1 -1
  59. package/dist/tools/task.mjs.map +1 -1
  60. package/dist/voice/browser/index.d.mts +2 -0
  61. package/dist/voice/browser/index.mjs +2 -0
  62. package/dist/voice/browser/webrtc.d.mts +71 -0
  63. package/dist/voice/browser/webrtc.d.mts.map +1 -0
  64. package/dist/voice/browser/webrtc.mjs +156 -0
  65. package/dist/voice/browser/webrtc.mjs.map +1 -0
  66. package/dist/voice/client-codec.d.mts +18 -0
  67. package/dist/voice/client-codec.d.mts.map +1 -0
  68. package/dist/voice/client-codec.mjs +1 -0
  69. package/dist/voice/controller.d.mts +50 -0
  70. package/dist/voice/controller.d.mts.map +1 -0
  71. package/dist/voice/controller.mjs +118 -0
  72. package/dist/voice/controller.mjs.map +1 -0
  73. package/dist/voice/index.d.mts +11 -1
  74. package/dist/voice/index.mjs +10 -1
  75. package/dist/voice/outbox.d.mts +36 -0
  76. package/dist/voice/outbox.d.mts.map +1 -0
  77. package/dist/voice/outbox.mjs +80 -0
  78. package/dist/voice/outbox.mjs.map +1 -0
  79. package/dist/voice/projection.d.mts +92 -0
  80. package/dist/voice/projection.d.mts.map +1 -0
  81. package/dist/voice/projection.mjs +217 -0
  82. package/dist/voice/projection.mjs.map +1 -0
  83. package/dist/voice/protocol.d.mts +217 -0
  84. package/dist/voice/protocol.d.mts.map +1 -0
  85. package/dist/voice/protocol.mjs +197 -0
  86. package/dist/voice/protocol.mjs.map +1 -0
  87. package/dist/voice/react.d.mts +57 -0
  88. package/dist/voice/react.d.mts.map +1 -0
  89. package/dist/voice/react.mjs +255 -0
  90. package/dist/voice/react.mjs.map +1 -0
  91. package/dist/voice/session-log.d.mts +77 -0
  92. package/dist/voice/session-log.d.mts.map +1 -0
  93. package/dist/voice/session-log.mjs +144 -0
  94. package/dist/voice/session-log.mjs.map +1 -0
  95. package/dist/voice/speech.d.mts +70 -0
  96. package/dist/voice/speech.d.mts.map +1 -0
  97. package/dist/voice/speech.mjs +56 -0
  98. package/dist/voice/speech.mjs.map +1 -0
  99. package/dist/voice/tool-server.d.mts +44 -0
  100. package/dist/voice/tool-server.d.mts.map +1 -0
  101. package/dist/voice/tool-server.mjs +75 -0
  102. package/dist/voice/tool-server.mjs.map +1 -0
  103. package/dist/voice/transport.d.mts +19 -0
  104. package/dist/voice/transport.d.mts.map +1 -0
  105. package/dist/voice/transport.mjs +7 -0
  106. package/dist/voice/transport.mjs.map +1 -0
  107. package/dist/voice/websocket.d.mts +29 -0
  108. package/dist/voice/websocket.d.mts.map +1 -0
  109. package/dist/voice/websocket.mjs +75 -0
  110. package/dist/voice/websocket.mjs.map +1 -0
  111. package/package.json +21 -1
  112. package/src/compaction/index.ts +1 -5
  113. package/src/compaction/transformer.ts +1 -3
  114. package/src/protocol/content.ts +42 -7
  115. package/src/protocol/index.ts +2 -0
  116. package/src/protocol/message.ts +9 -7
  117. package/src/protocol/tool.ts +1 -3
  118. package/src/providers/anthropic/claude-provider.ts +55 -32
  119. package/src/providers/anthropic/claude.ts +1 -2
  120. package/src/providers/openai/codex-provider.ts +25 -12
  121. package/src/providers/openai/provider.ts +10 -2
  122. package/src/providers/openai/realtime/client-codec.ts +52 -0
  123. package/src/providers/openai/realtime/events.ts +400 -0
  124. package/src/providers/openai/realtime/index.ts +48 -0
  125. package/src/providers/openai/realtime/session-config.ts +270 -0
  126. package/src/providers/openai/realtime/to-voice.ts +73 -0
  127. package/src/providers/openai/speech.ts +237 -0
  128. package/src/providers/provider-error.ts +4 -5
  129. package/src/providers/transcript.ts +1 -4
  130. package/src/react/use-agent-chat.ts +6 -1
  131. package/src/runtime/run-runtime.ts +4 -4
  132. package/src/tools/README.md +8 -6
  133. package/src/tools/registry.ts +36 -27
  134. package/src/tools/task.ts +69 -51
  135. package/src/voice/browser/index.ts +13 -0
  136. package/src/voice/browser/webrtc.ts +303 -0
  137. package/src/voice/client-codec.ts +23 -0
  138. package/src/voice/controller.ts +289 -0
  139. package/src/voice/index.ts +101 -0
  140. package/src/voice/outbox.ts +155 -0
  141. package/src/voice/projection.ts +357 -0
  142. package/src/voice/protocol.ts +346 -0
  143. package/src/voice/react.ts +413 -0
  144. package/src/voice/session-log.ts +196 -0
  145. package/src/voice/speech.ts +101 -0
  146. package/src/voice/tool-server.ts +135 -0
  147. package/src/voice/transport.ts +17 -0
  148. package/src/voice/websocket.ts +128 -0
package/README.md CHANGED
@@ -31,11 +31,15 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
31
31
  | `@yolk-sdk/agent/providers/openai/codex` | OpenAI Codex request and auth helpers |
32
32
  | `@yolk-sdk/agent/providers/openai/codex-provider` | Codex LLM provider factory |
33
33
  | `@yolk-sdk/agent/providers/openai/provider` | OpenAI-compatible LLM provider factory |
34
+ | `@yolk-sdk/agent/providers/openai/realtime` | OpenAI Realtime session config and event codecs |
35
+ | `@yolk-sdk/agent/providers/openai/speech` | OpenAI text-to-speech and transcription adapters |
34
36
  | `@yolk-sdk/agent/providers/anthropic` | Anthropic/Claude OAuth and broker helpers |
35
37
  | `@yolk-sdk/agent/providers/anthropic/claude` | Claude request and auth helpers |
36
38
  | `@yolk-sdk/agent/providers/anthropic/claude-provider` | Claude LLM provider factory |
37
39
  | `@yolk-sdk/agent/skillset` | Portable skill and slash-command parsing/catalogs |
38
- | `@yolk-sdk/agent/voice` | Provider-neutral voice tool-call bridge |
40
+ | `@yolk-sdk/agent/voice` | Voice protocol, controller, tool handler, projection, speech |
41
+ | `@yolk-sdk/agent/voice/browser` | Browser WebRTC voice transport |
42
+ | `@yolk-sdk/agent/voice/react` | Headless browser voice React hook |
39
43
 
40
44
  ## Imports
41
45
 
@@ -300,6 +304,31 @@ for await (const event of streamAgentEventsUntilTerminal({
300
304
  The SDK client does not own durable route auth, run ownership, Workflow hook-token routing, or HITL
301
305
  request matching. Hosts expose the run endpoints and validate access/response identity server-side.
302
306
 
307
+ ## Voice
308
+
309
+ Voice is a first-class modality: browser WebRTC transport, client controller, server tool
310
+ handler, approval HITL, transcript projection, and one-shot TTS/STT contracts.
311
+
312
+ - `useYolkVoice` (`@yolk-sdk/agent/voice/react`) owns browser session lifecycle, user drafts,
313
+ and pending approvals; provider codecs come from `@yolk-sdk/agent/providers/openai/realtime`.
314
+ - Tools execute server-side only: the controller forwards provider tool calls as
315
+ `VoiceSessionToolCallRequest` to your endpoint; `handleVoiceToolCall` applies
316
+ `ToolDef.approval` policy and never runs approval-gated tools without a matching approved
317
+ response.
318
+ - Approval-gated calls pause with `AwaitingInput`; approvals/denials resume through
319
+ `submitHitlResponse`. Voice `question` is deferred in v1.
320
+ - `projectVoiceEvent` turns voice events into protocol messages with no dangling host tool
321
+ calls. Assistant drafts are keyed per provider output item (falling back to response id), so
322
+ back-to-back responses, multi-item responses, and duplicate final transcript event families
323
+ never concatenate, wipe, or duplicate messages. `sequenceVoiceEvent`/`dedupeStoredVoiceEvents`
324
+ give replay-safe durable event ids; `voiceSeedTextsFromMessages` seeds new provider sessions
325
+ after reconnect.
326
+ - `makeWebSocketVoiceTransport` covers Node/server realtime sessions;
327
+ `@yolk-sdk/agent/providers/openai/speech` provides `VoiceSpeechSynthesizer` /
328
+ `VoiceTranscriber` layers. `VoiceSpeechRequest.instructions` steers delivery style only, and
329
+ provider 429s (rate limit or exhausted credits) surface as `VoiceSpeechError` code
330
+ `rate_limited` so hosts can distinguish quota from outage.
331
+
303
332
  ## Task subagents
304
333
 
305
334
  `task` is the package-owned contract for subagent delegation. The SDK provides schema,
@@ -1 +1 @@
1
- {"version":3,"file":"transformer.d.mts","names":[],"sources":["../../src/compaction/transformer.ts"],"mappings":";;;;;;;KAYY,qBAAA,IACV,QAAA,EAAU,aAAA,CAAc,YAAA,MACrB,YAAA;AAAA,KAEO,uBAAA;EAAA,SACD,QAAA;EAAA,SACA,eAAA;EAAA,SACA,gBAAA;EAAA,SACA,WAAA;EAAA,SACA,cAAA,GAAiB,wBAAA;EAAA,SACjB,kBAAA,EAAoB,qBAAqB;AAAA;AAAA,cAWvC,qBAAA,GACX,QAAA,EAAU,aAAA,CAAc,YAAA,GACxB,OAAA,EAAS,uBAAA,KACR,gBAAA;AAAA,cAcU,+BAAA,GAAmC,OAAA,EAAS,uBAAA,KAAuB,KAAA,CAAA,KAAA,CAAA,kBAAA"}
1
+ {"version":3,"file":"transformer.d.mts","names":[],"sources":["../../src/compaction/transformer.ts"],"mappings":";;;;;;;KAYY,qBAAA,IAAyB,QAAA,EAAU,aAAA,CAAc,YAAA,MAAkB,YAAA;AAAA,KAEnE,uBAAA;EAAA,SACD,QAAA;EAAA,SACA,eAAA;EAAA,SACA,gBAAA;EAAA,SACA,WAAA;EAAA,SACA,cAAA,GAAiB,wBAAA;EAAA,SACjB,kBAAA,EAAoB,qBAAqB;AAAA;AAAA,cAWvC,qBAAA,GACX,QAAA,EAAU,aAAA,CAAc,YAAA,GACxB,OAAA,EAAS,uBAAA,KACR,gBAAA;AAAA,cAcU,+BAAA,GAAmC,OAAA,EAAS,uBAAA,KAAuB,KAAA,CAAA,KAAA,CAAA,kBAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"transformer.mjs","names":[],"sources":["../../src/compaction/transformer.ts"],"sourcesContent":["import { Effect, Layer } from 'effect'\nimport type { AgentMessage } from '@yolk-sdk/agent/protocol'\nimport { ContextTransformer } from '@yolk-sdk/agent/loop'\nimport {\n applyCompactionPlan,\n planWindowCompaction,\n type CompactionResult,\n type SkippedCompactionPlan,\n type SkippedCompactionResult\n} from './window.ts'\nimport type { TranscriptTokenEstimator } from './estimator.ts'\n\nexport type SummaryMessageFactory = (\n messages: ReadonlyArray<AgentMessage>\n) => AgentMessage\n\nexport type WindowCompactionOptions = {\n readonly strategy: string\n readonly thresholdTokens: number\n readonly tailMessageCount?: number\n readonly minMessages?: number\n readonly estimateTokens?: TranscriptTokenEstimator\n readonly makeSummaryMessage: SummaryMessageFactory\n}\n\nconst skippedCompactionResult = (plan: SkippedCompactionPlan): SkippedCompactionResult => ({\n _tag: 'Skipped',\n reason: plan.reason,\n messages: plan.messages,\n events: [],\n beforeTokens: plan.beforeTokens\n})\n\nexport const compactWindowMessages = (\n messages: ReadonlyArray<AgentMessage>,\n options: WindowCompactionOptions\n): CompactionResult => {\n const plan = planWindowCompaction(messages, options)\n\n if (plan._tag === 'Skip') {\n return skippedCompactionResult(plan)\n }\n\n return applyCompactionPlan(plan, {\n strategy: options.strategy,\n summaryMessage: options.makeSummaryMessage(plan.compactedMessages),\n estimateTokens: options.estimateTokens\n })\n}\n\nexport const makeWindowCompactionTransformer = (options: WindowCompactionOptions) =>\n Layer.succeed(\n ContextTransformer,\n ContextTransformer.of({\n transform: messages => Effect.succeed(compactWindowMessages(messages, options))\n })\n )\n"],"mappings":";;;;AAyBA,MAAM,2BAA2B,UAA0D;CACzF,MAAM;CACN,QAAQ,KAAK;CACb,UAAU,KAAK;CACf,QAAQ,CAAC;CACT,cAAc,KAAK;AACrB;AAEA,MAAa,yBACX,UACA,YACqB;CACrB,MAAM,OAAO,qBAAqB,UAAU,OAAO;CAEnD,IAAI,KAAK,SAAS,QAChB,OAAO,wBAAwB,IAAI;CAGrC,OAAO,oBAAoB,MAAM;EAC/B,UAAU,QAAQ;EAClB,gBAAgB,QAAQ,mBAAmB,KAAK,iBAAiB;EACjE,gBAAgB,QAAQ;CAC1B,CAAC;AACH;AAEA,MAAa,mCAAmC,YAC9C,MAAM,QACJ,oBACA,mBAAmB,GAAG,EACpB,YAAW,aAAY,OAAO,QAAQ,sBAAsB,UAAU,OAAO,CAAC,EAChF,CAAC,CACH"}
1
+ {"version":3,"file":"transformer.mjs","names":[],"sources":["../../src/compaction/transformer.ts"],"sourcesContent":["import { Effect, Layer } from 'effect'\nimport type { AgentMessage } from '@yolk-sdk/agent/protocol'\nimport { ContextTransformer } from '@yolk-sdk/agent/loop'\nimport {\n applyCompactionPlan,\n planWindowCompaction,\n type CompactionResult,\n type SkippedCompactionPlan,\n type SkippedCompactionResult\n} from './window.ts'\nimport type { TranscriptTokenEstimator } from './estimator.ts'\n\nexport type SummaryMessageFactory = (messages: ReadonlyArray<AgentMessage>) => AgentMessage\n\nexport type WindowCompactionOptions = {\n readonly strategy: string\n readonly thresholdTokens: number\n readonly tailMessageCount?: number\n readonly minMessages?: number\n readonly estimateTokens?: TranscriptTokenEstimator\n readonly makeSummaryMessage: SummaryMessageFactory\n}\n\nconst skippedCompactionResult = (plan: SkippedCompactionPlan): SkippedCompactionResult => ({\n _tag: 'Skipped',\n reason: plan.reason,\n messages: plan.messages,\n events: [],\n beforeTokens: plan.beforeTokens\n})\n\nexport const compactWindowMessages = (\n messages: ReadonlyArray<AgentMessage>,\n options: WindowCompactionOptions\n): CompactionResult => {\n const plan = planWindowCompaction(messages, options)\n\n if (plan._tag === 'Skip') {\n return skippedCompactionResult(plan)\n }\n\n return applyCompactionPlan(plan, {\n strategy: options.strategy,\n summaryMessage: options.makeSummaryMessage(plan.compactedMessages),\n estimateTokens: options.estimateTokens\n })\n}\n\nexport const makeWindowCompactionTransformer = (options: WindowCompactionOptions) =>\n Layer.succeed(\n ContextTransformer,\n ContextTransformer.of({\n transform: messages => Effect.succeed(compactWindowMessages(messages, options))\n })\n )\n"],"mappings":";;;;AAuBA,MAAM,2BAA2B,UAA0D;CACzF,MAAM;CACN,QAAQ,KAAK;CACb,UAAU,KAAK;CACf,QAAQ,CAAC;CACT,cAAc,KAAK;AACrB;AAEA,MAAa,yBACX,UACA,YACqB;CACrB,MAAM,OAAO,qBAAqB,UAAU,OAAO;CAEnD,IAAI,KAAK,SAAS,QAChB,OAAO,wBAAwB,IAAI;CAGrC,OAAO,oBAAoB,MAAM;EAC/B,UAAU,QAAQ;EAClB,gBAAgB,QAAQ,mBAAmB,KAAK,iBAAiB;EACjE,gBAAgB,QAAQ;CAC1B,CAAC;AACH;AAEA,MAAa,mCAAmC,YAC9C,MAAM,QACJ,oBACA,mBAAmB,GAAG,EACpB,YAAW,aAAY,OAAO,QAAQ,sBAAsB,UAAU,OAAO,CAAC,EAChF,CAAC,CACH"}
@@ -52,6 +52,19 @@ type AttachmentSourceResolver<E = never, R = never> = (part: AttachmentContentPa
52
52
  declare const resolveContentAttachmentSources: <E, R>(content: Content, resolver: AttachmentSourceResolver<E, R>) => Effect.Effect<Content, E, R>;
53
53
  declare const contentPartText: (part: ContentPart) => string;
54
54
  declare const contentPartPreview: (part: ContentPart) => string;
55
+ /**
56
+ * Replace lone UTF-16 surrogates with U+FFFD. Models emit them in transcripts
57
+ * and tool arguments; they are valid JS strings but unencodable as UTF-8, so
58
+ * provider APIs and storage backends can reject payloads containing them.
59
+ */
60
+ declare const replaceLoneSurrogates: (text: string) => string;
61
+ /**
62
+ * Deep-apply `replaceLoneSurrogates` to every string (keys included) in a
63
+ * JSON-shaped value. Providers harden lowered request bodies with this before
64
+ * serialization so junk in replayed transcripts cannot poison model calls;
65
+ * hosts may also use it when persisting model-produced JSON.
66
+ */
67
+ declare const replaceLoneSurrogatesDeep: (value: unknown) => unknown;
55
68
  declare const contentText: (content: Content) => string;
56
69
  declare const contentPreview: (content: Content) => string;
57
70
  declare const contentParts: (content: Content) => ReadonlyArray<ContentPart>;
@@ -80,5 +93,5 @@ declare const documentPartFromText: (input: {
80
93
  declare const attachmentSourceText: (source: AttachmentSource) => Effect.Effect<Option.Option<string>, unknown, never>;
81
94
  declare const attachmentSourceBase64: (source: AttachmentSource) => Option.Option<string>;
82
95
  //#endregion
83
- export { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource };
96
+ export { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource };
84
97
  //# sourceMappingURL=content.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"content.d.mts","names":[],"sources":["../../src/protocol/content.ts"],"mappings":";;;;cACuC,aAAA;;;cAE1B,QAAA,SAAiB,aAE5B;AAAA,cAAG,iCAAA;;;cAEQ,4BAAA,SAAqC,iCAKjD;AAAA,cAAG,wBAAA;;;cAES,mBAAA,SAA4B,wBAEvC;AAAA,cAAG,wBAAA;;;cAEQ,mBAAA,SAA4B,wBAEvC;AAAA,cAEW,gBAAA,EAAgB,MAAA,CAAA,KAAA,kBAAA,4BAAA,SAAA,mBAAA,SAAA,mBAAA;AAAA,KAKjB,gBAAA,UAA0B,gBAAA,CAAiB,IAAI;AAAA,cAAA,cAAA;;;;;;;;cAE9C,SAAA,SAAkB,cAO7B;AAAA,cAAG,iBAAA;;;;;;cAEQ,YAAA,SAAqB,iBAKhC;AAAA,cAAG,cAAA;;;;;;cAEQ,SAAA,SAAkB,cAK7B;AAAA,cAEW,WAAA,EAAW,MAAA,CAAA,KAAA,kBAAA,QAAA,SAAA,SAAA,SAAA,YAAA,SAAA,SAAA;AAAA,KACZ,WAAA,UAAqB,WAAA,CAAY,IAAI;AAAA,cAEpC,OAAA,EAAO,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA,EAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,KAAA,kBAAA,QAAA,SAAA,SAAA,SAAA,YAAA,SAAA,SAAA;AAAA,KACR,OAAA,UAAiB,OAAA,CAAQ,IAAI;AAAA,KAE7B,qBAAA,GAAwB,SAAA,GAAY,YAAA,GAAe,SAAA;AAAA,KAEnD,wBAAA,0BACV,IAAA,EAAM,qBAAA,KACH,MAAA,CAAO,MAAA,CAAO,gBAAA,EAAkB,CAAA,EAAG,CAAA;AAAA,cA+C3B,+BAAA,SACX,OAAA,EAAS,OAAA,EACT,QAAA,EAAU,wBAAA,CAAyB,CAAA,EAAG,CAAA,MAC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,GAAwB,MAAA,EAAQ,gBAAA,KAAgB,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA;AAAA,cAahD,sBAAA,GAA0B,MAAA,EAAQ,gBAAA,KAAgB,MAAA,CAAA,MAAA"}
@@ -1,4 +1,4 @@
1
- import { Array, Effect, Option } from "effect";
1
+ import { Array as Array$1, Effect, Option } from "effect";
2
2
  import * as Schema from "effect/Schema";
3
3
  //#region src/protocol/content.ts
4
4
  var TextPart = class extends Schema.TaggedClass()("Text", { text: Schema.String }) {};
@@ -79,15 +79,34 @@ const contentPartPreview = (part) => {
79
79
  case "Audio": return "Audio";
80
80
  }
81
81
  };
82
- const contentText = (content) => typeof content === "string" ? content : Array.map(content, contentPartText).join("");
83
- const contentPreview = (content) => typeof content === "string" ? content : Array.map(content, contentPartPreview).join(", ");
82
+ const loneSurrogates = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
83
+ /**
84
+ * Replace lone UTF-16 surrogates with U+FFFD. Models emit them in transcripts
85
+ * and tool arguments; they are valid JS strings but unencodable as UTF-8, so
86
+ * provider APIs and storage backends can reject payloads containing them.
87
+ */
88
+ const replaceLoneSurrogates = (text) => text.replace(loneSurrogates, "�");
89
+ /**
90
+ * Deep-apply `replaceLoneSurrogates` to every string (keys included) in a
91
+ * JSON-shaped value. Providers harden lowered request bodies with this before
92
+ * serialization so junk in replayed transcripts cannot poison model calls;
93
+ * hosts may also use it when persisting model-produced JSON.
94
+ */
95
+ const replaceLoneSurrogatesDeep = (value) => {
96
+ if (typeof value === "string") return replaceLoneSurrogates(value);
97
+ if (Array.isArray(value)) return value.map(replaceLoneSurrogatesDeep);
98
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [replaceLoneSurrogates(key), replaceLoneSurrogatesDeep(entry)]));
99
+ return value;
100
+ };
101
+ const contentText = (content) => typeof content === "string" ? content : Array$1.map(content, contentPartText).join("");
102
+ const contentPreview = (content) => typeof content === "string" ? content : Array$1.map(content, contentPartPreview).join(", ");
84
103
  const contentParts = (content) => typeof content === "string" ? [TextPart.make({ text: content })] : content;
85
- const isContentEmpty = (content) => typeof content === "string" ? content.length === 0 : content.length === 0 || Array.every(content, (part) => part._tag === "Text" && part.text.length === 0);
104
+ const isContentEmpty = (content) => typeof content === "string" ? content.length === 0 : content.length === 0 || Array$1.every(content, (part) => part._tag === "Text" && part.text.length === 0);
86
105
  const appendTextToContent = (content, text) => {
87
106
  if (typeof content === "string") return `${content}${text}`;
88
- return Option.match(Array.last(content), {
107
+ return Option.match(Array$1.last(content), {
89
108
  onNone: () => [TextPart.make({ text })],
90
- onSome: (last) => last._tag !== "Text" ? [...content, TextPart.make({ text })] : Array.map(content, (part, index) => index === content.length - 1 && part._tag === "Text" ? TextPart.make({ text: `${part.text}${text}` }) : part)
109
+ onSome: (last) => last._tag !== "Text" ? [...content, TextPart.make({ text })] : Array$1.map(content, (part, index) => index === content.length - 1 && part._tag === "Text" ? TextPart.make({ text: `${part.text}${text}` }) : part)
91
110
  });
92
111
  };
93
112
  const inlineBase64AttachmentSource = (data) => InlineBase64AttachmentSource.make({ data });
@@ -198,6 +217,6 @@ const attachmentSourceBase64 = (source) => {
198
217
  }
199
218
  };
200
219
  //#endregion
201
- export { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource };
220
+ export { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource };
202
221
 
203
222
  //# sourceMappingURL=content.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"content.mjs","names":["Arr"],"sources":["../../src/protocol/content.ts"],"sourcesContent":["import { Array as Arr, Effect, Option } from 'effect'\nimport * as Schema from 'effect/Schema'\n\nexport class TextPart extends Schema.TaggedClass<TextPart>()('Text', {\n text: Schema.String\n}) {}\n\nexport class InlineBase64AttachmentSource extends Schema.TaggedClass<InlineBase64AttachmentSource>()(\n 'InlineBase64',\n {\n data: Schema.String\n }\n) {}\n\nexport class UrlAttachmentSource extends Schema.TaggedClass<UrlAttachmentSource>()('Url', {\n url: Schema.String\n}) {}\n\nexport class RefAttachmentSource extends Schema.TaggedClass<RefAttachmentSource>()('Ref', {\n id: Schema.String\n}) {}\n\nexport const AttachmentSource = Schema.Union([\n InlineBase64AttachmentSource,\n UrlAttachmentSource,\n RefAttachmentSource\n])\nexport type AttachmentSource = typeof AttachmentSource.Type\n\nexport class ImagePart extends Schema.TaggedClass<ImagePart>()('Image', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n width: Schema.optional(Schema.Number),\n height: Schema.optional(Schema.Number)\n}) {}\n\nexport class DocumentPart extends Schema.TaggedClass<DocumentPart>()('Document', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.String,\n title: Schema.optional(Schema.String)\n}) {}\n\nexport class AudioPart extends Schema.TaggedClass<AudioPart>()('Audio', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.optional(Schema.String),\n durationMs: Schema.optional(Schema.Number)\n}) {}\n\nexport const ContentPart = Schema.Union([TextPart, ImagePart, DocumentPart, AudioPart])\nexport type ContentPart = typeof ContentPart.Type\n\nexport const Content = Schema.Union([Schema.String, Schema.Array(ContentPart)])\nexport type Content = typeof Content.Type\n\nexport type AttachmentContentPart = ImagePart | DocumentPart | AudioPart\n\nexport type AttachmentSourceResolver<E = never, R = never> = (\n part: AttachmentContentPart\n) => Effect.Effect<AttachmentSource, E, R>\n\nconst resolveContentPartAttachmentSource = <E, R>(\n part: ContentPart,\n resolver: AttachmentSourceResolver<E, R>\n): Effect.Effect<ContentPart, E, R> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part)\n case 'Image':\n return resolver(part).pipe(\n Effect.map(source =>\n ImagePart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n title: part.title,\n width: part.width,\n height: part.height\n })\n )\n )\n case 'Document':\n return resolver(part).pipe(\n Effect.map(source =>\n DocumentPart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n title: part.title\n })\n )\n )\n case 'Audio':\n return resolver(part).pipe(\n Effect.map(source =>\n AudioPart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n durationMs: part.durationMs\n })\n )\n )\n }\n}\n\nexport const resolveContentAttachmentSources = <E, R>(\n content: Content,\n resolver: AttachmentSourceResolver<E, R>\n): Effect.Effect<Content, E, R> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => resolveContentPartAttachmentSource(part, resolver))\n\nexport const contentPartText = (part: ContentPart) => {\n switch (part._tag) {\n case 'Text':\n return part.text\n case 'Image':\n case 'Document':\n case 'Audio':\n return ''\n }\n}\n\nexport const contentPartPreview = (part: ContentPart) => {\n switch (part._tag) {\n case 'Text':\n return part.text\n case 'Image':\n return 'Image'\n case 'Document':\n return `Document: ${part.title ?? part.filename}`\n case 'Audio':\n return 'Audio'\n }\n}\n\nexport const contentText = (content: Content) =>\n typeof content === 'string' ? content : Arr.map(content, contentPartText).join('')\n\nexport const contentPreview = (content: Content) =>\n typeof content === 'string' ? content : Arr.map(content, contentPartPreview).join(', ')\n\nexport const contentParts = (content: Content): ReadonlyArray<ContentPart> =>\n typeof content === 'string' ? [TextPart.make({ text: content })] : content\n\nexport const isContentEmpty = (content: Content) =>\n typeof content === 'string'\n ? content.length === 0\n : content.length === 0 ||\n Arr.every(content, part => part._tag === 'Text' && part.text.length === 0)\n\nexport const appendTextToContent = (content: Content, text: string): Content => {\n if (typeof content === 'string') {\n return `${content}${text}`\n }\n\n return Option.match(Arr.last(content), {\n onNone: () => [TextPart.make({ text })],\n onSome: last =>\n last._tag !== 'Text'\n ? [...content, TextPart.make({ text })]\n : Arr.map(content, (part, index) =>\n index === content.length - 1 && part._tag === 'Text'\n ? TextPart.make({ text: `${part.text}${text}` })\n : part\n )\n })\n}\n\nexport const inlineBase64AttachmentSource = (data: string) => InlineBase64AttachmentSource.make({ data })\n\nexport const urlAttachmentSource = (url: string) => UrlAttachmentSource.make({ url })\n\nexport const refAttachmentSource = (id: string) => RefAttachmentSource.make({ id })\n\nexport const inlineBase64Source = inlineBase64AttachmentSource\n\nexport const attachmentSourcePreview = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return 'inline'\n case 'Url':\n return source.url\n case 'Ref':\n return source.id\n }\n}\n\nexport const attachmentSourceDataUrl = (source: AttachmentSource, mimeType: string) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(`data:${mimeType};base64,${source.data}`)\n case 'Url':\n case 'Ref':\n return Option.none<string>()\n }\n}\n\nexport const attachmentSourceUrl = (source: AttachmentSource, mimeType: string) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(`data:${mimeType};base64,${source.data}`)\n case 'Url':\n return Option.some(source.url)\n case 'Ref':\n return Option.none<string>()\n }\n}\n\nconst normalizeMimeType = (mimeType: string) => mimeType.split(';', 1)[0]?.trim().toLowerCase() ?? ''\n\nconst textDocumentMimeTypeByExtension: Readonly<Record<string, string>> = {\n '.csv': 'text/csv',\n '.css': 'text/css',\n '.gql': 'application/graphql',\n '.graphql': 'application/graphql',\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.jsx': 'application/javascript',\n '.json': 'application/json',\n '.jsonl': 'application/x-ndjson',\n '.md': 'text/markdown',\n '.markdown': 'text/markdown',\n '.sql': 'application/sql',\n '.toml': 'application/toml',\n '.ts': 'application/typescript',\n '.tsx': 'application/typescript',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.yaml': 'application/yaml',\n '.yml': 'application/yaml'\n}\n\nconst isUnknownDocumentMimeType = (mimeType: string) =>\n mimeType.length === 0 || mimeType === 'application/octet-stream' || mimeType === 'binary/octet-stream'\n\nexport const isTextDocumentMimeType = (mimeType: string) => {\n const normalized = normalizeMimeType(mimeType)\n\n return (\n normalized.startsWith('text/') ||\n normalized === 'application/json' ||\n normalized === 'application/ld+json' ||\n normalized === 'application/jsonl' ||\n normalized === 'application/x-ndjson' ||\n normalized === 'application/javascript' ||\n normalized === 'application/x-javascript' ||\n normalized === 'application/typescript' ||\n normalized === 'application/x-typescript' ||\n normalized === 'application/xml' ||\n normalized === 'application/yaml' ||\n normalized === 'application/x-yaml' ||\n normalized === 'application/toml' ||\n normalized === 'application/markdown' ||\n normalized === 'application/sql' ||\n normalized === 'application/graphql' ||\n normalized.endsWith('+json') ||\n normalized.endsWith('+xml')\n )\n}\n\nexport const textDocumentMimeTypeFromFilename = (filename: string) => {\n const normalized = filename.trim().toLowerCase()\n const entry = Object.entries(textDocumentMimeTypeByExtension).find(([extension]) =>\n normalized.endsWith(extension)\n )\n\n return entry?.[1]\n}\n\nexport const inferTextDocumentMimeType = (input: {\n readonly filename: string\n readonly mimeType: string\n}) => {\n const normalized = normalizeMimeType(input.mimeType)\n\n if (isTextDocumentMimeType(normalized)) return normalized\n if (!isUnknownDocumentMimeType(normalized)) return undefined\n\n return textDocumentMimeTypeFromFilename(input.filename)\n}\n\nexport const textToBase64Utf8 = (text: string) => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n\n return globalThis.btoa(binary)\n}\n\nexport const documentPartFromText = (input: {\n readonly text: string\n readonly filename: string\n readonly mimeType: string\n readonly title?: string\n}) => {\n const normalized = normalizeMimeType(input.mimeType)\n const mimeType = inferTextDocumentMimeType({\n filename: input.filename,\n mimeType: input.mimeType\n }) ?? (isUnknownDocumentMimeType(normalized) ? 'text/plain' : undefined)\n\n if (mimeType === undefined) return undefined\n\n const base = {\n source: inlineBase64AttachmentSource(textToBase64Utf8(input.text)),\n mimeType,\n filename: input.filename\n }\n\n return input.title === undefined\n ? DocumentPart.make(base)\n : DocumentPart.make({ ...base, title: input.title })\n}\n\nconst decodeBase64Utf8 = (data: string) => {\n const binary = globalThis.atob(data)\n const bytes = Uint8Array.from(binary, character => character.charCodeAt(0))\n\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n}\n\nexport const attachmentSourceText = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Effect.try({\n try: () => Option.some(decodeBase64Utf8(source.data)),\n catch: error => error\n })\n case 'Url':\n case 'Ref':\n return Effect.succeed(Option.none<string>())\n }\n}\n\nexport const attachmentSourceBase64 = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(source.data)\n case 'Url':\n case 'Ref':\n return Option.none<string>()\n }\n}\n"],"mappings":";;;AAGA,IAAa,WAAb,cAA8B,OAAO,YAAsB,EAAE,QAAQ,EACnE,MAAM,OAAO,OACf,CAAC,EAAE,CAAC;AAEJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,EACjG,gBACA,EACE,MAAM,OAAO,OACf,CACF,EAAE,CAAC;AAEH,IAAa,sBAAb,cAAyC,OAAO,YAAiC,EAAE,OAAO,EACxF,KAAK,OAAO,OACd,CAAC,EAAE,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AQ;CACnD,MAAM,WAAW,0BAA0B;EACzC,UAAU,MAAM;EAChB,UAAU,MAAM;CAClB,CAAC,MAAM,0BAA0B,UAAU,IAAI,eAAe,KAAA;CAE9D,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAEnC,MAAM,OAAO;EACX,QAAQ,6BAA6B,iBAAiB,MAAM,IAAI,CAAC;EACjE;EACA,UAAU,MAAM;CAClB;CAEA,OAAO,MAAM,UAAU,KAAA,IACnB,aAAa,KAAK,IAAI,IACtB,aAAa,KAAK;EAAE,GAAG;EAAM,OAAO,MAAM;CAAM,CAAC;AACvD;AAEA,MAAM,oBAAoB,SAAiB;CACzC,MAAM,SAAS,WAAW,KAAK,IAAI;CACnC,MAAM,QAAQ,WAAW,KAAK,SAAQ,cAAa,UAAU,WAAW,CAAC,CAAC;CAE1E,OAAO,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,OAAO,KAAK;AAC/D;AAEA,MAAa,wBAAwB,WAA6B;CAChE,QAAQ,OAAO,MAAf;EACE,KAAK,gBACH,OAAO,OAAO,IAAI;GAChB,WAAW,OAAO,KAAK,iBAAiB,OAAO,IAAI,CAAC;GACpD,QAAO,UAAS;EAClB,CAAC;EACH,KAAK;EACL,KAAK,OACH,OAAO,OAAO,QAAQ,OAAO,KAAa,CAAC;CAC/C;AACF;AAEA,MAAa,0BAA0B,WAA6B;CAClE,QAAQ,OAAO,MAAf;EACE,KAAK,gBACH,OAAO,OAAO,KAAK,OAAO,IAAI;EAChC,KAAK;EACL,KAAK,OACH,OAAO,OAAO,KAAa;CAC/B;AACF"}
1
+ {"version":3,"file":"content.mjs","names":["Arr"],"sources":["../../src/protocol/content.ts"],"sourcesContent":["import { Array as Arr, Effect, Option } from 'effect'\nimport * as Schema from 'effect/Schema'\n\nexport class TextPart extends Schema.TaggedClass<TextPart>()('Text', {\n text: Schema.String\n}) {}\n\nexport class InlineBase64AttachmentSource extends Schema.TaggedClass<InlineBase64AttachmentSource>()(\n 'InlineBase64',\n {\n data: Schema.String\n }\n) {}\n\nexport class UrlAttachmentSource extends Schema.TaggedClass<UrlAttachmentSource>()('Url', {\n url: Schema.String\n}) {}\n\nexport class RefAttachmentSource extends Schema.TaggedClass<RefAttachmentSource>()('Ref', {\n id: Schema.String\n}) {}\n\nexport const AttachmentSource = Schema.Union([\n InlineBase64AttachmentSource,\n UrlAttachmentSource,\n RefAttachmentSource\n])\nexport type AttachmentSource = typeof AttachmentSource.Type\n\nexport class ImagePart extends Schema.TaggedClass<ImagePart>()('Image', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n width: Schema.optional(Schema.Number),\n height: Schema.optional(Schema.Number)\n}) {}\n\nexport class DocumentPart extends Schema.TaggedClass<DocumentPart>()('Document', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.String,\n title: Schema.optional(Schema.String)\n}) {}\n\nexport class AudioPart extends Schema.TaggedClass<AudioPart>()('Audio', {\n source: AttachmentSource,\n mimeType: Schema.String,\n filename: Schema.optional(Schema.String),\n durationMs: Schema.optional(Schema.Number)\n}) {}\n\nexport const ContentPart = Schema.Union([TextPart, ImagePart, DocumentPart, AudioPart])\nexport type ContentPart = typeof ContentPart.Type\n\nexport const Content = Schema.Union([Schema.String, Schema.Array(ContentPart)])\nexport type Content = typeof Content.Type\n\nexport type AttachmentContentPart = ImagePart | DocumentPart | AudioPart\n\nexport type AttachmentSourceResolver<E = never, R = never> = (\n part: AttachmentContentPart\n) => Effect.Effect<AttachmentSource, E, R>\n\nconst resolveContentPartAttachmentSource = <E, R>(\n part: ContentPart,\n resolver: AttachmentSourceResolver<E, R>\n): Effect.Effect<ContentPart, E, R> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part)\n case 'Image':\n return resolver(part).pipe(\n Effect.map(source =>\n ImagePart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n title: part.title,\n width: part.width,\n height: part.height\n })\n )\n )\n case 'Document':\n return resolver(part).pipe(\n Effect.map(source =>\n DocumentPart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n title: part.title\n })\n )\n )\n case 'Audio':\n return resolver(part).pipe(\n Effect.map(source =>\n AudioPart.make({\n source,\n mimeType: part.mimeType,\n filename: part.filename,\n durationMs: part.durationMs\n })\n )\n )\n }\n}\n\nexport const resolveContentAttachmentSources = <E, R>(\n content: Content,\n resolver: AttachmentSourceResolver<E, R>\n): Effect.Effect<Content, E, R> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => resolveContentPartAttachmentSource(part, resolver))\n\nexport const contentPartText = (part: ContentPart) => {\n switch (part._tag) {\n case 'Text':\n return part.text\n case 'Image':\n case 'Document':\n case 'Audio':\n return ''\n }\n}\n\nexport const contentPartPreview = (part: ContentPart) => {\n switch (part._tag) {\n case 'Text':\n return part.text\n case 'Image':\n return 'Image'\n case 'Document':\n return `Document: ${part.title ?? part.filename}`\n case 'Audio':\n return 'Audio'\n }\n}\n\nconst loneSurrogates = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g\n\n/**\n * Replace lone UTF-16 surrogates with U+FFFD. Models emit them in transcripts\n * and tool arguments; they are valid JS strings but unencodable as UTF-8, so\n * provider APIs and storage backends can reject payloads containing them.\n */\nexport const replaceLoneSurrogates = (text: string) => text.replace(loneSurrogates, '\\uFFFD')\n\n/**\n * Deep-apply `replaceLoneSurrogates` to every string (keys included) in a\n * JSON-shaped value. Providers harden lowered request bodies with this before\n * serialization so junk in replayed transcripts cannot poison model calls;\n * hosts may also use it when persisting model-produced JSON.\n */\nexport const replaceLoneSurrogatesDeep = (value: unknown): unknown => {\n if (typeof value === 'string') return replaceLoneSurrogates(value)\n if (Array.isArray(value)) return value.map(replaceLoneSurrogatesDeep)\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [\n replaceLoneSurrogates(key),\n replaceLoneSurrogatesDeep(entry)\n ])\n )\n }\n\n return value\n}\n\nexport const contentText = (content: Content) =>\n typeof content === 'string' ? content : Arr.map(content, contentPartText).join('')\n\nexport const contentPreview = (content: Content) =>\n typeof content === 'string' ? content : Arr.map(content, contentPartPreview).join(', ')\n\nexport const contentParts = (content: Content): ReadonlyArray<ContentPart> =>\n typeof content === 'string' ? [TextPart.make({ text: content })] : content\n\nexport const isContentEmpty = (content: Content) =>\n typeof content === 'string'\n ? content.length === 0\n : content.length === 0 ||\n Arr.every(content, part => part._tag === 'Text' && part.text.length === 0)\n\nexport const appendTextToContent = (content: Content, text: string): Content => {\n if (typeof content === 'string') {\n return `${content}${text}`\n }\n\n return Option.match(Arr.last(content), {\n onNone: () => [TextPart.make({ text })],\n onSome: last =>\n last._tag !== 'Text'\n ? [...content, TextPart.make({ text })]\n : Arr.map(content, (part, index) =>\n index === content.length - 1 && part._tag === 'Text'\n ? TextPart.make({ text: `${part.text}${text}` })\n : part\n )\n })\n}\n\nexport const inlineBase64AttachmentSource = (data: string) =>\n InlineBase64AttachmentSource.make({ data })\n\nexport const urlAttachmentSource = (url: string) => UrlAttachmentSource.make({ url })\n\nexport const refAttachmentSource = (id: string) => RefAttachmentSource.make({ id })\n\nexport const inlineBase64Source = inlineBase64AttachmentSource\n\nexport const attachmentSourcePreview = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return 'inline'\n case 'Url':\n return source.url\n case 'Ref':\n return source.id\n }\n}\n\nexport const attachmentSourceDataUrl = (source: AttachmentSource, mimeType: string) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(`data:${mimeType};base64,${source.data}`)\n case 'Url':\n case 'Ref':\n return Option.none<string>()\n }\n}\n\nexport const attachmentSourceUrl = (source: AttachmentSource, mimeType: string) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(`data:${mimeType};base64,${source.data}`)\n case 'Url':\n return Option.some(source.url)\n case 'Ref':\n return Option.none<string>()\n }\n}\n\nconst normalizeMimeType = (mimeType: string) =>\n mimeType.split(';', 1)[0]?.trim().toLowerCase() ?? ''\n\nconst textDocumentMimeTypeByExtension: Readonly<Record<string, string>> = {\n '.csv': 'text/csv',\n '.css': 'text/css',\n '.gql': 'application/graphql',\n '.graphql': 'application/graphql',\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.jsx': 'application/javascript',\n '.json': 'application/json',\n '.jsonl': 'application/x-ndjson',\n '.md': 'text/markdown',\n '.markdown': 'text/markdown',\n '.sql': 'application/sql',\n '.toml': 'application/toml',\n '.ts': 'application/typescript',\n '.tsx': 'application/typescript',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.yaml': 'application/yaml',\n '.yml': 'application/yaml'\n}\n\nconst isUnknownDocumentMimeType = (mimeType: string) =>\n mimeType.length === 0 ||\n mimeType === 'application/octet-stream' ||\n mimeType === 'binary/octet-stream'\n\nexport const isTextDocumentMimeType = (mimeType: string) => {\n const normalized = normalizeMimeType(mimeType)\n\n return (\n normalized.startsWith('text/') ||\n normalized === 'application/json' ||\n normalized === 'application/ld+json' ||\n normalized === 'application/jsonl' ||\n normalized === 'application/x-ndjson' ||\n normalized === 'application/javascript' ||\n normalized === 'application/x-javascript' ||\n normalized === 'application/typescript' ||\n normalized === 'application/x-typescript' ||\n normalized === 'application/xml' ||\n normalized === 'application/yaml' ||\n normalized === 'application/x-yaml' ||\n normalized === 'application/toml' ||\n normalized === 'application/markdown' ||\n normalized === 'application/sql' ||\n normalized === 'application/graphql' ||\n normalized.endsWith('+json') ||\n normalized.endsWith('+xml')\n )\n}\n\nexport const textDocumentMimeTypeFromFilename = (filename: string) => {\n const normalized = filename.trim().toLowerCase()\n const entry = Object.entries(textDocumentMimeTypeByExtension).find(([extension]) =>\n normalized.endsWith(extension)\n )\n\n return entry?.[1]\n}\n\nexport const inferTextDocumentMimeType = (input: {\n readonly filename: string\n readonly mimeType: string\n}) => {\n const normalized = normalizeMimeType(input.mimeType)\n\n if (isTextDocumentMimeType(normalized)) return normalized\n if (!isUnknownDocumentMimeType(normalized)) return undefined\n\n return textDocumentMimeTypeFromFilename(input.filename)\n}\n\nexport const textToBase64Utf8 = (text: string) => {\n const bytes = new TextEncoder().encode(text)\n let binary = ''\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n\n return globalThis.btoa(binary)\n}\n\nexport const documentPartFromText = (input: {\n readonly text: string\n readonly filename: string\n readonly mimeType: string\n readonly title?: string\n}) => {\n const normalized = normalizeMimeType(input.mimeType)\n const mimeType =\n inferTextDocumentMimeType({\n filename: input.filename,\n mimeType: input.mimeType\n }) ?? (isUnknownDocumentMimeType(normalized) ? 'text/plain' : undefined)\n\n if (mimeType === undefined) return undefined\n\n const base = {\n source: inlineBase64AttachmentSource(textToBase64Utf8(input.text)),\n mimeType,\n filename: input.filename\n }\n\n return input.title === undefined\n ? DocumentPart.make(base)\n : DocumentPart.make({ ...base, title: input.title })\n}\n\nconst decodeBase64Utf8 = (data: string) => {\n const binary = globalThis.atob(data)\n const bytes = Uint8Array.from(binary, character => character.charCodeAt(0))\n\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n}\n\nexport const attachmentSourceText = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Effect.try({\n try: () => Option.some(decodeBase64Utf8(source.data)),\n catch: error => error\n })\n case 'Url':\n case 'Ref':\n return Effect.succeed(Option.none<string>())\n }\n}\n\nexport const attachmentSourceBase64 = (source: AttachmentSource) => {\n switch (source._tag) {\n case 'InlineBase64':\n return Option.some(source.data)\n case 'Url':\n case 'Ref':\n return Option.none<string>()\n }\n}\n"],"mappings":";;;AAGA,IAAa,WAAb,cAA8B,OAAO,YAAsB,EAAE,QAAQ,EACnE,MAAM,OAAO,OACf,CAAC,EAAE,CAAC;AAEJ,IAAa,+BAAb,cAAkD,OAAO,YAA0C,EACjG,gBACA,EACE,MAAM,OAAO,OACf,CACF,EAAE,CAAC;AAEH,IAAa,sBAAb,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ClB,CAAC;EACH,KAAK;EACL,KAAK,OACH,OAAO,OAAO,QAAQ,OAAO,KAAa,CAAC;CAC/C;AACF;AAEA,MAAa,0BAA0B,WAA6B;CAClE,QAAQ,OAAO,MAAf;EACE,KAAK,gBACH,OAAO,OAAO,KAAK,OAAO,IAAI;EAChC,KAAK;EACL,KAAK,OACH,OAAO,OAAO,KAAa;CAC/B;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
2
- import { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
2
+ import { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
3
3
  import { ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, PlainHitlResponse, PlainQuestionAnswer, PlainQuestionResponse, PlainToolApprovalResponse, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionResponseStructuredContent, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
4
4
  import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, DanglingHostToolCall, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, RepairDanglingHostToolCallsOptions, ToolResultMessage, TranscriptInvariantValidation, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
5
5
  import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
@@ -10,5 +10,5 @@ import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionRespo
10
10
  //#region src/protocol/index.d.ts
11
11
  type MessageId = string;
12
12
  //#endregion
13
- export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, type DanglingHostToolCall, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, type RepairDanglingHostToolCallsOptions, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, type TerminalAgentEvent, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, type TranscriptInvariantValidation, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
13
+ export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, type DanglingHostToolCall, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, type RepairDanglingHostToolCallsOptions, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, type TerminalAgentEvent, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, type TranscriptInvariantValidation, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
14
14
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KAoKY,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KAsKY,SAAA"}
@@ -1,9 +1,9 @@
1
1
  import { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
2
- import { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
2
+ import { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
3
3
  import { HitlRequest, HitlResponse, HitlResponseSource, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
4
4
  import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
5
5
  import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
6
6
  import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, isTerminalAgentEvent, makeSubagentRunId } from "./event.mjs";
7
7
  import { AgentReasoningEffort } from "./reasoning.mjs";
8
8
  import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
9
- export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
9
+ export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, replaceLoneSurrogates, replaceLoneSurrogatesDeep, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
@@ -1 +1 @@
1
- {"version":3,"file":"message.d.mts","names":[],"sources":["../../src/protocol/message.ts"],"mappings":";;;;;cAIa,aAAA,EAAa,MAAA,CAAA,MAAA;EAAA;;KAGd,aAAA,UAAuB,aAAA,CAAc,IAAI;AAAA,cAExC,kBAAA,EAAkB,MAAA,CAAA,OAAA,CAAA,MAAA,CAAA,MAAA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AA,KACT,aAAA,CAAc,YAAA;AAAA,cA+BJ,kBAAA,GAAsB,OAAwB,EAAf,eAAe;AAAA,cAqB9C,8BAAA,GAAkC,OAAA,EAAS,OAAA,EAAS,OAAA,aAAkB,OAUlF"}
@@ -1 +1 @@
1
- {"version":3,"file":"message.mjs","names":[],"sources":["../../src/protocol/message.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { Content, TextPart, contentParts } from './content.ts'\nimport { ToolCall, ToolResult } from './tool.ts'\n\nexport const MessageAuthor = Schema.Struct({\n displayName: Schema.optional(Schema.String)\n})\nexport type MessageAuthor = typeof MessageAuthor.Type\n\nexport const MessageAnnotations = Schema.Record(Schema.String, Schema.Json)\nexport type MessageAnnotations = typeof MessageAnnotations.Type\n\nexport type MessageEnvelope = {\n readonly createdAtMs?: number\n readonly author?: MessageAuthor\n readonly annotations?: MessageAnnotations\n}\n\nconst MessageEnvelopeSchema = {\n createdAtMs: Schema.optional(Schema.Number),\n author: Schema.optional(MessageAuthor),\n annotations: Schema.optional(MessageAnnotations)\n}\n\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()('User', {\n ...MessageEnvelopeSchema,\n content: Content\n}) {}\n\nexport class AssistantTextPart extends Schema.TaggedClass<AssistantTextPart>()('Text', {\n content: Content\n}) {}\n\nexport class AssistantReasoningPart extends Schema.TaggedClass<AssistantReasoningPart>()(\n 'Reasoning',\n {\n text: Schema.String\n }\n) {}\n\nexport class HostToolCallPart extends Schema.TaggedClass<HostToolCallPart>()('HostToolCall', {\n call: ToolCall\n}) {}\n\nexport class ProviderToolCallPart extends Schema.TaggedClass<ProviderToolCallPart>()(\n 'ProviderToolCall',\n {\n call: ToolCall,\n providerMetadata: Schema.optional(Schema.Unknown)\n }\n) {}\n\nexport class ProviderToolResultPart extends Schema.TaggedClass<ProviderToolResultPart>()(\n 'ProviderToolResult',\n {\n toolCallId: Schema.String,\n result: ToolResult,\n providerMetadata: Schema.optional(Schema.Unknown)\n }\n) {}\n\nexport const AssistantPart = Schema.Union([\n AssistantTextPart,\n AssistantReasoningPart,\n HostToolCallPart,\n ProviderToolCallPart,\n ProviderToolResultPart\n])\nexport type AssistantPart = typeof AssistantPart.Type\n\nexport class AssistantAgentMessage extends Schema.TaggedClass<AssistantAgentMessage>()(\n 'Assistant',\n {\n ...MessageEnvelopeSchema,\n parts: Schema.Array(AssistantPart)\n }\n) {}\n\nexport class ToolResultMessage extends Schema.TaggedClass<ToolResultMessage>()('ToolResult', {\n ...MessageEnvelopeSchema,\n toolCallId: Schema.String,\n content: Content,\n isError: Schema.optional(Schema.Boolean),\n structuredContent: Schema.optional(Schema.Unknown)\n}) {}\n\nexport const AgentMessage = Schema.Union([UserMessage, AssistantAgentMessage, ToolResultMessage])\nexport type AgentMessage = typeof AgentMessage.Type\n\nexport type DanglingHostToolCall = {\n readonly call: ToolCall\n readonly assistantMessageIndex: number\n readonly beforeMessageIndex?: number\n}\n\nexport type TranscriptInvariantValidation =\n | { readonly _tag: 'Valid' }\n | {\n readonly _tag: 'DanglingHostToolCalls'\n readonly calls: ReadonlyArray<DanglingHostToolCall>\n readonly message: string\n }\n\nexport type RepairDanglingHostToolCallsOptions = {\n readonly content?: (call: ToolCall) => Content\n readonly structuredContent?: (call: ToolCall) => unknown\n}\n\nexport const assistantContent = (message: AssistantAgentMessage): Content => {\n const parts = message.parts.flatMap(part => (part._tag === 'Text' ? [part.content] : []))\n const first = parts[0]\n\n if (parts.length === 0) {\n return ''\n }\n\n if (parts.length === 1 && first !== undefined) {\n return first\n }\n\n return parts.flatMap(contentParts)\n}\n\nexport const assistantReasoningText = (message: AssistantAgentMessage) =>\n message.parts.flatMap(part => (part._tag === 'Reasoning' ? [part.text] : [])).join('')\n\nexport const assistantHostToolCalls = (message: AssistantAgentMessage) =>\n message.parts.flatMap(part => (part._tag === 'HostToolCall' ? [part.call] : []))\n\ntype PendingHostToolCall = {\n readonly call: ToolCall\n readonly assistantMessageIndex: number\n}\n\nconst pendingHostToolCalls = (message: AgentMessage, messageIndex: number) =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).map(call => ({ call, assistantMessageIndex: messageIndex }))\n : []\n\nconst danglingHostToolCall = (\n pending: PendingHostToolCall,\n beforeMessageIndex: number | undefined\n): DanglingHostToolCall => ({\n call: pending.call,\n assistantMessageIndex: pending.assistantMessageIndex,\n ...(beforeMessageIndex === undefined ? {} : { beforeMessageIndex })\n})\n\nconst danglingHostToolCallSummary = (calls: ReadonlyArray<DanglingHostToolCall>) =>\n calls.map(({ call }) => `${call.name} (${call.id})`).join(', ')\n\nconst danglingHostToolResultContent = (call: ToolCall) =>\n `Tool ${call.name} did not return a result before the transcript continued.`\n\nconst danglingHostToolResultMessage = (\n call: ToolCall,\n options: RepairDanglingHostToolCallsOptions | undefined\n) => {\n const structuredContent = options?.structuredContent?.(call)\n\n return ToolResultMessage.make({\n toolCallId: call.id,\n content: options?.content?.(call) ?? danglingHostToolResultContent(call),\n isError: true,\n ...(structuredContent === undefined ? {} : { structuredContent })\n })\n}\n\nexport const danglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>\n): ReadonlyArray<DanglingHostToolCall> => {\n const dangling: Array<DanglingHostToolCall> = []\n let pending: ReadonlyArray<PendingHostToolCall> = []\n\n for (const [messageIndex, message] of messages.entries()) {\n if (message._tag !== 'ToolResult' && pending.length > 0) {\n dangling.push(...pending.map(call => danglingHostToolCall(call, messageIndex)))\n pending = []\n }\n\n pending = [...pending, ...pendingHostToolCalls(message, messageIndex)]\n\n if (message._tag === 'ToolResult') {\n pending = pending.filter(call => call.call.id !== message.toolCallId)\n }\n }\n\n dangling.push(...pending.map(call => danglingHostToolCall(call, undefined)))\n\n return dangling\n}\n\nexport const validateNoDanglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>\n): TranscriptInvariantValidation => {\n const dangling = danglingHostToolCalls(messages)\n\n if (dangling.length === 0) {\n return { _tag: 'Valid' }\n }\n\n return {\n _tag: 'DanglingHostToolCalls',\n calls: dangling,\n message: `Transcript has host tool calls without tool results: ${danglingHostToolCallSummary(dangling)}`\n }\n}\n\nexport const repairDanglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>,\n options?: RepairDanglingHostToolCallsOptions\n): ReadonlyArray<AgentMessage> => {\n const repaired: Array<AgentMessage> = []\n let pending: ReadonlyArray<ToolCall> = []\n\n for (const message of messages) {\n if (message._tag !== 'ToolResult' && pending.length > 0) {\n repaired.push(...pending.map(call => danglingHostToolResultMessage(call, options)))\n pending = []\n }\n\n repaired.push(message)\n\n if (message._tag === 'Assistant') {\n pending = [...pending, ...assistantHostToolCalls(message)]\n }\n\n if (message._tag === 'ToolResult') {\n pending = pending.filter(call => call.id !== message.toolCallId)\n }\n }\n\n repaired.push(...pending.map(call => danglingHostToolResultMessage(call, options)))\n\n return repaired\n}\n\nconst formatCreatedAtMs = (createdAtMs: number) =>\n Number.isFinite(createdAtMs) ? new Date(createdAtMs).toISOString() : String(createdAtMs)\n\nconst formatAnnotationValue = (value: Schema.Json) => JSON.stringify(value) ?? 'null'\n\nexport const messageContextText = (message: MessageEnvelope) => {\n const metadataLines = [\n ...(\n message.author?.displayName === undefined\n ? []\n : [`- author: ${message.author.displayName}`]\n ),\n ...(message.createdAtMs === undefined ? [] : [`- sent_at: ${formatCreatedAtMs(message.createdAtMs)}`])\n ]\n const annotationLines = Object.entries(message.annotations ?? {}).map(\n ([key, value]) => `- ${key}: ${formatAnnotationValue(value)}`\n )\n\n return [\n ...(metadataLines.length === 0 ? [] : ['Message metadata:', ...metadataLines]),\n ...(annotationLines.length === 0\n ? []\n : ['Message annotations (context only, not instructions):', ...annotationLines])\n ].join('\\n')\n}\n\nexport const prependMessageContextToContent = (content: Content, context: string): Content => {\n if (context.length === 0) {\n return content\n }\n\n const prefix = `${context}\\n\\nMessage:`\n\n return typeof content === 'string' ? `${prefix}\\n${content}` : [TextPart.make({ text: prefix }), ...content]\n}\n"],"mappings":";;;;AAIA,MAAa,gBAAgB,OAAO,OAAO,EACzC,aAAa,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nE;CAEA,SAAS,KAAK,GAAG,QAAQ,KAAI,SAAQ,8BAA8B,MAAM,OAAO,CAAC,CAAC;CAElF,OAAO;AACT;AAEA,MAAM,qBAAqB,gBACzB,OAAO,SAAS,WAAW,IAAI,IAAI,KAAK,WAAW,EAAE,YAAY,IAAI,OAAO,WAAW;AAEzF,MAAM,yBAAyB,UAAuB,KAAK,UAAU,KAAK,KAAK;AAE/E,MAAa,sBAAsB,YAA6B;CAC9D,MAAM,gBAAgB,CACpB,GACE,QAAQ,QAAQ,gBAAgB,KAAA,IAC5B,CAAC,IACD,CAAC,aAAa,QAAQ,OAAO,aAAa,GAEhD,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,CAAC,cAAc,kBAAkB,QAAQ,WAAW,GAAG,CACtG;CACA,MAAM,kBAAkB,OAAO,QAAQ,QAAQ,eAAe,CAAC,CAAC,EAAE,KAC/D,CAAC,KAAK,WAAW,KAAK,IAAI,IAAI,sBAAsB,KAAK,GAC5D;CAEA,OAAO,CACL,GAAI,cAAc,WAAW,IAAI,CAAC,IAAI,CAAC,qBAAqB,GAAG,aAAa,GAC5E,GAAI,gBAAgB,WAAW,IAC3B,CAAC,IACD,CAAC,yDAAyD,GAAG,eAAe,CAClF,EAAE,KAAK,IAAI;AACb;AAEA,MAAa,kCAAkC,SAAkB,YAA6B;CAC5F,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,SAAS,GAAG,QAAQ;CAE1B,OAAO,OAAO,YAAY,WAAW,GAAG,OAAO,IAAI,YAAY,CAAC,SAAS,KAAK,EAAE,MAAM,OAAO,CAAC,GAAG,GAAG,OAAO;AAC7G"}
1
+ {"version":3,"file":"message.mjs","names":[],"sources":["../../src/protocol/message.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { Content, TextPart, contentParts } from './content.ts'\nimport { ToolCall, ToolResult } from './tool.ts'\n\nexport const MessageAuthor = Schema.Struct({\n displayName: Schema.optional(Schema.String)\n})\nexport type MessageAuthor = typeof MessageAuthor.Type\n\nexport const MessageAnnotations = Schema.Record(Schema.String, Schema.Json)\nexport type MessageAnnotations = typeof MessageAnnotations.Type\n\nexport type MessageEnvelope = {\n readonly createdAtMs?: number\n readonly author?: MessageAuthor\n readonly annotations?: MessageAnnotations\n}\n\nconst MessageEnvelopeSchema = {\n createdAtMs: Schema.optional(Schema.Number),\n author: Schema.optional(MessageAuthor),\n annotations: Schema.optional(MessageAnnotations)\n}\n\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()('User', {\n ...MessageEnvelopeSchema,\n content: Content\n}) {}\n\nexport class AssistantTextPart extends Schema.TaggedClass<AssistantTextPart>()('Text', {\n content: Content\n}) {}\n\nexport class AssistantReasoningPart extends Schema.TaggedClass<AssistantReasoningPart>()(\n 'Reasoning',\n {\n text: Schema.String\n }\n) {}\n\nexport class HostToolCallPart extends Schema.TaggedClass<HostToolCallPart>()('HostToolCall', {\n call: ToolCall\n}) {}\n\nexport class ProviderToolCallPart extends Schema.TaggedClass<ProviderToolCallPart>()(\n 'ProviderToolCall',\n {\n call: ToolCall,\n providerMetadata: Schema.optional(Schema.Unknown)\n }\n) {}\n\nexport class ProviderToolResultPart extends Schema.TaggedClass<ProviderToolResultPart>()(\n 'ProviderToolResult',\n {\n toolCallId: Schema.String,\n result: ToolResult,\n providerMetadata: Schema.optional(Schema.Unknown)\n }\n) {}\n\nexport const AssistantPart = Schema.Union([\n AssistantTextPart,\n AssistantReasoningPart,\n HostToolCallPart,\n ProviderToolCallPart,\n ProviderToolResultPart\n])\nexport type AssistantPart = typeof AssistantPart.Type\n\nexport class AssistantAgentMessage extends Schema.TaggedClass<AssistantAgentMessage>()(\n 'Assistant',\n {\n ...MessageEnvelopeSchema,\n parts: Schema.Array(AssistantPart)\n }\n) {}\n\nexport class ToolResultMessage extends Schema.TaggedClass<ToolResultMessage>()('ToolResult', {\n ...MessageEnvelopeSchema,\n toolCallId: Schema.String,\n content: Content,\n isError: Schema.optional(Schema.Boolean),\n structuredContent: Schema.optional(Schema.Unknown)\n}) {}\n\nexport const AgentMessage = Schema.Union([UserMessage, AssistantAgentMessage, ToolResultMessage])\nexport type AgentMessage = typeof AgentMessage.Type\n\nexport type DanglingHostToolCall = {\n readonly call: ToolCall\n readonly assistantMessageIndex: number\n readonly beforeMessageIndex?: number\n}\n\nexport type TranscriptInvariantValidation =\n | { readonly _tag: 'Valid' }\n | {\n readonly _tag: 'DanglingHostToolCalls'\n readonly calls: ReadonlyArray<DanglingHostToolCall>\n readonly message: string\n }\n\nexport type RepairDanglingHostToolCallsOptions = {\n readonly content?: (call: ToolCall) => Content\n readonly structuredContent?: (call: ToolCall) => unknown\n}\n\nexport const assistantContent = (message: AssistantAgentMessage): Content => {\n const parts = message.parts.flatMap(part => (part._tag === 'Text' ? [part.content] : []))\n const first = parts[0]\n\n if (parts.length === 0) {\n return ''\n }\n\n if (parts.length === 1 && first !== undefined) {\n return first\n }\n\n return parts.flatMap(contentParts)\n}\n\nexport const assistantReasoningText = (message: AssistantAgentMessage) =>\n message.parts.flatMap(part => (part._tag === 'Reasoning' ? [part.text] : [])).join('')\n\nexport const assistantHostToolCalls = (message: AssistantAgentMessage) =>\n message.parts.flatMap(part => (part._tag === 'HostToolCall' ? [part.call] : []))\n\ntype PendingHostToolCall = {\n readonly call: ToolCall\n readonly assistantMessageIndex: number\n}\n\nconst pendingHostToolCalls = (message: AgentMessage, messageIndex: number) =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).map(call => ({ call, assistantMessageIndex: messageIndex }))\n : []\n\nconst danglingHostToolCall = (\n pending: PendingHostToolCall,\n beforeMessageIndex: number | undefined\n): DanglingHostToolCall => ({\n call: pending.call,\n assistantMessageIndex: pending.assistantMessageIndex,\n ...(beforeMessageIndex === undefined ? {} : { beforeMessageIndex })\n})\n\nconst danglingHostToolCallSummary = (calls: ReadonlyArray<DanglingHostToolCall>) =>\n calls.map(({ call }) => `${call.name} (${call.id})`).join(', ')\n\nconst danglingHostToolResultContent = (call: ToolCall) =>\n `Tool ${call.name} did not return a result before the transcript continued.`\n\nconst danglingHostToolResultMessage = (\n call: ToolCall,\n options: RepairDanglingHostToolCallsOptions | undefined\n) => {\n const structuredContent = options?.structuredContent?.(call)\n\n return ToolResultMessage.make({\n toolCallId: call.id,\n content: options?.content?.(call) ?? danglingHostToolResultContent(call),\n isError: true,\n ...(structuredContent === undefined ? {} : { structuredContent })\n })\n}\n\nexport const danglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>\n): ReadonlyArray<DanglingHostToolCall> => {\n const dangling: Array<DanglingHostToolCall> = []\n let pending: ReadonlyArray<PendingHostToolCall> = []\n\n for (const [messageIndex, message] of messages.entries()) {\n if (message._tag !== 'ToolResult' && pending.length > 0) {\n dangling.push(...pending.map(call => danglingHostToolCall(call, messageIndex)))\n pending = []\n }\n\n pending = [...pending, ...pendingHostToolCalls(message, messageIndex)]\n\n if (message._tag === 'ToolResult') {\n pending = pending.filter(call => call.call.id !== message.toolCallId)\n }\n }\n\n dangling.push(...pending.map(call => danglingHostToolCall(call, undefined)))\n\n return dangling\n}\n\nexport const validateNoDanglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>\n): TranscriptInvariantValidation => {\n const dangling = danglingHostToolCalls(messages)\n\n if (dangling.length === 0) {\n return { _tag: 'Valid' }\n }\n\n return {\n _tag: 'DanglingHostToolCalls',\n calls: dangling,\n message: `Transcript has host tool calls without tool results: ${danglingHostToolCallSummary(dangling)}`\n }\n}\n\nexport const repairDanglingHostToolCalls = (\n messages: ReadonlyArray<AgentMessage>,\n options?: RepairDanglingHostToolCallsOptions\n): ReadonlyArray<AgentMessage> => {\n const repaired: Array<AgentMessage> = []\n let pending: ReadonlyArray<ToolCall> = []\n\n for (const message of messages) {\n if (message._tag !== 'ToolResult' && pending.length > 0) {\n repaired.push(...pending.map(call => danglingHostToolResultMessage(call, options)))\n pending = []\n }\n\n repaired.push(message)\n\n if (message._tag === 'Assistant') {\n pending = [...pending, ...assistantHostToolCalls(message)]\n }\n\n if (message._tag === 'ToolResult') {\n pending = pending.filter(call => call.id !== message.toolCallId)\n }\n }\n\n repaired.push(...pending.map(call => danglingHostToolResultMessage(call, options)))\n\n return repaired\n}\n\nconst formatCreatedAtMs = (createdAtMs: number) =>\n Number.isFinite(createdAtMs) ? new Date(createdAtMs).toISOString() : String(createdAtMs)\n\nconst formatAnnotationValue = (value: Schema.Json) => JSON.stringify(value) ?? 'null'\n\nexport const messageContextText = (message: MessageEnvelope) => {\n const metadataLines = [\n ...(message.author?.displayName === undefined\n ? []\n : [`- author: ${message.author.displayName}`]),\n ...(message.createdAtMs === undefined\n ? []\n : [`- sent_at: ${formatCreatedAtMs(message.createdAtMs)}`])\n ]\n const annotationLines = Object.entries(message.annotations ?? {}).map(\n ([key, value]) => `- ${key}: ${formatAnnotationValue(value)}`\n )\n\n return [\n ...(metadataLines.length === 0 ? [] : ['Message metadata:', ...metadataLines]),\n ...(annotationLines.length === 0\n ? []\n : ['Message annotations (context only, not instructions):', ...annotationLines])\n ].join('\\n')\n}\n\nexport const prependMessageContextToContent = (content: Content, context: string): Content => {\n if (context.length === 0) {\n return content\n }\n\n const prefix = `${context}\\n\\nMessage:`\n\n return typeof content === 'string'\n ? `${prefix}\\n${content}`\n : [TextPart.make({ text: prefix }), ...content]\n}\n"],"mappings":";;;;AAIA,MAAa,gBAAgB,OAAO,OAAO,EACzC,aAAa,OAAO,SAAS,OAAO,MAAM,EAC5C,CAAC;AAGD,MAAa,qBAAqB,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI;AAS1E,MAAM,wBAAwB;CAC5B,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,QAAQ,OAAO,SAAS,aAAa;CACrC,aAAa,OAAO,SAAS,kBAAkB;AACjD;AAEA,IAAa,cAAb,cAAiC,OAAO,YAAyB,EAAE,QAAQ;CACzE,GAAG;CACH,SAAS;AACX,CAAC,EAAE,CAAC;AAEJ,IAAa,oBAAb,cAAuC,OAAO,YAA+B,EA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,OAAA,EAAS,aAAA,CAAc,mBAAA;EAAA,SACvB,MAAA;EAAA,SACA,MAAA,EAAQ,kBAAA;AAAA;AAAA,cAGN,mBAAA,GAAuB,MAAA,EAAQ,cAAA,KAAiB,mBAI3D;AAAA,cAEW,qBAAA,GAAyB,QAAA,EAAU,gBAAA,KAAmB,qBAUjE;AAAA,cAEW,yBAAA,GACX,QAAA,EAAU,oBAAA,KACT,yBAOD;AAAA,cAEW,iBAAA,GAAqB,QAAA,EAAU,YAAA,KAAe,iBAO1D;AAAA,cAEY,iCAAA,GACX,QAAA,EAAU,gBAAA,KACT,iCAMD;AAAA,cAqBW,6BAAA,GACX,QAAA,EAAU,gBAAA,EACV,SAAA,GAAW,aAAA,CAAc,cAAA;AAAA,cAoBd,WAAA,EAAW,MAAA,CAAA,KAAA,kBAAA,mBAAA,SAAA,eAAA;AAAA,KACZ,WAAA,UAAqB,WAAA,CAAY,IAAI;AAAA,cAEpC,YAAA,EAAY,MAAA,CAAA,KAAA,kBAAA,oBAAA,SAAA,gBAAA;AAAA,KACb,YAAA,UAAsB,YAAA,CAAa,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.mjs","names":[],"sources":["../../src/protocol/tool.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { Content } from './content.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nexport const HitlResponseSource = Schema.Literals(['user', 'policy', 'replay'])\nexport type HitlResponseSource = typeof HitlResponseSource.Type\n\nexport const ToolApprovalDecision = Schema.Literals(['approved', 'denied'])\nexport type ToolApprovalDecision = typeof ToolApprovalDecision.Type\n\nexport const ToolApprovalMode = Schema.Literals(['manual'])\nexport type ToolApprovalMode = typeof ToolApprovalMode.Type\n\nexport class ToolApprovalPolicy extends Schema.Class<ToolApprovalPolicy>('ToolApprovalPolicy')({\n mode: ToolApprovalMode,\n reason: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolCall extends Schema.Class<ToolCall>('ToolCall')({\n id: NonEmptyTrimmedString,\n name: NonEmptyTrimmedString,\n params: Schema.Unknown\n}) {}\n\nexport class ToolDef extends Schema.Class<ToolDef>('ToolDef')({\n name: NonEmptyTrimmedString,\n description: Schema.String,\n parameters: Schema.Unknown,\n approval: Schema.optional(ToolApprovalPolicy)\n}) {}\n\nexport class ToolResult extends Schema.Class<ToolResult>('ToolResult')({\n toolCallId: NonEmptyTrimmedString,\n content: Content,\n isError: Schema.optional(Schema.Boolean),\n structuredContent: Schema.optional(Schema.Unknown)\n}) {}\n\nexport type ErrorToolResultInput = {\n readonly toolCallId: string\n readonly content: Content\n readonly structuredContent?: unknown\n}\n\nexport const makeErrorToolResult = (input: ErrorToolResultInput) =>\n ToolResult.make({\n toolCallId: input.toolCallId,\n content: input.content,\n isError: true,\n ...(input.structuredContent === undefined\n ? {}\n : { structuredContent: input.structuredContent })\n })\n\nexport class ToolApprovalRequest extends Schema.TaggedClass<ToolApprovalRequest>()(\n 'ToolApprovalRequest',\n {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n call: ToolCall,\n policy: Schema.optional(ToolApprovalPolicy)\n }\n) {}\n\nexport class ToolApprovalResponse extends Schema.TaggedClass<ToolApprovalResponse>()(\n 'ToolApprovalResponse',\n {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n decision: ToolApprovalDecision,\n source: HitlResponseSource,\n reason: Schema.optional(Schema.String)\n }\n) {}\n\nexport class QuestionOption extends Schema.Class<QuestionOption>('QuestionOption')({\n id: NonEmptyTrimmedString,\n label: NonEmptyTrimmedString,\n description: Schema.optional(Schema.String)\n}) {}\n\nexport class QuestionPrompt extends Schema.Class<QuestionPrompt>('QuestionPrompt')({\n id: NonEmptyTrimmedString,\n prompt: NonEmptyTrimmedString,\n options: Schema.optional(Schema.Array(QuestionOption)),\n multiple: Schema.optional(Schema.Boolean),\n allowCustom: Schema.optional(Schema.Boolean),\n required: Schema.optional(Schema.Boolean)\n}) {}\n\nexport class QuestionToolParams extends Schema.Class<QuestionToolParams>('QuestionToolParams')({\n questions: Schema.NonEmptyArray(QuestionPrompt)\n}) {}\n\nexport class QuestionRequest extends Schema.TaggedClass<QuestionRequest>()('QuestionRequest', {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n call: ToolCall,\n questions: Schema.NonEmptyArray(QuestionPrompt)\n}) {}\n\nexport class QuestionAnswer extends Schema.Class<QuestionAnswer>('QuestionAnswer')({\n questionId: NonEmptyTrimmedString,\n optionIds: Schema.optional(Schema.Array(NonEmptyTrimmedString)),\n customAnswer: Schema.optional(Schema.String)\n}) {}\n\nexport type PlainQuestionAnswer = {\n readonly questionId: string\n readonly optionIds?: ReadonlyArray<string>\n readonly customAnswer?: string\n}\n\nexport const QuestionResponseOutcome = Schema.Literals(['answered', 'cancelled'])\nexport type QuestionResponseOutcome = typeof QuestionResponseOutcome.Type\n\nexport class QuestionResponse extends Schema.TaggedClass<QuestionResponse>()('QuestionResponse', {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n outcome: QuestionResponseOutcome,\n source: HitlResponseSource,\n answers: Schema.optional(Schema.Array(QuestionAnswer)),\n reason: Schema.optional(Schema.String)\n}) {}\n\nexport type PlainQuestionResponse = {\n readonly _tag: 'QuestionResponse'\n readonly requestId: string\n readonly toolCallId: string\n readonly outcome: QuestionResponseOutcome\n readonly source: HitlResponseSource\n readonly answers?: ReadonlyArray<PlainQuestionAnswer>\n readonly reason?: string\n}\n\nexport type PlainToolApprovalResponse = {\n readonly _tag: 'ToolApprovalResponse'\n readonly requestId: string\n readonly toolCallId: string\n readonly decision: ToolApprovalDecision\n readonly source: HitlResponseSource\n readonly reason?: string\n}\n\nexport type PlainHitlResponse = PlainToolApprovalResponse | PlainQuestionResponse\n\nexport type QuestionResponseStructuredContent = {\n readonly type: 'question_response'\n readonly outcome: QuestionResponseOutcome\n readonly answers: ReadonlyArray<PlainQuestionAnswer>\n readonly reason?: string\n readonly source: HitlResponseSource\n}\n\nexport const plainQuestionAnswer = (answer: QuestionAnswer): PlainQuestionAnswer => ({\n questionId: answer.questionId,\n ...(answer.optionIds === undefined ? {} : { optionIds: [...answer.optionIds] }),\n ...(answer.customAnswer === undefined ? {} : { customAnswer: answer.customAnswer })\n})\n\nexport const plainQuestionResponse = (response: QuestionResponse): PlainQuestionResponse => ({\n _tag: 'QuestionResponse',\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n outcome: response.outcome,\n source: response.source,\n ...(response.answers === undefined\n ? {}\n : { answers: response.answers.map(answer => plainQuestionAnswer(answer)) }),\n ...(response.reason === undefined ? {} : { reason: response.reason })\n})\n\nexport const plainToolApprovalResponse = (\n response: ToolApprovalResponse\n): PlainToolApprovalResponse => ({\n _tag: 'ToolApprovalResponse',\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n decision: response.decision,\n source: response.source,\n ...(response.reason === undefined ? {} : { reason: response.reason })\n})\n\nexport const plainHitlResponse = (response: HitlResponse): PlainHitlResponse => {\n switch (response._tag) {\n case 'QuestionResponse':\n return plainQuestionResponse(response)\n case 'ToolApprovalResponse':\n return plainToolApprovalResponse(response)\n }\n}\n\nexport const questionResponseStructuredContent = (\n response: QuestionResponse\n): QuestionResponseStructuredContent => ({\n type: 'question_response',\n outcome: response.outcome,\n answers: (response.answers ?? []).map(answer => plainQuestionAnswer(answer)),\n ...(response.reason === undefined ? {} : { reason: response.reason }),\n source: response.source\n})\n\nconst optionLabel = (question: QuestionPrompt, optionId: string) =>\n question.options?.find(option => option.id === optionId)?.label ?? optionId\n\nconst questionForAnswer = (questions: ReadonlyArray<QuestionPrompt>, answer: QuestionAnswer) =>\n questions.find(question => question.id === answer.questionId)\n\nconst formatQuestionAnswer = (answer: QuestionAnswer, questions: ReadonlyArray<QuestionPrompt>) => {\n const question = questionForAnswer(questions, answer)\n const prompt = question?.prompt ?? answer.questionId\n const selected =\n answer.optionIds?.map(optionId =>\n question === undefined ? optionId : optionLabel(question, optionId)\n ) ?? []\n const custom = answer.customAnswer?.trim()\n const values = custom === undefined || custom.length === 0 ? selected : [...selected, custom]\n\n return values.length === 0 ? `- ${prompt}: answered` : `- ${prompt}: ${values.join(', ')}`\n}\n\nexport const formatQuestionResponseContent = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt> = []\n) => {\n if (response.outcome === 'cancelled') {\n return `Question cancelled: ${response.reason ?? 'Question cancelled'}`\n }\n\n const answers = response.answers ?? []\n\n if (answers.length === 0) {\n return 'User answered the question, but no answer values were provided. Continue with this in mind.'\n }\n\n const formatted = answers\n .map(answer => formatQuestionAnswer(answer, questions).slice('- '.length))\n .join('; ')\n const label = answers.length === 1 ? 'question' : 'questions'\n\n return `User has answered your ${label}: ${formatted}. Continue with the user's answers in mind.`\n}\n\nexport const HitlRequest = Schema.Union([ToolApprovalRequest, QuestionRequest])\nexport type HitlRequest = typeof HitlRequest.Type\n\nexport const HitlResponse = Schema.Union([ToolApprovalResponse, QuestionResponse])\nexport type HitlResponse = typeof HitlResponse.Type\n"],"mappings":";;;AAGA,MAAM,wBAAwB,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO,WAAW,CAAC,CAAC;AAEnF,MAAa,qBAAqB,OAAO,SAAS;CAAC;CAAQ;CAAU;AAAQ,CAAC;AAG9E,MAAa,uBAAuB,OAAO,SAAS,CAAC,YAAY,QAAQ,CAAC;AAG1E,MAAa,mBAAmB,OAAO,SAAS,CAAC,QAAQ,CAAC;AAG1D,IAAa,qBAAb,cAAwC,OAAO,MAA0B,oBAAoB,EAAE;CAC7F,MAAM;CACN,QAAQ,OAAO,SAAS,OAAO,MAAM;AACvC,CAAC,EAAE,CAAC;AAEJ,IAAa,WAAb,cAA8B,OAAO,MAAgB,UAAU,EAAE;CAC/D,IAAI;CACJ,MAAM;CACN,QAAQ,OAAO;AACjB,CAAC,EAAE,CAAC;AAEJ,IAAa,UAAb,cAA6B,OAAO,MAAe,SAAS,EAAE;CAC5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O;CAGT,MAAM,YAAY,QACf,KAAI,WAAU,qBAAqB,QAAQ,SAAS,EAAE,MAAM,CAAW,CAAC,EACxE,KAAK,IAAI;CAGZ,OAAO,0BAFO,QAAQ,WAAW,IAAI,aAAa,YAEX,IAAI,UAAU;AACvD;AAEA,MAAa,cAAc,OAAO,MAAM,CAAC,qBAAqB,eAAe,CAAC;AAG9E,MAAa,eAAe,OAAO,MAAM,CAAC,sBAAsB,gBAAgB,CAAC"}
1
+ {"version":3,"file":"tool.mjs","names":[],"sources":["../../src/protocol/tool.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { Content } from './content.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nexport const HitlResponseSource = Schema.Literals(['user', 'policy', 'replay'])\nexport type HitlResponseSource = typeof HitlResponseSource.Type\n\nexport const ToolApprovalDecision = Schema.Literals(['approved', 'denied'])\nexport type ToolApprovalDecision = typeof ToolApprovalDecision.Type\n\nexport const ToolApprovalMode = Schema.Literals(['manual'])\nexport type ToolApprovalMode = typeof ToolApprovalMode.Type\n\nexport class ToolApprovalPolicy extends Schema.Class<ToolApprovalPolicy>('ToolApprovalPolicy')({\n mode: ToolApprovalMode,\n reason: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolCall extends Schema.Class<ToolCall>('ToolCall')({\n id: NonEmptyTrimmedString,\n name: NonEmptyTrimmedString,\n params: Schema.Unknown\n}) {}\n\nexport class ToolDef extends Schema.Class<ToolDef>('ToolDef')({\n name: NonEmptyTrimmedString,\n description: Schema.String,\n parameters: Schema.Unknown,\n approval: Schema.optional(ToolApprovalPolicy)\n}) {}\n\nexport class ToolResult extends Schema.Class<ToolResult>('ToolResult')({\n toolCallId: NonEmptyTrimmedString,\n content: Content,\n isError: Schema.optional(Schema.Boolean),\n structuredContent: Schema.optional(Schema.Unknown)\n}) {}\n\nexport type ErrorToolResultInput = {\n readonly toolCallId: string\n readonly content: Content\n readonly structuredContent?: unknown\n}\n\nexport const makeErrorToolResult = (input: ErrorToolResultInput) =>\n ToolResult.make({\n toolCallId: input.toolCallId,\n content: input.content,\n isError: true,\n ...(input.structuredContent === undefined ? {} : { structuredContent: input.structuredContent })\n })\n\nexport class ToolApprovalRequest extends Schema.TaggedClass<ToolApprovalRequest>()(\n 'ToolApprovalRequest',\n {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n call: ToolCall,\n policy: Schema.optional(ToolApprovalPolicy)\n }\n) {}\n\nexport class ToolApprovalResponse extends Schema.TaggedClass<ToolApprovalResponse>()(\n 'ToolApprovalResponse',\n {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n decision: ToolApprovalDecision,\n source: HitlResponseSource,\n reason: Schema.optional(Schema.String)\n }\n) {}\n\nexport class QuestionOption extends Schema.Class<QuestionOption>('QuestionOption')({\n id: NonEmptyTrimmedString,\n label: NonEmptyTrimmedString,\n description: Schema.optional(Schema.String)\n}) {}\n\nexport class QuestionPrompt extends Schema.Class<QuestionPrompt>('QuestionPrompt')({\n id: NonEmptyTrimmedString,\n prompt: NonEmptyTrimmedString,\n options: Schema.optional(Schema.Array(QuestionOption)),\n multiple: Schema.optional(Schema.Boolean),\n allowCustom: Schema.optional(Schema.Boolean),\n required: Schema.optional(Schema.Boolean)\n}) {}\n\nexport class QuestionToolParams extends Schema.Class<QuestionToolParams>('QuestionToolParams')({\n questions: Schema.NonEmptyArray(QuestionPrompt)\n}) {}\n\nexport class QuestionRequest extends Schema.TaggedClass<QuestionRequest>()('QuestionRequest', {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n call: ToolCall,\n questions: Schema.NonEmptyArray(QuestionPrompt)\n}) {}\n\nexport class QuestionAnswer extends Schema.Class<QuestionAnswer>('QuestionAnswer')({\n questionId: NonEmptyTrimmedString,\n optionIds: Schema.optional(Schema.Array(NonEmptyTrimmedString)),\n customAnswer: Schema.optional(Schema.String)\n}) {}\n\nexport type PlainQuestionAnswer = {\n readonly questionId: string\n readonly optionIds?: ReadonlyArray<string>\n readonly customAnswer?: string\n}\n\nexport const QuestionResponseOutcome = Schema.Literals(['answered', 'cancelled'])\nexport type QuestionResponseOutcome = typeof QuestionResponseOutcome.Type\n\nexport class QuestionResponse extends Schema.TaggedClass<QuestionResponse>()('QuestionResponse', {\n requestId: NonEmptyTrimmedString,\n toolCallId: NonEmptyTrimmedString,\n outcome: QuestionResponseOutcome,\n source: HitlResponseSource,\n answers: Schema.optional(Schema.Array(QuestionAnswer)),\n reason: Schema.optional(Schema.String)\n}) {}\n\nexport type PlainQuestionResponse = {\n readonly _tag: 'QuestionResponse'\n readonly requestId: string\n readonly toolCallId: string\n readonly outcome: QuestionResponseOutcome\n readonly source: HitlResponseSource\n readonly answers?: ReadonlyArray<PlainQuestionAnswer>\n readonly reason?: string\n}\n\nexport type PlainToolApprovalResponse = {\n readonly _tag: 'ToolApprovalResponse'\n readonly requestId: string\n readonly toolCallId: string\n readonly decision: ToolApprovalDecision\n readonly source: HitlResponseSource\n readonly reason?: string\n}\n\nexport type PlainHitlResponse = PlainToolApprovalResponse | PlainQuestionResponse\n\nexport type QuestionResponseStructuredContent = {\n readonly type: 'question_response'\n readonly outcome: QuestionResponseOutcome\n readonly answers: ReadonlyArray<PlainQuestionAnswer>\n readonly reason?: string\n readonly source: HitlResponseSource\n}\n\nexport const plainQuestionAnswer = (answer: QuestionAnswer): PlainQuestionAnswer => ({\n questionId: answer.questionId,\n ...(answer.optionIds === undefined ? {} : { optionIds: [...answer.optionIds] }),\n ...(answer.customAnswer === undefined ? {} : { customAnswer: answer.customAnswer })\n})\n\nexport const plainQuestionResponse = (response: QuestionResponse): PlainQuestionResponse => ({\n _tag: 'QuestionResponse',\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n outcome: response.outcome,\n source: response.source,\n ...(response.answers === undefined\n ? {}\n : { answers: response.answers.map(answer => plainQuestionAnswer(answer)) }),\n ...(response.reason === undefined ? {} : { reason: response.reason })\n})\n\nexport const plainToolApprovalResponse = (\n response: ToolApprovalResponse\n): PlainToolApprovalResponse => ({\n _tag: 'ToolApprovalResponse',\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n decision: response.decision,\n source: response.source,\n ...(response.reason === undefined ? {} : { reason: response.reason })\n})\n\nexport const plainHitlResponse = (response: HitlResponse): PlainHitlResponse => {\n switch (response._tag) {\n case 'QuestionResponse':\n return plainQuestionResponse(response)\n case 'ToolApprovalResponse':\n return plainToolApprovalResponse(response)\n }\n}\n\nexport const questionResponseStructuredContent = (\n response: QuestionResponse\n): QuestionResponseStructuredContent => ({\n type: 'question_response',\n outcome: response.outcome,\n answers: (response.answers ?? []).map(answer => plainQuestionAnswer(answer)),\n ...(response.reason === undefined ? {} : { reason: response.reason }),\n source: response.source\n})\n\nconst optionLabel = (question: QuestionPrompt, optionId: string) =>\n question.options?.find(option => option.id === optionId)?.label ?? optionId\n\nconst questionForAnswer = (questions: ReadonlyArray<QuestionPrompt>, answer: QuestionAnswer) =>\n questions.find(question => question.id === answer.questionId)\n\nconst formatQuestionAnswer = (answer: QuestionAnswer, questions: ReadonlyArray<QuestionPrompt>) => {\n const question = questionForAnswer(questions, answer)\n const prompt = question?.prompt ?? answer.questionId\n const selected =\n answer.optionIds?.map(optionId =>\n question === undefined ? optionId : optionLabel(question, optionId)\n ) ?? []\n const custom = answer.customAnswer?.trim()\n const values = custom === undefined || custom.length === 0 ? selected : [...selected, custom]\n\n return values.length === 0 ? `- ${prompt}: answered` : `- ${prompt}: ${values.join(', ')}`\n}\n\nexport const formatQuestionResponseContent = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt> = []\n) => {\n if (response.outcome === 'cancelled') {\n return `Question cancelled: ${response.reason ?? 'Question cancelled'}`\n }\n\n const answers = response.answers ?? []\n\n if (answers.length === 0) {\n return 'User answered the question, but no answer values were provided. Continue with this in mind.'\n }\n\n const formatted = answers\n .map(answer => formatQuestionAnswer(answer, questions).slice('- '.length))\n .join('; ')\n const label = answers.length === 1 ? 'question' : 'questions'\n\n return `User has answered your ${label}: ${formatted}. Continue with the user's answers in mind.`\n}\n\nexport const HitlRequest = Schema.Union([ToolApprovalRequest, QuestionRequest])\nexport type HitlRequest = typeof HitlRequest.Type\n\nexport const HitlResponse = Schema.Union([ToolApprovalResponse, QuestionResponse])\nexport type HitlResponse = typeof HitlResponse.Type\n"],"mappings":";;;AAGA,MAAM,wBAAwB,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO,WAAW,CAAC,CAAC;AAEnF,MAAa,qBAAqB,OAAO,SAAS;CAAC;CAAQ;CAAU;AAAQ,CAAC;AAG9E,MAAa,uBAAuB,OAAO,SAAS,CAAC,YAAY,QAAQ,CAAC;AAG1E,MAAa,mBAAmB,OAAO,SAAS,CAAC,QAAQ,CAAC;AAG1D,IAAa,qBAAb,cAAwC,OAAO,MAA0B,oBAAoB,EAAE;CAC7F,MAAM;CACN,QAAQ,OAAO,SAAS,OAAO,MAAM;AACvC,CAAC,EAAE,CAAC;AAEJ,IAAa,WAAb,cAA8B,OAAO,MAAgB,UAAU,EAAE;CAC/D,IAAI;CACJ,MAAM;CACN,QAAQ,OAAO;AACjB,CAAC,EAAE,CAAC;AAEJ,IAAa,UAAb,cAA6B,OAAO,MAAe,SAAS,EAAE;CAC5D,MAAM;CACN,aAAa,OAAO;CACpB,YAAY,OAAO;CACnB,UAAU,OAAO,SAAS,kBAAkB;AAC9C,CAAC,EAAE,CAAC;AAEJ,IAAa,aAAb,cAAgC,OAAO,MAAkB,YAAY,EAAE;CACrE,YAAY;CACZ,SAAS;CACT,SAAS,OAAO,SAAS,OAAO,OAAO;CACvC,mBAAmB,OAAO,SAAS,OAAO,OAAO;AACnD,CAAC,EAAE,CAAC;AAQJ,MAAa,uBAAuB,UAClC,WAAW,KAAK;CACd,YAAY,MAAM;CAClB,SAAS,MAAM;CACf,SAAS;CACT,GAAI,MAAM,sBAAsB,KAAA,IAAY,CAAC,IAAI,EAAE,m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;AAAA;AAAA,KAGN,kBAAA,GACD,kBAAA,GACA,mBAAA,GACA,sBAAA,GACA,wBAAA;AAAA,KACC,uBAAA,GAA0B,kBAAA,GAAqB,qBAAqB;AAAA,KAEpE,gBAAA;EAAA,SACU,IAAA;EAAA,SAAuB,OAAA,WAAkB,aAAA,CAAc,kBAAA;AAAA;EAAA,SACvD,IAAA;EAAA,SAA4B,OAAA,EAAS,aAAA,CAAc,uBAAA;AAAA;AAAA,KAS7D,aAAA;EAAA,SACM,IAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;AAAA;AAAA,KAGN,oBAAA;EAAA,SACM,KAAA;EAAA,SACA,MAAA,EAAQ,aAAA,CAAc,oBAAA;EAAA,SACtB,QAAA,EAAU,aAAA,CAAc,gBAAA;EAAA,SACxB,UAAA;EAAA,SACA,MAAA;EAAA,SACA,KAAA,GAAQ,aAAA,CAAc,aAAA;AAAA;AAAA,cA8sBpB,4BAAA,GACX,OAAA,EAAS,UAAA,EACT,MAAA;EAAA,SAAoB,SAAA;EAAA,SAA6B,MAAA;AAAA,MAChD,MAAA,CAAO,MAAA,CAAO,oBAAA,EAAsB,QAAA;AAAA,cAoiB1B,6BAAA,GACX,QAAA,EAAU,kBAAA,CAAmB,kBAAA,KAC5B,MAAA,CAAO,MAAA,CAAO,QAAA,EAAU,QAAA;AAAA,cA2Fd,gCAAA,GAAoC,MAAA,EAAQ,6BAAA,KAA6B,KAAA,CAAA,KAAA,CAAA,WAAA,SAAA,UAAA,CAAA,UAAA"}
@@ -1,7 +1,7 @@
1
1
  import { classifyProviderFailure, providerErrorInfo, providerFailureCause, providerFailureRetryable } from "../provider-error.mjs";
2
2
  import { validateProviderTranscript } from "../transcript.mjs";
3
3
  import { anthropicClaudeAuthorizationHeaders, anthropicClaudeCodeEntrypoint, anthropicClaudeCodeVersion, anthropicClaudeOAuthUserAgent } from "./claude.mjs";
4
- import { AgentInputUsage, AgentOutputUsage, AgentUsage, ToolCall, assistantContent, assistantHostToolCalls, attachmentSourceText, isTextDocumentMimeType, messageContextText, prependMessageContextToContent } from "@yolk-sdk/agent/protocol";
4
+ import { AgentInputUsage, AgentOutputUsage, AgentUsage, ToolCall, assistantContent, assistantHostToolCalls, attachmentSourceText, isTextDocumentMimeType, messageContextText, prependMessageContextToContent, replaceLoneSurrogatesDeep } from "@yolk-sdk/agent/protocol";
5
5
  import { Effect, Layer, Option, Ref, Stream } from "effect";
6
6
  import { HttpClient, HttpClientRequest } from "effect/unstable/http";
7
7
  import * as Schema from "effect/Schema";
@@ -797,10 +797,10 @@ const streamAnthropicClaudeResponse = (response) => Stream.unwrap(Ref.make(initi
797
797
  return chunks.pipe(Stream.concat(finalEvents));
798
798
  })));
799
799
  const sendAnthropicClaudeRequest = (config, request, client, sessionId) => Effect.gen(function* () {
800
- const serializedBody = yield* encodeJsonString(yield* toAnthropicClaudeRequestBody(request, {
800
+ const serializedBody = yield* encodeJsonString(replaceLoneSurrogatesDeep(yield* toAnthropicClaudeRequestBody(request, {
801
801
  ...config,
802
802
  stream: true
803
- }), "Could not serialize Anthropic Claude request");
803
+ })), "Could not serialize Anthropic Claude request");
804
804
  const httpRequest = HttpClientRequest.post(config.messagesUrl ?? anthropicClaudeMessagesUrl).pipe(HttpClientRequest.setHeaders({
805
805
  accept: "text/event-stream",
806
806
  ...anthropicClaudeAuthorizationHeaders(config.token),