@yolk-sdk/agent 0.0.1-canary.7 → 0.0.1-canary.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,6 +61,23 @@ const program = run({
61
61
  // Provide LLM provider, loop config, context transformer, and tool executor layers in the host app.
62
62
  ```
63
63
 
64
+ ## Protocol content
65
+
66
+ `Content` is either plain text or ordered parts:
67
+
68
+ - `TextPart`
69
+ - `ImagePart` with `InlineBase64`, `Url`, or host-owned `Ref` source
70
+ - `DocumentPart` with `InlineBase64`, `Url`, or host-owned `Ref` source
71
+ - `AudioPart` with `InlineBase64`, `Url`, or host-owned `Ref` source
72
+
73
+ Build sources with `inlineBase64AttachmentSource`, `urlAttachmentSource`, or
74
+ `refAttachmentSource`. Providers require inline/resolved media before lowering. Use inline base64
75
+ for simple apps, or persist `Ref` values and call `resolveContentAttachmentSources` at your storage
76
+ boundary before provider execution. Host apps own upload, auth, retention, and ref hydration policy.
77
+
78
+ Use model capabilities like `textOnlyModelCapabilities`, `textImageModelCapabilities`, or
79
+ `textImageDocumentModelCapabilities` so the loop rejects unsupported inputs before provider calls.
80
+
64
81
  ## Human-in-the-loop
65
82
 
66
83
  HITL is protocol-level, not UI-level:
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;KAsEY,cAAA;AAAA,KAEA,SAAA;EAAA,SACD,QAAA,EAAU,aAAA,CAAc,YAAA;EAAA,SACxB,YAAA;EAAA,SACA,KAAA,EAAO,aAAA,CAAc,OAAA;EAAA,SACrB,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,oBAAA;EAAA,SAClB,YAAA,GAAe,sBAAA;AAAA;AAAA,KAGd,eAAA,GAAkB,SAAS;EAAA,SAC5B,IAAI;AAAA;AAAA,KAGH,eAAA;EAAA,SACD,KAAA,EAAO,aAA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,GAAQ,UAAA;AAAA;AAAA,cAqhCN,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,kBAAA,GAAqB,WAAA,GAAc,UAAA;AAAA,cAuBnE,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,UAAA,GAAa,YAAA;AAAA,cA4C7C,GAAA,GACX,MAAA,EAAQ,SAAA,KACP,MAAA,CAAO,MAAA,CACR,UAAA,EACA,cAAA,EACA,kBAAA,GAAqB,WAAA,GAAc,UAAA,GAAa,YAAA"}
package/dist/loop/run.mjs CHANGED
@@ -59,6 +59,7 @@ const validateContent = (message, capabilities) => Effect.forEach(contentPartsFr
59
59
  switch (part._tag) {
60
60
  case "Text": return capabilities.input.text ? Effect.void : Effect.fail(unsupportedInputError("Text input is not supported by this model"));
61
61
  case "Image": return capabilities.input.image ? Effect.void : Effect.fail(unsupportedInputError("Image input is not supported by this model"));
62
+ case "Document": return capabilities.input.document ? Effect.void : Effect.fail(unsupportedInputError("Document input is not supported by this model"));
62
63
  case "Audio": return capabilities.input.audio ? Effect.void : Effect.fail(unsupportedInputError("Audio input is not supported by this model"));
63
64
  }
64
65
  });
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":["AgentLLMTextDelta","AgentLLMReasoningDelta"],"sources":["../../src/loop/run.ts"],"sourcesContent":["import { Clock, Effect, Ref, Stream } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentAwaitingInput,\n AgentEnd,\n AgentRetry,\n AgentStart,\n AssistantMessageEvent,\n UsageUpdate,\n addAgentUsage,\n contentParts,\n contentPreview,\n LLMReasoningDelta as AgentLLMReasoningDelta,\n LLMStreamEnd,\n LLMStreamStart,\n LLMTextDelta as AgentLLMTextDelta,\n ToolExecutionCompleted,\n ToolExecutionError,\n ToolExecutionStarted,\n ToolApprovalDenied,\n ToolApprovalGranted,\n ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionAnswered,\n QuestionCancelled,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n makeSubagentRunId,\n ToolApprovalRequest,\n ToolResultMessage,\n SubagentCompleted,\n SubagentStarted,\n assistantHostToolCalls,\n type ToolCall,\n type AgentReasoningEffort,\n type HitlRequest,\n type HitlResponse,\n type QuestionPrompt,\n type QuestionResponse,\n type ToolApprovalResponse,\n ToolResult,\n TurnEnd,\n TurnStart,\n zeroAgentUsage,\n type AgentEvent,\n type AgentErrorCode,\n type AgentMessage,\n type AgentUsage,\n type AgentModelCapabilities,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport { accumulateAssistantMessage, collectToolCalls } from './accumulator.ts'\nimport {\n AbortError,\n LLMError,\n ToolError,\n type AgentLoopError,\n type LLMProviderError,\n} from './error.ts'\nimport type { LLMEvent } from './llm-event.ts'\nimport { ContextTransformer, type ContextTransformResult } from './services/context-transformer.ts'\nimport { LLMProvider, type LLMRequest } from './services/llm-provider.ts'\nimport { LoopConfig, type LoopConfigShape } from './services/loop-config.ts'\nimport { ToolExecutor } from './services/tool-executor.ts'\n\nexport type AgentLoopRunId = string\n\nexport type RunConfig = {\n readonly messages: ReadonlyArray<AgentMessage>\n readonly systemPrompt: string\n readonly tools: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly capabilities?: AgentModelCapabilities\n}\n\nexport type ModelTurnConfig = RunConfig & {\n readonly turn: number\n}\n\nexport type ToolBatchConfig = {\n readonly calls: ReadonlyArray<ToolCall>\n readonly tools?: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly createdMessages?: ReadonlyArray<AgentMessage>\n readonly turn?: number\n readonly usage?: AgentUsage\n}\n\nconst questionToolName = 'question'\n\ntype TaskCallMetadata = {\n readonly subagentRunId: string\n readonly subagentType: string\n readonly description: string\n}\n\nconst objectField = (input: unknown, key: string) =>\n input !== null && typeof input === 'object' ? Object.getOwnPropertyDescriptor(input, key)?.value : undefined\n\nconst nonEmptyStringField = (input: unknown, key: string) => {\n const value = objectField(input, key)\n\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nconst taskCallMetadata = (call: ToolCall): TaskCallMetadata | undefined => {\n if (call.name !== 'task') {\n return undefined\n }\n\n const subagentType = nonEmptyStringField(call.params, 'subagent_type')\n const description = nonEmptyStringField(call.params, 'description')\n\n if (subagentType === undefined || description === undefined) {\n return undefined\n }\n\n return {\n subagentRunId: makeSubagentRunId(call.id),\n subagentType,\n description\n }\n}\n\nconst subagentStartedEvent = (input: {\n readonly call: ToolCall\n readonly model: string\n readonly startedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentStarted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n createdAtMs: input.startedAtMs\n })\n}\n\nconst subagentCompletedEvent = (input: {\n readonly call: ToolCall\n readonly result: ToolResult\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentCompleted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n status: input.result.isError === true ? 'error' : 'completed',\n durationMs: Math.max(0, input.endedAtMs - input.startedAtMs),\n summary: contentPreview(input.result.content),\n createdAtMs: input.endedAtMs\n })\n}\n\nconst unsupportedInputError = (message: string) =>\n new LLMError({\n cause: 'validation_error',\n message,\n retryable: false\n })\n\nconst validateContent = (message: AgentMessage, capabilities: AgentModelCapabilities) =>\n Effect.forEach(contentPartsFromMessage(message), part => {\n switch (part._tag) {\n case 'Text':\n return capabilities.input.text\n ? Effect.void\n : Effect.fail(unsupportedInputError('Text input is not supported by this model'))\n case 'Image':\n return capabilities.input.image\n ? Effect.void\n : Effect.fail(unsupportedInputError('Image input is not supported by this model'))\n case 'Audio':\n return capabilities.input.audio\n ? Effect.void\n : Effect.fail(unsupportedInputError('Audio input is not supported by this model'))\n }\n })\n\nconst contentPartsFromMessage = (message: AgentMessage) => {\n switch (message._tag) {\n case 'User':\n case 'ToolResult':\n return contentParts(message.content)\n case 'Assistant':\n return message.parts.flatMap(part => (part._tag === 'Text' ? contentParts(part.content) : []))\n }\n}\n\nconst validateCapabilities = (\n config: RunConfig,\n messages: ReadonlyArray<AgentMessage>\n): Effect.Effect<void, LLMError> => {\n const capabilities = config.capabilities\n\n if (capabilities === undefined) {\n return Effect.void\n }\n\n if (!capabilities.tools && config.tools.length > 0) {\n return Effect.fail(unsupportedInputError('Tools are not supported by this model'))\n }\n\n if (!capabilities.reasoning && config.reasoningEffort !== undefined) {\n return Effect.fail(unsupportedInputError('Reasoning effort is not supported by this model'))\n }\n\n return Effect.forEach(messages, message => validateContent(message, capabilities)).pipe(\n Effect.asVoid\n )\n}\n\nconst toLlmEvent = (event: LLMEvent): ReadonlyArray<AgentEvent> => {\n switch (event._tag) {\n case 'TextDelta':\n return [AgentLLMTextDelta.make({ text: event.text })]\n case 'ReasoningDelta':\n return [AgentLLMReasoningDelta.make({ text: event.text })]\n case 'ToolCall':\n return [ToolInputEnd.make({ call: event.call })]\n case 'ToolInputStart':\n return [ToolInputStart.make({ id: event.id, name: event.name })]\n case 'ToolInputDelta':\n return [ToolInputDelta.make({ id: event.id, delta: event.delta })]\n case 'ProviderToolResult':\n return [ProviderToolResult.make({ call: event.call, result: event.result })]\n case 'Usage':\n return [UsageUpdate.make({ usage: event.usage })]\n case 'Done':\n return []\n }\n}\n\nconst isLlmEvent = (event: LLMEvent | AgentEvent | AgentRetry): event is LLMEvent => {\n switch (event._tag) {\n case 'TextDelta':\n case 'ReasoningDelta':\n case 'Done':\n case 'ToolCall':\n case 'ToolInputStart':\n case 'ToolInputDelta':\n case 'ProviderToolResult':\n case 'Usage':\n return true\n default:\n return false\n }\n}\n\ntype TurnStreamInput = {\n readonly config: RunConfig\n readonly contextTransformer: {\n readonly transform: (\n messages: ReadonlyArray<AgentMessage>\n ) => Effect.Effect<ContextTransformResult, AgentLoopError>\n }\n readonly loopConfig: LoopConfigShape\n readonly provider: {\n readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMProviderError>\n }\n readonly executor: {\n readonly execute: (call: ToolCall) => Effect.Effect<ToolResult, ToolError>\n }\n readonly currentMessages: ReadonlyArray<AgentMessage>\n readonly createdMessages: Ref.Ref<ReadonlyArray<AgentMessage>>\n readonly usage: Ref.Ref<AgentUsage>\n readonly turn: number\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number) =>\n Math.max(0, Math.floor(baseDelayMs * 2 ** Math.max(0, attempt - 1)))\n\nconst retryReason = (error: LLMError): AgentErrorCode => error.cause\n\nconst retrySleep = (delayMs: number) =>\n delayMs === 0 ? Effect.void : Effect.sleep(`${delayMs} millis`)\n\nconst failAgentLoopError = (\n error: AgentLoopError\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> => Stream.fail(error)\n\nconst sleepStream = (delayMs: number): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.fromEffect(retrySleep(delayMs)).pipe(Stream.flatMap(() => Stream.empty))\n\nconst withProviderRetries = (\n stream: Stream.Stream<LLMEvent, LLMProviderError>,\n loopConfig: TurnStreamInput['loopConfig'],\n makeStream: () => Stream.Stream<LLMEvent, LLMProviderError>,\n attempt: number\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.unwrap(\n Ref.make(false).pipe(\n Effect.map(emittedProviderEvent =>\n stream.pipe(\n Stream.tap(() => Ref.set(emittedProviderEvent, true)),\n Stream.catchTags({\n LLMError: error =>\n Stream.unwrap(\n Ref.get(emittedProviderEvent).pipe(\n Effect.map(emitted => {\n if (\n emitted ||\n !error.retryable ||\n error.cause === 'context_overflow' ||\n attempt > loopConfig.maxRetries\n ) {\n return failAgentLoopError(error)\n }\n\n const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message\n })\n ).pipe(\n Stream.concat(sleepStream(delayMs)),\n Stream.concat(\n withProviderRetries(makeStream(), loopConfig, makeStream, attempt + 1)\n )\n )\n })\n )\n ),\n AbortError: failAgentLoopError,\n FauxExhaustedError: failAgentLoopError\n })\n )\n )\n )\n )\n\nconst makeToolExecutionStream = (\n executor: TurnStreamInput['executor'],\n call: ToolCall,\n model: string\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAtMs = yield* Clock.currentTimeMillis\n const started = subagentStartedEvent({ call, model, startedAtMs })\n const startEvents: ReadonlyArray<AgentEvent> = started === undefined\n ? [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs })]\n : [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs }), started]\n\n return Stream.fromIterable(startEvents).pipe(\n Stream.concat(\n Stream.fromEffect(\n executor.execute(call).pipe(\n Effect.flatMap(result =>\n Clock.currentTimeMillis.pipe(\n Effect.map(endedAtMs => {\n const completed = subagentCompletedEvent({\n call,\n result,\n model,\n startedAtMs,\n endedAtMs\n })\n const toolCompleted = ToolExecutionCompleted.make({\n call,\n result,\n createdAtMs: endedAtMs\n })\n\n return completed === undefined\n ? [toolCompleted]\n : [toolCompleted, completed]\n })\n )\n )\n )\n ).pipe(\n Stream.flatMap(Stream.fromIterable),\n Stream.catchTag('ToolError', error =>\n Stream.fromEffect(Clock.currentTimeMillis).pipe(\n Stream.flatMap(endedAtMs =>\n Stream.make(\n ToolExecutionError.make({\n call,\n message: error.message,\n code: toolErrorCode(error),\n createdAtMs: endedAtMs\n })\n )\n ),\n Stream.concat(Stream.fail(error))\n )\n )\n )\n )\n )\n })\n )\n\ntype IndexedToolResultMessage = {\n readonly index: number\n readonly message: AgentMessage\n}\n\ntype IndexedToolCall = {\n readonly index: number\n readonly call: ToolCall\n}\n\ntype PreparedToolCall =\n | {\n readonly _tag: 'Execute'\n readonly index: number\n readonly call: ToolCall\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Result'\n readonly index: number\n readonly call: ToolCall\n readonly result: ToolResult\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Pending'\n readonly request: HitlRequest\n readonly events: ReadonlyArray<AgentEvent>\n }\n\ntype PreparedToolBatch = {\n readonly callsToExecute: ReadonlyArray<IndexedToolCall>\n readonly resultMessages: ReadonlyArray<IndexedToolResultMessage>\n readonly resultEvents: ReadonlyArray<AgentEvent>\n readonly events: ReadonlyArray<AgentEvent>\n readonly pendingRequests: ReadonlyArray<HitlRequest>\n readonly pendingEvents: ReadonlyArray<AgentEvent>\n}\n\ntype NonEmptyHitlRequests = readonly [HitlRequest, ...Array<HitlRequest>]\n\nconst boundedToolConcurrency = (loopConfig: LoopConfigShape) =>\n Math.max(1, loopConfig.toolConcurrency)\n\nconst toolResultMessageFromResult = (result: ToolResult) =>\n ToolResultMessage.make({\n toolCallId: result.toolCallId,\n content: result.content,\n isError: result.isError,\n structuredContent: result.structuredContent\n })\n\nconst toolDefFor = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n tools.find(tool => tool.name === call.name)\n\nconst approvalRequired = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n toolDefFor(tools, call)?.approval?.mode === 'manual'\n\nconst approvalRequestId = (call: ToolCall) => `approval:${call.id}`\n\nconst questionRequestId = (call: ToolCall) => `question:${call.id}`\n\nconst matchesApproval = (response: ToolApprovalResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === approvalRequestId(call)\n\nconst matchesQuestion = (response: QuestionResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === questionRequestId(call)\n\nconst approvalResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'ToolApprovalResponse' && matchesApproval(response, call) ? [response] : []\n )[0]\n\nconst questionResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'QuestionResponse' && matchesQuestion(response, call) ? [response] : []\n )[0]\n\nconst toolApprovalRequest = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall\n): ToolApprovalRequest =>\n ToolApprovalRequest.make({\n requestId: approvalRequestId(call),\n toolCallId: call.id,\n call,\n policy: toolDefFor(tools, call)?.approval\n })\n\nconst deniedToolResult = (call: ToolCall, response: ToolApprovalResponse) => {\n const reason = response.reason ?? 'Denied by user'\n\n return ToolResult.make({\n toolCallId: call.id,\n content: `Tool call denied: ${reason}`,\n isError: true,\n structuredContent: {\n type: 'tool_approval_denied',\n reason,\n source: response.source\n }\n })\n}\n\nconst questionToolResult = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt>\n) => {\n return ToolResult.make({\n toolCallId: response.toolCallId,\n content: formatQuestionResponseContent(response, questions),\n isError: response.outcome === 'cancelled' ? true : undefined,\n structuredContent: {\n type: 'question_response',\n outcome: response.outcome,\n answers: response.answers ?? [],\n reason: response.reason,\n source: response.source\n }\n })\n}\n\nconst invalidQuestionToolResult = (call: ToolCall) =>\n ToolResult.make({\n toolCallId: call.id,\n content: 'Invalid question arguments.',\n isError: true,\n structuredContent: { type: 'question_invalid' }\n })\n\nconst prepareQuestionCall = (\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): Effect.Effect<PreparedToolCall> =>\n Effect.gen(function* () {\n const decoded = yield* Schema.decodeUnknownEffect(QuestionToolParams)(call.params).pipe(\n Effect.result\n )\n\n if (decoded._tag === 'Failure') {\n return {\n _tag: 'Result',\n index,\n call,\n result: invalidQuestionToolResult(call),\n events: []\n }\n }\n\n const response = questionResponseFor(responses, call)\n\n if (response !== undefined) {\n return {\n _tag: 'Result',\n index,\n call,\n result: questionToolResult(response, decoded.success.questions),\n events: [\n response.outcome === 'answered'\n ? QuestionAnswered.make({ response })\n : QuestionCancelled.make({ response })\n ]\n }\n }\n\n const request = QuestionRequest.make({\n requestId: questionRequestId(call),\n toolCallId: call.id,\n call,\n questions: decoded.success.questions\n })\n\n return {\n _tag: 'Pending',\n request,\n events: [QuestionRequested.make({ request })]\n }\n })\n\nconst prepareApprovalCall = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): PreparedToolCall => {\n if (!approvalRequired(tools, call)) {\n return { _tag: 'Execute', index, call, events: [] }\n }\n\n const request = toolApprovalRequest(tools, call)\n const response = approvalResponseFor(responses, call)\n\n if (response === undefined) {\n return {\n _tag: 'Pending',\n request,\n events: [ToolApprovalRequested.make({ call, request })]\n }\n }\n\n if (response.decision === 'denied') {\n return {\n _tag: 'Result',\n index,\n call,\n result: deniedToolResult(call, response),\n events: [ToolApprovalDenied.make({ toolCallId: call.id, reason: response.reason ?? 'Denied by user', response })]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [ToolApprovalGranted.make({ toolCallId: call.id, response })]\n }\n}\n\nconst prepareToolCall = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly call: ToolCall\n readonly index: number\n}): Effect.Effect<PreparedToolCall> =>\n input.call.name === questionToolName\n ? prepareQuestionCall(input.call, input.index, input.responses)\n : Effect.succeed(prepareApprovalCall(input.tools, input.call, input.index, input.responses))\n\nconst prepareToolBatch = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly calls: ReadonlyArray<ToolCall>\n}): Effect.Effect<PreparedToolBatch> =>\n Effect.gen(function* () {\n const prepared = yield* Effect.forEach(input.calls, (call, index) =>\n prepareToolCall({ tools: input.tools, responses: input.responses, call, index })\n )\n\n return {\n callsToExecute: prepared.flatMap(item =>\n item._tag === 'Execute' ? [{ index: item.index, call: item.call }] : []\n ),\n resultMessages: prepared.flatMap(item =>\n item._tag === 'Result'\n ? [{ index: item.index, message: toolResultMessageFromResult(item.result) }]\n : []\n ),\n resultEvents: syntheticToolCompletionEvents(prepared),\n events: prepared.flatMap(item => (item._tag === 'Pending' ? [] : item.events)),\n pendingRequests: prepared.flatMap(item => (item._tag === 'Pending' ? [item.request] : [])),\n pendingEvents: prepared.flatMap(item => (item._tag === 'Pending' ? item.events : []))\n }\n })\n\nconst orderedToolResultMessages = (results: ReadonlyArray<IndexedToolResultMessage>) =>\n [...results].sort((left, right) => left.index - right.index).map(result => result.message)\n\nconst syntheticToolCompletionEvents = (\n prepared: ReadonlyArray<PreparedToolCall>\n): ReadonlyArray<AgentEvent> =>\n prepared.flatMap(item =>\n item._tag === 'Result'\n ? [ToolExecutionCompleted.make({ call: item.call, result: item.result })]\n : []\n )\n\nconst toolResultIds = (messages: ReadonlyArray<AgentMessage>): ReadonlySet<string> =>\n new Set(messages.flatMap(message => (message._tag === 'ToolResult' ? [message.toolCallId] : [])))\n\nconst pendingHostToolCalls = (messages: ReadonlyArray<AgentMessage>) => {\n const completed = toolResultIds(messages)\n\n return messages.flatMap(message =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).filter(call => !completed.has(call.id))\n : []\n )\n}\n\nconst nonEmptyHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): NonEmptyHitlRequests | undefined => {\n const first = requests[0]\n\n return first === undefined ? undefined : [first, ...requests.slice(1)]\n}\n\nconst parallelToolExecutionStream = (input: {\n readonly calls: ReadonlyArray<IndexedToolCall>\n readonly executor: TurnStreamInput['executor']\n readonly loopConfig: LoopConfigShape\n readonly model: string\n readonly results: Ref.Ref<ReadonlyArray<IndexedToolResultMessage>>\n}) =>\n Stream.mergeAll(\n input.calls.map(({ call, index }) =>\n makeToolExecutionStream(input.executor, call, input.model).pipe(\n Stream.tap(event => {\n if (event._tag !== 'ToolExecutionCompleted') {\n return Effect.void\n }\n\n return Ref.update(input.results, results => [\n ...results,\n { index, message: toolResultMessageFromResult(event.result) }\n ])\n })\n )\n ),\n { concurrency: boundedToolConcurrency(input.loopConfig) }\n )\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\ntype TurnCompletion = {\n readonly toolCalls: ReadonlyArray<ToolCall>\n readonly stopReason: 'stop' | 'tool_use'\n}\n\nconst validateTurnCompletion = (\n events: ReadonlyArray<LLMEvent>\n): Effect.Effect<TurnCompletion, LLMError> => {\n const doneEvents = events.filter(event => event._tag === 'Done')\n const toolCalls = collectToolCalls(events)\n const stopReason: TurnCompletion['stopReason'] = toolCalls.length === 0 ? 'stop' : 'tool_use'\n\n if (doneEvents.length !== 1) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `Expected exactly one LLM done event, received ${doneEvents.length}`,\n retryable: false\n })\n )\n }\n\n const doneEvent = doneEvents[0]\n\n if (doneEvent === undefined || doneEvent.stopReason !== stopReason) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `LLM done reason must be ${stopReason}`,\n retryable: false\n })\n )\n }\n\n return Effect.succeed({ toolCalls, stopReason })\n}\n\nconst makeAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n const turnEndEvents: ReadonlyArray<AgentEvent> = [\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage })\n ]\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n if (completion.toolCalls.length === 0) {\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentEnd.make({\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: completion.toolCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n ...prepared.events,\n ...prepared.pendingEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n Stream.make(TurnEnd.make({ turn: input.turn, reason: completion.stopReason })).pipe(\n Stream.concat(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, assistantMessage, ...orderedResults],\n turn: input.turn + 1\n })\n )\n )\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(turnEndEvents).pipe(\n Stream.concat(Stream.fromIterable(prepared.events)),\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst makeModelOnlyAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n return Stream.fromIterable([\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage }),\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason })\n ])\n })\n )\n\nconst makeLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeModelOnlyLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeModelOnlyAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeTurnStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nconst makePendingToolResumeStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const pendingCalls = pendingHostToolCalls(input.currentMessages)\n\n if (pendingCalls.length === 0 || (input.config.hitlResponses ?? []).length === 0) {\n return makeTurnStream(input)\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: pendingCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...prepared.events,\n ...prepared.pendingEvents,\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: Math.max(0, input.turn - 1),\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, ...orderedResults]\n })\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(prepared.events).pipe(\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst unavailableToolExecutor: TurnStreamInput['executor'] = {\n execute: call =>\n Effect.fail(\n new ToolError({\n tool: call.name,\n message: 'Tool execution is not available in model turn step',\n cause: 'execution'\n })\n )\n}\n\nconst makeModelOnlyTurnStream = (\n input: TurnStreamInput\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeModelOnlyLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nexport const runModelTurn = (\n config: ModelTurnConfig\n): Stream.Stream<AgentEvent, AgentLoopError, ContextTransformer | LLMProvider | LoopConfig> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return makeModelOnlyTurnStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor: unavailableToolExecutor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: config.turn\n })\n })\n )\n\nexport const runToolBatch = (\n config: ToolBatchConfig\n): Stream.Stream<AgentEvent, AgentLoopError, LoopConfig | ToolExecutor> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const executor = yield* ToolExecutor\n const loopConfig = yield* LoopConfig\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: config.tools ?? [],\n responses: config.hitlResponses ?? [],\n calls: config.calls\n })\n const hasPendingRequests = prepared.pendingRequests.length > 0\n const resultEvents = hasPendingRequests ? [] : prepared.resultEvents\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n const awaitingEvents: ReadonlyArray<AgentEvent> = pendingRequests === undefined\n ? []\n : [\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages: config.createdMessages ?? [],\n turns: config.turn ?? 0,\n usage: config.usage ?? zeroAgentUsage\n })\n ]\n\n return Stream.fromIterable([\n ...prepared.events,\n ...resultEvents,\n ...prepared.pendingEvents,\n ...awaitingEvents\n ]).pipe(\n Stream.concat(\n parallelToolExecutionStream({\n calls: hasPendingRequests ? [] : prepared.callsToExecute,\n executor,\n loopConfig,\n model: config.model ?? '',\n results: toolResultMessages\n })\n )\n )\n })\n )\n\nexport const run = (\n config: RunConfig\n): Stream.Stream<\n AgentEvent,\n AgentLoopError,\n ContextTransformer | LLMProvider | LoopConfig | ToolExecutor\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const executor = yield* ToolExecutor\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return Stream.make(AgentStart.make({})).pipe(\n Stream.concat(\n makePendingToolResumeStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: 1\n })\n )\n )\n })\n )\n"],"mappings":";;;;;;;;;;AAgGA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAAW,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAAQ,KAAA;AAErG,MAAM,uBAAuB,OAAgB,QAAgB;CAC3D,MAAM,QAAQ,YAAY,OAAO,GAAG;CAEpC,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ,KAAA;AACxE;AAEA,MAAM,oBAAoB,SAAi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/loop/run.ts"],"sourcesContent":["import { Clock, Effect, Ref, Stream } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentAwaitingInput,\n AgentEnd,\n AgentRetry,\n AgentStart,\n AssistantMessageEvent,\n UsageUpdate,\n addAgentUsage,\n contentParts,\n contentPreview,\n LLMReasoningDelta as AgentLLMReasoningDelta,\n LLMStreamEnd,\n LLMStreamStart,\n LLMTextDelta as AgentLLMTextDelta,\n ToolExecutionCompleted,\n ToolExecutionError,\n ToolExecutionStarted,\n ToolApprovalDenied,\n ToolApprovalGranted,\n ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionAnswered,\n QuestionCancelled,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n makeSubagentRunId,\n ToolApprovalRequest,\n ToolResultMessage,\n SubagentCompleted,\n SubagentStarted,\n assistantHostToolCalls,\n type ToolCall,\n type AgentReasoningEffort,\n type HitlRequest,\n type HitlResponse,\n type QuestionPrompt,\n type QuestionResponse,\n type ToolApprovalResponse,\n ToolResult,\n TurnEnd,\n TurnStart,\n zeroAgentUsage,\n type AgentEvent,\n type AgentErrorCode,\n type AgentMessage,\n type AgentUsage,\n type AgentModelCapabilities,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport { accumulateAssistantMessage, collectToolCalls } from './accumulator.ts'\nimport {\n AbortError,\n LLMError,\n ToolError,\n type AgentLoopError,\n type LLMProviderError,\n} from './error.ts'\nimport type { LLMEvent } from './llm-event.ts'\nimport { ContextTransformer, type ContextTransformResult } from './services/context-transformer.ts'\nimport { LLMProvider, type LLMRequest } from './services/llm-provider.ts'\nimport { LoopConfig, type LoopConfigShape } from './services/loop-config.ts'\nimport { ToolExecutor } from './services/tool-executor.ts'\n\nexport type AgentLoopRunId = string\n\nexport type RunConfig = {\n readonly messages: ReadonlyArray<AgentMessage>\n readonly systemPrompt: string\n readonly tools: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly capabilities?: AgentModelCapabilities\n}\n\nexport type ModelTurnConfig = RunConfig & {\n readonly turn: number\n}\n\nexport type ToolBatchConfig = {\n readonly calls: ReadonlyArray<ToolCall>\n readonly tools?: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly createdMessages?: ReadonlyArray<AgentMessage>\n readonly turn?: number\n readonly usage?: AgentUsage\n}\n\nconst questionToolName = 'question'\n\ntype TaskCallMetadata = {\n readonly subagentRunId: string\n readonly subagentType: string\n readonly description: string\n}\n\nconst objectField = (input: unknown, key: string) =>\n input !== null && typeof input === 'object' ? Object.getOwnPropertyDescriptor(input, key)?.value : undefined\n\nconst nonEmptyStringField = (input: unknown, key: string) => {\n const value = objectField(input, key)\n\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nconst taskCallMetadata = (call: ToolCall): TaskCallMetadata | undefined => {\n if (call.name !== 'task') {\n return undefined\n }\n\n const subagentType = nonEmptyStringField(call.params, 'subagent_type')\n const description = nonEmptyStringField(call.params, 'description')\n\n if (subagentType === undefined || description === undefined) {\n return undefined\n }\n\n return {\n subagentRunId: makeSubagentRunId(call.id),\n subagentType,\n description\n }\n}\n\nconst subagentStartedEvent = (input: {\n readonly call: ToolCall\n readonly model: string\n readonly startedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentStarted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n createdAtMs: input.startedAtMs\n })\n}\n\nconst subagentCompletedEvent = (input: {\n readonly call: ToolCall\n readonly result: ToolResult\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentCompleted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n status: input.result.isError === true ? 'error' : 'completed',\n durationMs: Math.max(0, input.endedAtMs - input.startedAtMs),\n summary: contentPreview(input.result.content),\n createdAtMs: input.endedAtMs\n })\n}\n\nconst unsupportedInputError = (message: string) =>\n new LLMError({\n cause: 'validation_error',\n message,\n retryable: false\n })\n\nconst validateContent = (message: AgentMessage, capabilities: AgentModelCapabilities) =>\n Effect.forEach(contentPartsFromMessage(message), part => {\n switch (part._tag) {\n case 'Text':\n return capabilities.input.text\n ? Effect.void\n : Effect.fail(unsupportedInputError('Text input is not supported by this model'))\n case 'Image':\n return capabilities.input.image\n ? Effect.void\n : Effect.fail(unsupportedInputError('Image input is not supported by this model'))\n case 'Document':\n return capabilities.input.document\n ? Effect.void\n : Effect.fail(unsupportedInputError('Document input is not supported by this model'))\n case 'Audio':\n return capabilities.input.audio\n ? Effect.void\n : Effect.fail(unsupportedInputError('Audio input is not supported by this model'))\n }\n })\n\nconst contentPartsFromMessage = (message: AgentMessage) => {\n switch (message._tag) {\n case 'User':\n case 'ToolResult':\n return contentParts(message.content)\n case 'Assistant':\n return message.parts.flatMap(part => (part._tag === 'Text' ? contentParts(part.content) : []))\n }\n}\n\nconst validateCapabilities = (\n config: RunConfig,\n messages: ReadonlyArray<AgentMessage>\n): Effect.Effect<void, LLMError> => {\n const capabilities = config.capabilities\n\n if (capabilities === undefined) {\n return Effect.void\n }\n\n if (!capabilities.tools && config.tools.length > 0) {\n return Effect.fail(unsupportedInputError('Tools are not supported by this model'))\n }\n\n if (!capabilities.reasoning && config.reasoningEffort !== undefined) {\n return Effect.fail(unsupportedInputError('Reasoning effort is not supported by this model'))\n }\n\n return Effect.forEach(messages, message => validateContent(message, capabilities)).pipe(\n Effect.asVoid\n )\n}\n\nconst toLlmEvent = (event: LLMEvent): ReadonlyArray<AgentEvent> => {\n switch (event._tag) {\n case 'TextDelta':\n return [AgentLLMTextDelta.make({ text: event.text })]\n case 'ReasoningDelta':\n return [AgentLLMReasoningDelta.make({ text: event.text })]\n case 'ToolCall':\n return [ToolInputEnd.make({ call: event.call })]\n case 'ToolInputStart':\n return [ToolInputStart.make({ id: event.id, name: event.name })]\n case 'ToolInputDelta':\n return [ToolInputDelta.make({ id: event.id, delta: event.delta })]\n case 'ProviderToolResult':\n return [ProviderToolResult.make({ call: event.call, result: event.result })]\n case 'Usage':\n return [UsageUpdate.make({ usage: event.usage })]\n case 'Done':\n return []\n }\n}\n\nconst isLlmEvent = (event: LLMEvent | AgentEvent | AgentRetry): event is LLMEvent => {\n switch (event._tag) {\n case 'TextDelta':\n case 'ReasoningDelta':\n case 'Done':\n case 'ToolCall':\n case 'ToolInputStart':\n case 'ToolInputDelta':\n case 'ProviderToolResult':\n case 'Usage':\n return true\n default:\n return false\n }\n}\n\ntype TurnStreamInput = {\n readonly config: RunConfig\n readonly contextTransformer: {\n readonly transform: (\n messages: ReadonlyArray<AgentMessage>\n ) => Effect.Effect<ContextTransformResult, AgentLoopError>\n }\n readonly loopConfig: LoopConfigShape\n readonly provider: {\n readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMProviderError>\n }\n readonly executor: {\n readonly execute: (call: ToolCall) => Effect.Effect<ToolResult, ToolError>\n }\n readonly currentMessages: ReadonlyArray<AgentMessage>\n readonly createdMessages: Ref.Ref<ReadonlyArray<AgentMessage>>\n readonly usage: Ref.Ref<AgentUsage>\n readonly turn: number\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number) =>\n Math.max(0, Math.floor(baseDelayMs * 2 ** Math.max(0, attempt - 1)))\n\nconst retryReason = (error: LLMError): AgentErrorCode => error.cause\n\nconst retrySleep = (delayMs: number) =>\n delayMs === 0 ? Effect.void : Effect.sleep(`${delayMs} millis`)\n\nconst failAgentLoopError = (\n error: AgentLoopError\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> => Stream.fail(error)\n\nconst sleepStream = (delayMs: number): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.fromEffect(retrySleep(delayMs)).pipe(Stream.flatMap(() => Stream.empty))\n\nconst withProviderRetries = (\n stream: Stream.Stream<LLMEvent, LLMProviderError>,\n loopConfig: TurnStreamInput['loopConfig'],\n makeStream: () => Stream.Stream<LLMEvent, LLMProviderError>,\n attempt: number\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.unwrap(\n Ref.make(false).pipe(\n Effect.map(emittedProviderEvent =>\n stream.pipe(\n Stream.tap(() => Ref.set(emittedProviderEvent, true)),\n Stream.catchTags({\n LLMError: error =>\n Stream.unwrap(\n Ref.get(emittedProviderEvent).pipe(\n Effect.map(emitted => {\n if (\n emitted ||\n !error.retryable ||\n error.cause === 'context_overflow' ||\n attempt > loopConfig.maxRetries\n ) {\n return failAgentLoopError(error)\n }\n\n const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message\n })\n ).pipe(\n Stream.concat(sleepStream(delayMs)),\n Stream.concat(\n withProviderRetries(makeStream(), loopConfig, makeStream, attempt + 1)\n )\n )\n })\n )\n ),\n AbortError: failAgentLoopError,\n FauxExhaustedError: failAgentLoopError\n })\n )\n )\n )\n )\n\nconst makeToolExecutionStream = (\n executor: TurnStreamInput['executor'],\n call: ToolCall,\n model: string\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAtMs = yield* Clock.currentTimeMillis\n const started = subagentStartedEvent({ call, model, startedAtMs })\n const startEvents: ReadonlyArray<AgentEvent> = started === undefined\n ? [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs })]\n : [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs }), started]\n\n return Stream.fromIterable(startEvents).pipe(\n Stream.concat(\n Stream.fromEffect(\n executor.execute(call).pipe(\n Effect.flatMap(result =>\n Clock.currentTimeMillis.pipe(\n Effect.map(endedAtMs => {\n const completed = subagentCompletedEvent({\n call,\n result,\n model,\n startedAtMs,\n endedAtMs\n })\n const toolCompleted = ToolExecutionCompleted.make({\n call,\n result,\n createdAtMs: endedAtMs\n })\n\n return completed === undefined\n ? [toolCompleted]\n : [toolCompleted, completed]\n })\n )\n )\n )\n ).pipe(\n Stream.flatMap(Stream.fromIterable),\n Stream.catchTag('ToolError', error =>\n Stream.fromEffect(Clock.currentTimeMillis).pipe(\n Stream.flatMap(endedAtMs =>\n Stream.make(\n ToolExecutionError.make({\n call,\n message: error.message,\n code: toolErrorCode(error),\n createdAtMs: endedAtMs\n })\n )\n ),\n Stream.concat(Stream.fail(error))\n )\n )\n )\n )\n )\n })\n )\n\ntype IndexedToolResultMessage = {\n readonly index: number\n readonly message: AgentMessage\n}\n\ntype IndexedToolCall = {\n readonly index: number\n readonly call: ToolCall\n}\n\ntype PreparedToolCall =\n | {\n readonly _tag: 'Execute'\n readonly index: number\n readonly call: ToolCall\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Result'\n readonly index: number\n readonly call: ToolCall\n readonly result: ToolResult\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Pending'\n readonly request: HitlRequest\n readonly events: ReadonlyArray<AgentEvent>\n }\n\ntype PreparedToolBatch = {\n readonly callsToExecute: ReadonlyArray<IndexedToolCall>\n readonly resultMessages: ReadonlyArray<IndexedToolResultMessage>\n readonly resultEvents: ReadonlyArray<AgentEvent>\n readonly events: ReadonlyArray<AgentEvent>\n readonly pendingRequests: ReadonlyArray<HitlRequest>\n readonly pendingEvents: ReadonlyArray<AgentEvent>\n}\n\ntype NonEmptyHitlRequests = readonly [HitlRequest, ...Array<HitlRequest>]\n\nconst boundedToolConcurrency = (loopConfig: LoopConfigShape) =>\n Math.max(1, loopConfig.toolConcurrency)\n\nconst toolResultMessageFromResult = (result: ToolResult) =>\n ToolResultMessage.make({\n toolCallId: result.toolCallId,\n content: result.content,\n isError: result.isError,\n structuredContent: result.structuredContent\n })\n\nconst toolDefFor = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n tools.find(tool => tool.name === call.name)\n\nconst approvalRequired = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n toolDefFor(tools, call)?.approval?.mode === 'manual'\n\nconst approvalRequestId = (call: ToolCall) => `approval:${call.id}`\n\nconst questionRequestId = (call: ToolCall) => `question:${call.id}`\n\nconst matchesApproval = (response: ToolApprovalResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === approvalRequestId(call)\n\nconst matchesQuestion = (response: QuestionResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === questionRequestId(call)\n\nconst approvalResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'ToolApprovalResponse' && matchesApproval(response, call) ? [response] : []\n )[0]\n\nconst questionResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'QuestionResponse' && matchesQuestion(response, call) ? [response] : []\n )[0]\n\nconst toolApprovalRequest = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall\n): ToolApprovalRequest =>\n ToolApprovalRequest.make({\n requestId: approvalRequestId(call),\n toolCallId: call.id,\n call,\n policy: toolDefFor(tools, call)?.approval\n })\n\nconst deniedToolResult = (call: ToolCall, response: ToolApprovalResponse) => {\n const reason = response.reason ?? 'Denied by user'\n\n return ToolResult.make({\n toolCallId: call.id,\n content: `Tool call denied: ${reason}`,\n isError: true,\n structuredContent: {\n type: 'tool_approval_denied',\n reason,\n source: response.source\n }\n })\n}\n\nconst questionToolResult = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt>\n) => {\n return ToolResult.make({\n toolCallId: response.toolCallId,\n content: formatQuestionResponseContent(response, questions),\n isError: response.outcome === 'cancelled' ? true : undefined,\n structuredContent: {\n type: 'question_response',\n outcome: response.outcome,\n answers: response.answers ?? [],\n reason: response.reason,\n source: response.source\n }\n })\n}\n\nconst invalidQuestionToolResult = (call: ToolCall) =>\n ToolResult.make({\n toolCallId: call.id,\n content: 'Invalid question arguments.',\n isError: true,\n structuredContent: { type: 'question_invalid' }\n })\n\nconst prepareQuestionCall = (\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): Effect.Effect<PreparedToolCall> =>\n Effect.gen(function* () {\n const decoded = yield* Schema.decodeUnknownEffect(QuestionToolParams)(call.params).pipe(\n Effect.result\n )\n\n if (decoded._tag === 'Failure') {\n return {\n _tag: 'Result',\n index,\n call,\n result: invalidQuestionToolResult(call),\n events: []\n }\n }\n\n const response = questionResponseFor(responses, call)\n\n if (response !== undefined) {\n return {\n _tag: 'Result',\n index,\n call,\n result: questionToolResult(response, decoded.success.questions),\n events: [\n response.outcome === 'answered'\n ? QuestionAnswered.make({ response })\n : QuestionCancelled.make({ response })\n ]\n }\n }\n\n const request = QuestionRequest.make({\n requestId: questionRequestId(call),\n toolCallId: call.id,\n call,\n questions: decoded.success.questions\n })\n\n return {\n _tag: 'Pending',\n request,\n events: [QuestionRequested.make({ request })]\n }\n })\n\nconst prepareApprovalCall = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): PreparedToolCall => {\n if (!approvalRequired(tools, call)) {\n return { _tag: 'Execute', index, call, events: [] }\n }\n\n const request = toolApprovalRequest(tools, call)\n const response = approvalResponseFor(responses, call)\n\n if (response === undefined) {\n return {\n _tag: 'Pending',\n request,\n events: [ToolApprovalRequested.make({ call, request })]\n }\n }\n\n if (response.decision === 'denied') {\n return {\n _tag: 'Result',\n index,\n call,\n result: deniedToolResult(call, response),\n events: [ToolApprovalDenied.make({ toolCallId: call.id, reason: response.reason ?? 'Denied by user', response })]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [ToolApprovalGranted.make({ toolCallId: call.id, response })]\n }\n}\n\nconst prepareToolCall = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly call: ToolCall\n readonly index: number\n}): Effect.Effect<PreparedToolCall> =>\n input.call.name === questionToolName\n ? prepareQuestionCall(input.call, input.index, input.responses)\n : Effect.succeed(prepareApprovalCall(input.tools, input.call, input.index, input.responses))\n\nconst prepareToolBatch = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly calls: ReadonlyArray<ToolCall>\n}): Effect.Effect<PreparedToolBatch> =>\n Effect.gen(function* () {\n const prepared = yield* Effect.forEach(input.calls, (call, index) =>\n prepareToolCall({ tools: input.tools, responses: input.responses, call, index })\n )\n\n return {\n callsToExecute: prepared.flatMap(item =>\n item._tag === 'Execute' ? [{ index: item.index, call: item.call }] : []\n ),\n resultMessages: prepared.flatMap(item =>\n item._tag === 'Result'\n ? [{ index: item.index, message: toolResultMessageFromResult(item.result) }]\n : []\n ),\n resultEvents: syntheticToolCompletionEvents(prepared),\n events: prepared.flatMap(item => (item._tag === 'Pending' ? [] : item.events)),\n pendingRequests: prepared.flatMap(item => (item._tag === 'Pending' ? [item.request] : [])),\n pendingEvents: prepared.flatMap(item => (item._tag === 'Pending' ? item.events : []))\n }\n })\n\nconst orderedToolResultMessages = (results: ReadonlyArray<IndexedToolResultMessage>) =>\n [...results].sort((left, right) => left.index - right.index).map(result => result.message)\n\nconst syntheticToolCompletionEvents = (\n prepared: ReadonlyArray<PreparedToolCall>\n): ReadonlyArray<AgentEvent> =>\n prepared.flatMap(item =>\n item._tag === 'Result'\n ? [ToolExecutionCompleted.make({ call: item.call, result: item.result })]\n : []\n )\n\nconst toolResultIds = (messages: ReadonlyArray<AgentMessage>): ReadonlySet<string> =>\n new Set(messages.flatMap(message => (message._tag === 'ToolResult' ? [message.toolCallId] : [])))\n\nconst pendingHostToolCalls = (messages: ReadonlyArray<AgentMessage>) => {\n const completed = toolResultIds(messages)\n\n return messages.flatMap(message =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).filter(call => !completed.has(call.id))\n : []\n )\n}\n\nconst nonEmptyHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): NonEmptyHitlRequests | undefined => {\n const first = requests[0]\n\n return first === undefined ? undefined : [first, ...requests.slice(1)]\n}\n\nconst parallelToolExecutionStream = (input: {\n readonly calls: ReadonlyArray<IndexedToolCall>\n readonly executor: TurnStreamInput['executor']\n readonly loopConfig: LoopConfigShape\n readonly model: string\n readonly results: Ref.Ref<ReadonlyArray<IndexedToolResultMessage>>\n}) =>\n Stream.mergeAll(\n input.calls.map(({ call, index }) =>\n makeToolExecutionStream(input.executor, call, input.model).pipe(\n Stream.tap(event => {\n if (event._tag !== 'ToolExecutionCompleted') {\n return Effect.void\n }\n\n return Ref.update(input.results, results => [\n ...results,\n { index, message: toolResultMessageFromResult(event.result) }\n ])\n })\n )\n ),\n { concurrency: boundedToolConcurrency(input.loopConfig) }\n )\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\ntype TurnCompletion = {\n readonly toolCalls: ReadonlyArray<ToolCall>\n readonly stopReason: 'stop' | 'tool_use'\n}\n\nconst validateTurnCompletion = (\n events: ReadonlyArray<LLMEvent>\n): Effect.Effect<TurnCompletion, LLMError> => {\n const doneEvents = events.filter(event => event._tag === 'Done')\n const toolCalls = collectToolCalls(events)\n const stopReason: TurnCompletion['stopReason'] = toolCalls.length === 0 ? 'stop' : 'tool_use'\n\n if (doneEvents.length !== 1) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `Expected exactly one LLM done event, received ${doneEvents.length}`,\n retryable: false\n })\n )\n }\n\n const doneEvent = doneEvents[0]\n\n if (doneEvent === undefined || doneEvent.stopReason !== stopReason) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `LLM done reason must be ${stopReason}`,\n retryable: false\n })\n )\n }\n\n return Effect.succeed({ toolCalls, stopReason })\n}\n\nconst makeAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n const turnEndEvents: ReadonlyArray<AgentEvent> = [\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage })\n ]\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n if (completion.toolCalls.length === 0) {\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentEnd.make({\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: completion.toolCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n ...prepared.events,\n ...prepared.pendingEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n Stream.make(TurnEnd.make({ turn: input.turn, reason: completion.stopReason })).pipe(\n Stream.concat(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, assistantMessage, ...orderedResults],\n turn: input.turn + 1\n })\n )\n )\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(turnEndEvents).pipe(\n Stream.concat(Stream.fromIterable(prepared.events)),\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst makeModelOnlyAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n return Stream.fromIterable([\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage }),\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason })\n ])\n })\n )\n\nconst makeLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeModelOnlyLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeModelOnlyAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeTurnStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nconst makePendingToolResumeStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const pendingCalls = pendingHostToolCalls(input.currentMessages)\n\n if (pendingCalls.length === 0 || (input.config.hitlResponses ?? []).length === 0) {\n return makeTurnStream(input)\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: pendingCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...prepared.events,\n ...prepared.pendingEvents,\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: Math.max(0, input.turn - 1),\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, ...orderedResults]\n })\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(prepared.events).pipe(\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst unavailableToolExecutor: TurnStreamInput['executor'] = {\n execute: call =>\n Effect.fail(\n new ToolError({\n tool: call.name,\n message: 'Tool execution is not available in model turn step',\n cause: 'execution'\n })\n )\n}\n\nconst makeModelOnlyTurnStream = (\n input: TurnStreamInput\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeModelOnlyLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nexport const runModelTurn = (\n config: ModelTurnConfig\n): Stream.Stream<AgentEvent, AgentLoopError, ContextTransformer | LLMProvider | LoopConfig> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return makeModelOnlyTurnStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor: unavailableToolExecutor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: config.turn\n })\n })\n )\n\nexport const runToolBatch = (\n config: ToolBatchConfig\n): Stream.Stream<AgentEvent, AgentLoopError, LoopConfig | ToolExecutor> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const executor = yield* ToolExecutor\n const loopConfig = yield* LoopConfig\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: config.tools ?? [],\n responses: config.hitlResponses ?? [],\n calls: config.calls\n })\n const hasPendingRequests = prepared.pendingRequests.length > 0\n const resultEvents = hasPendingRequests ? [] : prepared.resultEvents\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n const awaitingEvents: ReadonlyArray<AgentEvent> = pendingRequests === undefined\n ? []\n : [\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages: config.createdMessages ?? [],\n turns: config.turn ?? 0,\n usage: config.usage ?? zeroAgentUsage\n })\n ]\n\n return Stream.fromIterable([\n ...prepared.events,\n ...resultEvents,\n ...prepared.pendingEvents,\n ...awaitingEvents\n ]).pipe(\n Stream.concat(\n parallelToolExecutionStream({\n calls: hasPendingRequests ? [] : prepared.callsToExecute,\n executor,\n loopConfig,\n model: config.model ?? '',\n results: toolResultMessages\n })\n )\n )\n })\n )\n\nexport const run = (\n config: RunConfig\n): Stream.Stream<\n AgentEvent,\n AgentLoopError,\n ContextTransformer | LLMProvider | LoopConfig | ToolExecutor\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const executor = yield* ToolExecutor\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return Stream.make(AgentStart.make({})).pipe(\n Stream.concat(\n makePendingToolResumeStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: 1\n })\n )\n )\n })\n )\n"],"mappings":";;;;;;;;;;AAgGA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAAW,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAAQ,KAAA;AAErG,MAAM,uBAAuB,OAAgB,QAAgB;CAC3D,MAAM,QAAQ,YAAY,OAAO,GAAG;CAEpC,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ,KAAA;AACxE;AAEA,MAAM,oBAAoB,SAAiD;CACzE,IAAI,KAAK,SAAS,QAChB;CAGF,MAAM,eAAe,oBAAoB,KAAK,QAAQ,eAAe;CACrE,MAAM,cAAc,oBAAoB,KAAK,QAAQ,aAAa;CAElE,IAAI,iBAAiB,KAAA,KAAa,gBAAgB,KAAA,GAChD;CAGF,OAAO;EACL,eAAe,kBAAkB,KAAK,EAAE;EACxC;EACA;CACF;AACF;AAEA,MAAM,wBAAwB,UAIxB;CACJ,MAAM,WAAW,iBAAiB,MAAM,IAAI;CAE5C,OAAO,aAAa,KAAA,IAChB,KAAA,IACA,gBAAgB,KAAK;EACnB,kBAAkB,MAAM,KAAK;EAC7B,eAAe,SAAS;EACxB,cAAc,SAAS;EACvB,aAAa,SAAS;EACtB,OAAO,MAAM;EACb,aAAa,MAAM;CACrB,CAAC;AACP;AAEA,MAAM,0BAA0B,UAM1B;CACJ,MAAM,WAAW,iBAAiB,MAAM,IAAI;CAE5C,OAAO,aAAa,KAAA,IAChB,KAAA,IACA,kBAAkB,KAAK;EACrB,kBAAkB,MAAM,KAAK;EAC7B,eAAe,SAAS;EACxB,cAAc,SAAS;EACvB,aAAa,SAAS;EACtB,OAAO,MAAM;EACb,QAAQ,MAAM,OAAO,YAAY,OAAO,UAAU;EAClD,YAAY,KAAK,IAAI,GAAG,MAAM,YAAY,MAA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H;AAEF,MAAa,OACX,WAMA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,qBAAqB,OAAO;CAClC,MAAM,aAAa,OAAO;CAC1B,MAAM,WAAW,OAAO;CACxB,MAAM,WAAW,OAAO;CACxB,MAAM,kBAAkB,OAAO,IAAI,KAAkC,CAAC,CAAC;CACvE,MAAM,QAAQ,OAAO,IAAI,KAAK,cAAc;CAE5C,OAAO,OAAO,KAAK,WAAW,KAAK,CAAC,CAAC,CAAC,EAAE,KACtC,OAAO,OACL,4BAA4B;EAC1B;EACA;EACA;EACA;EACA;EACA,iBAAiB,OAAO;EACxB;EACA;EACA,MAAM;CACR,CAAC,CACH,CACF;AACF,CAAC,CACH"}
@@ -4,6 +4,7 @@ import * as Schema from "effect/Schema";
4
4
  declare const AgentContentCapabilities_base: Schema.Class<AgentContentCapabilities, Schema.Struct<{
5
5
  readonly text: Schema.Boolean;
6
6
  readonly image: Schema.Boolean;
7
+ readonly document: Schema.Boolean;
7
8
  readonly audio: Schema.Boolean;
8
9
  }>, {}>;
9
10
  declare class AgentContentCapabilities extends AgentContentCapabilities_base {}
@@ -15,6 +16,7 @@ declare const AgentModelCapabilities_base: Schema.Class<AgentModelCapabilities,
15
16
  declare class AgentModelCapabilities extends AgentModelCapabilities_base {}
16
17
  declare const textOnlyModelCapabilities: AgentModelCapabilities;
17
18
  declare const textImageModelCapabilities: AgentModelCapabilities;
19
+ declare const textImageDocumentModelCapabilities: AgentModelCapabilities;
18
20
  //#endregion
19
- export { AgentContentCapabilities, AgentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities };
21
+ export { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities };
20
22
  //# sourceMappingURL=capability.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.mts","names":[],"sources":["../../src/protocol/capability.ts"],"mappings":";;;cAAuC,6BAAA;;;;;cAE1B,wBAAA,SAAiC,6BAM5C;AAAA,cAAG,2BAAA;;;;;cAEQ,sBAAA,SAA+B,2BAM1C;AAAA,cAEW,yBAAA,EAAyB,sBAIpC;AAAA,cAEW,0BAAA,EAA0B,sBAIrC"}
1
+ {"version":3,"file":"capability.d.mts","names":[],"sources":["../../src/protocol/capability.ts"],"mappings":";;;cAAuC,6BAAA;;;;;;cAE1B,wBAAA,SAAiC,6BAO5C;AAAA,cAAG,2BAAA;;;;;cAEQ,sBAAA,SAA+B,2BAM1C;AAAA,cAEW,yBAAA,EAAyB,sBAIpC;AAAA,cAEW,0BAAA,EAA0B,sBAIrC;AAAA,cAEW,kCAAA,EAAkC,sBAI7C"}
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
3
3
  var AgentContentCapabilities = class extends Schema.Class("AgentContentCapabilities")({
4
4
  text: Schema.Boolean,
5
5
  image: Schema.Boolean,
6
+ document: Schema.Boolean,
6
7
  audio: Schema.Boolean
7
8
  }) {};
8
9
  var AgentModelCapabilities = class extends Schema.Class("AgentModelCapabilities")({
@@ -14,6 +15,7 @@ const textOnlyModelCapabilities = AgentModelCapabilities.make({
14
15
  input: AgentContentCapabilities.make({
15
16
  text: true,
16
17
  image: false,
18
+ document: false,
17
19
  audio: false
18
20
  }),
19
21
  tools: true,
@@ -23,12 +25,23 @@ const textImageModelCapabilities = AgentModelCapabilities.make({
23
25
  input: AgentContentCapabilities.make({
24
26
  text: true,
25
27
  image: true,
28
+ document: false,
29
+ audio: false
30
+ }),
31
+ tools: true,
32
+ reasoning: true
33
+ });
34
+ const textImageDocumentModelCapabilities = AgentModelCapabilities.make({
35
+ input: AgentContentCapabilities.make({
36
+ text: true,
37
+ image: true,
38
+ document: true,
26
39
  audio: false
27
40
  }),
28
41
  tools: true,
29
42
  reasoning: true
30
43
  });
31
44
  //#endregion
32
- export { AgentContentCapabilities, AgentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities };
45
+ export { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities };
33
46
 
34
47
  //# sourceMappingURL=capability.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"capability.mjs","names":[],"sources":["../../src/protocol/capability.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\n\nexport class AgentContentCapabilities extends Schema.Class<AgentContentCapabilities>(\n 'AgentContentCapabilities'\n)({\n text: Schema.Boolean,\n image: Schema.Boolean,\n audio: Schema.Boolean\n}) {}\n\nexport class AgentModelCapabilities extends Schema.Class<AgentModelCapabilities>(\n 'AgentModelCapabilities'\n)({\n input: AgentContentCapabilities,\n tools: Schema.Boolean,\n reasoning: Schema.Boolean\n}) {}\n\nexport const textOnlyModelCapabilities = AgentModelCapabilities.make({\n input: AgentContentCapabilities.make({ text: true, image: false, audio: false }),\n tools: true,\n reasoning: true\n})\n\nexport const textImageModelCapabilities = AgentModelCapabilities.make({\n input: AgentContentCapabilities.make({ text: true, image: true, audio: false }),\n tools: true,\n reasoning: true\n})\n"],"mappings":";;AAEA,IAAa,2BAAb,cAA8C,OAAO,MACnD,0BACF,EAAE;CACA,MAAM,OAAO;CACb,OAAO,OAAO;CACd,OAAO,OAAO;AAChB,CAAC,EAAE,CAAC;AAEJ,IAAa,yBAAb,cAA4C,OAAO,MACjD,wBACF,EAAE;CACA,OAAO;CACP,OAAO,OAAO;CACd,WAAW,OAAO;AACpB,CAAC,EAAE,CAAC;AAEJ,MAAa,4BAA4B,uBAAuB,KAAK;CACnE,OAAO,yBAAyB,KAAK;EAAE,MAAM;EAAM,OAAO;EAAO,OAAO;CAAM,CAAC;CAC/E,OAAO;CACP,WAAW;AACb,CAAC;AAED,MAAa,6BAA6B,uBAAuB,KAAK;CACpE,OAAO,yBAAyB,KAAK;EAAE,MAAM;EAAM,OAAO;EAAM,OAAO;CAAM,CAAC;CAC9E,OAAO;CACP,WAAW;AACb,CAAC"}
1
+ {"version":3,"file":"capability.mjs","names":[],"sources":["../../src/protocol/capability.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\n\nexport class AgentContentCapabilities extends Schema.Class<AgentContentCapabilities>(\n 'AgentContentCapabilities'\n)({\n text: Schema.Boolean,\n image: Schema.Boolean,\n document: Schema.Boolean,\n audio: Schema.Boolean\n}) {}\n\nexport class AgentModelCapabilities extends Schema.Class<AgentModelCapabilities>(\n 'AgentModelCapabilities'\n)({\n input: AgentContentCapabilities,\n tools: Schema.Boolean,\n reasoning: Schema.Boolean\n}) {}\n\nexport const textOnlyModelCapabilities = AgentModelCapabilities.make({\n input: AgentContentCapabilities.make({ text: true, image: false, document: false, audio: false }),\n tools: true,\n reasoning: true\n})\n\nexport const textImageModelCapabilities = AgentModelCapabilities.make({\n input: AgentContentCapabilities.make({ text: true, image: true, document: false, audio: false }),\n tools: true,\n reasoning: true\n})\n\nexport const textImageDocumentModelCapabilities = AgentModelCapabilities.make({\n input: AgentContentCapabilities.make({ text: true, image: true, document: true, audio: false }),\n tools: true,\n reasoning: true\n})\n"],"mappings":";;AAEA,IAAa,2BAAb,cAA8C,OAAO,MACnD,0BACF,EAAE;CACA,MAAM,OAAO;CACb,OAAO,OAAO;CACd,UAAU,OAAO;CACjB,OAAO,OAAO;AAChB,CAAC,EAAE,CAAC;AAEJ,IAAa,yBAAb,cAA4C,OAAO,MACjD,wBACF,EAAE;CACA,OAAO;CACP,OAAO,OAAO;CACd,WAAW,OAAO;AACpB,CAAC,EAAE,CAAC;AAEJ,MAAa,4BAA4B,uBAAuB,KAAK;CACnE,OAAO,yBAAyB,KAAK;EAAE,MAAM;EAAM,OAAO;EAAO,UAAU;EAAO,OAAO;CAAM,CAAC;CAChG,OAAO;CACP,WAAW;AACb,CAAC;AAED,MAAa,6BAA6B,uBAAuB,KAAK;CACpE,OAAO,yBAAyB,KAAK;EAAE,MAAM;EAAM,OAAO;EAAM,UAAU;EAAO,OAAO;CAAM,CAAC;CAC/F,OAAO;CACP,WAAW;AACb,CAAC;AAED,MAAa,qCAAqC,uBAAuB,KAAK;CAC5E,OAAO,yBAAyB,KAAK;EAAE,MAAM;EAAM,OAAO;EAAM,UAAU;EAAM,OAAO;CAAM,CAAC;CAC9F,OAAO;CACP,WAAW;AACb,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { Effect, Option } from "effect";
1
2
  import * as Schema from "effect/Schema";
2
3
 
3
4
  //#region src/protocol/content.d.ts
@@ -5,20 +6,50 @@ declare const TextPart_base: Schema.Class<TextPart, Schema.TaggedStruct<"Text",
5
6
  readonly text: Schema.String;
6
7
  }>, {}>;
7
8
  declare class TextPart extends TextPart_base {}
8
- declare const ImagePart_base: Schema.Class<ImagePart, Schema.TaggedStruct<"Image", {
9
+ declare const InlineBase64AttachmentSource_base: Schema.Class<InlineBase64AttachmentSource, Schema.TaggedStruct<"InlineBase64", {
9
10
  readonly data: Schema.String;
11
+ }>, {}>;
12
+ declare class InlineBase64AttachmentSource extends InlineBase64AttachmentSource_base {}
13
+ declare const UrlAttachmentSource_base: Schema.Class<UrlAttachmentSource, Schema.TaggedStruct<"Url", {
14
+ readonly url: Schema.String;
15
+ }>, {}>;
16
+ declare class UrlAttachmentSource extends UrlAttachmentSource_base {}
17
+ declare const RefAttachmentSource_base: Schema.Class<RefAttachmentSource, Schema.TaggedStruct<"Ref", {
18
+ readonly id: Schema.String;
19
+ }>, {}>;
20
+ declare class RefAttachmentSource extends RefAttachmentSource_base {}
21
+ declare const AttachmentSource: Schema.Union<readonly [typeof InlineBase64AttachmentSource, typeof UrlAttachmentSource, typeof RefAttachmentSource]>;
22
+ type AttachmentSource = typeof AttachmentSource.Type;
23
+ declare const ImagePart_base: Schema.Class<ImagePart, Schema.TaggedStruct<"Image", {
24
+ readonly source: Schema.Union<readonly [typeof InlineBase64AttachmentSource, typeof UrlAttachmentSource, typeof RefAttachmentSource]>;
10
25
  readonly mimeType: Schema.String;
26
+ readonly filename: Schema.optional<Schema.String>;
27
+ readonly title: Schema.optional<Schema.String>;
28
+ readonly width: Schema.optional<Schema.Number>;
29
+ readonly height: Schema.optional<Schema.Number>;
11
30
  }>, {}>;
12
31
  declare class ImagePart extends ImagePart_base {}
32
+ declare const DocumentPart_base: Schema.Class<DocumentPart, Schema.TaggedStruct<"Document", {
33
+ readonly source: Schema.Union<readonly [typeof InlineBase64AttachmentSource, typeof UrlAttachmentSource, typeof RefAttachmentSource]>;
34
+ readonly mimeType: Schema.String;
35
+ readonly filename: Schema.String;
36
+ readonly title: Schema.optional<Schema.String>;
37
+ }>, {}>;
38
+ declare class DocumentPart extends DocumentPart_base {}
13
39
  declare const AudioPart_base: Schema.Class<AudioPart, Schema.TaggedStruct<"Audio", {
14
- readonly data: Schema.String;
15
- readonly format: Schema.Literals<readonly ["pcm16", "wav", "mp3", "opus"]>;
40
+ readonly source: Schema.Union<readonly [typeof InlineBase64AttachmentSource, typeof UrlAttachmentSource, typeof RefAttachmentSource]>;
41
+ readonly mimeType: Schema.String;
42
+ readonly filename: Schema.optional<Schema.String>;
43
+ readonly durationMs: Schema.optional<Schema.Number>;
16
44
  }>, {}>;
17
45
  declare class AudioPart extends AudioPart_base {}
18
- declare const ContentPart: Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>;
46
+ declare const ContentPart: Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>;
19
47
  type ContentPart = typeof ContentPart.Type;
20
- declare const Content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>>]>;
48
+ declare const Content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>>]>;
21
49
  type Content = typeof Content.Type;
50
+ type AttachmentContentPart = ImagePart | DocumentPart | AudioPart;
51
+ type AttachmentSourceResolver<E = never, R = never> = (part: AttachmentContentPart) => Effect.Effect<AttachmentSource, E, R>;
52
+ declare const resolveContentAttachmentSources: <E, R>(content: Content, resolver: AttachmentSourceResolver<E, R>) => Effect.Effect<Content, E, R>;
22
53
  declare const contentPartText: (part: ContentPart) => string;
23
54
  declare const contentPartPreview: (part: ContentPart) => string;
24
55
  declare const contentText: (content: Content) => string;
@@ -26,6 +57,13 @@ declare const contentPreview: (content: Content) => string;
26
57
  declare const contentParts: (content: Content) => ReadonlyArray<ContentPart>;
27
58
  declare const isContentEmpty: (content: Content) => boolean;
28
59
  declare const appendTextToContent: (content: Content, text: string) => Content;
60
+ declare const inlineBase64AttachmentSource: (data: string) => InlineBase64AttachmentSource;
61
+ declare const urlAttachmentSource: (url: string) => UrlAttachmentSource;
62
+ declare const refAttachmentSource: (id: string) => RefAttachmentSource;
63
+ declare const inlineBase64Source: (data: string) => InlineBase64AttachmentSource;
64
+ declare const attachmentSourcePreview: (source: AttachmentSource) => string;
65
+ declare const attachmentSourceDataUrl: (source: AttachmentSource, mimeType: string) => Option.Option<string>;
66
+ declare const attachmentSourceBase64: (source: AttachmentSource) => Option.Option<string>;
29
67
  //#endregion
30
- export { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToContent, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, isContentEmpty };
68
+ export { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, refAttachmentSource, resolveContentAttachmentSources, urlAttachmentSource };
31
69
  //# 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,cAAA;;;;cAEQ,SAAA,SAAkB,cAG7B;AAAA,cAAG,cAAA;;;;cAEQ,SAAA,SAAkB,cAG7B;AAAA,cAEW,WAAA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A,GAA2B,MAAwB,EAAhB,gBAAgB;AAAA,cAWnD,uBAAA,GAA2B,MAAA,EAAQ,gBAAA,EAAkB,QAAA,aAAgB,MAAA,CAAA,MAAA;AAAA,cAUrE,sBAAA,GAA0B,MAAA,EAAQ,gBAAA,KAAgB,MAAA,CAAA,MAAA"}
@@ -1,30 +1,73 @@
1
- import { Array, Option } from "effect";
1
+ import { Array, 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 }) {};
5
+ var InlineBase64AttachmentSource = class extends Schema.TaggedClass()("InlineBase64", { data: Schema.String }) {};
6
+ var UrlAttachmentSource = class extends Schema.TaggedClass()("Url", { url: Schema.String }) {};
7
+ var RefAttachmentSource = class extends Schema.TaggedClass()("Ref", { id: Schema.String }) {};
8
+ const AttachmentSource = Schema.Union([
9
+ InlineBase64AttachmentSource,
10
+ UrlAttachmentSource,
11
+ RefAttachmentSource
12
+ ]);
5
13
  var ImagePart = class extends Schema.TaggedClass()("Image", {
6
- data: Schema.String,
7
- mimeType: Schema.String
14
+ source: AttachmentSource,
15
+ mimeType: Schema.String,
16
+ filename: Schema.optional(Schema.String),
17
+ title: Schema.optional(Schema.String),
18
+ width: Schema.optional(Schema.Number),
19
+ height: Schema.optional(Schema.Number)
20
+ }) {};
21
+ var DocumentPart = class extends Schema.TaggedClass()("Document", {
22
+ source: AttachmentSource,
23
+ mimeType: Schema.String,
24
+ filename: Schema.String,
25
+ title: Schema.optional(Schema.String)
8
26
  }) {};
9
27
  var AudioPart = class extends Schema.TaggedClass()("Audio", {
10
- data: Schema.String,
11
- format: Schema.Literals([
12
- "pcm16",
13
- "wav",
14
- "mp3",
15
- "opus"
16
- ])
28
+ source: AttachmentSource,
29
+ mimeType: Schema.String,
30
+ filename: Schema.optional(Schema.String),
31
+ durationMs: Schema.optional(Schema.Number)
17
32
  }) {};
18
33
  const ContentPart = Schema.Union([
19
34
  TextPart,
20
35
  ImagePart,
36
+ DocumentPart,
21
37
  AudioPart
22
38
  ]);
23
39
  const Content = Schema.Union([Schema.String, Schema.Array(ContentPart)]);
40
+ const resolveContentPartAttachmentSource = (part, resolver) => {
41
+ switch (part._tag) {
42
+ case "Text": return Effect.succeed(part);
43
+ case "Image": return resolver(part).pipe(Effect.map((source) => ImagePart.make({
44
+ source,
45
+ mimeType: part.mimeType,
46
+ filename: part.filename,
47
+ title: part.title,
48
+ width: part.width,
49
+ height: part.height
50
+ })));
51
+ case "Document": return resolver(part).pipe(Effect.map((source) => DocumentPart.make({
52
+ source,
53
+ mimeType: part.mimeType,
54
+ filename: part.filename,
55
+ title: part.title
56
+ })));
57
+ case "Audio": return resolver(part).pipe(Effect.map((source) => AudioPart.make({
58
+ source,
59
+ mimeType: part.mimeType,
60
+ filename: part.filename,
61
+ durationMs: part.durationMs
62
+ })));
63
+ }
64
+ };
65
+ const resolveContentAttachmentSources = (content, resolver) => typeof content === "string" ? Effect.succeed(content) : Effect.forEach(content, (part) => resolveContentPartAttachmentSource(part, resolver));
24
66
  const contentPartText = (part) => {
25
67
  switch (part._tag) {
26
68
  case "Text": return part.text;
27
69
  case "Image":
70
+ case "Document":
28
71
  case "Audio": return "";
29
72
  }
30
73
  };
@@ -32,6 +75,7 @@ const contentPartPreview = (part) => {
32
75
  switch (part._tag) {
33
76
  case "Text": return part.text;
34
77
  case "Image": return "Image";
78
+ case "Document": return `Document: ${part.title ?? part.filename}`;
35
79
  case "Audio": return "Audio";
36
80
  }
37
81
  };
@@ -46,7 +90,32 @@ const appendTextToContent = (content, text) => {
46
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)
47
91
  });
48
92
  };
93
+ const inlineBase64AttachmentSource = (data) => InlineBase64AttachmentSource.make({ data });
94
+ const urlAttachmentSource = (url) => UrlAttachmentSource.make({ url });
95
+ const refAttachmentSource = (id) => RefAttachmentSource.make({ id });
96
+ const inlineBase64Source = inlineBase64AttachmentSource;
97
+ const attachmentSourcePreview = (source) => {
98
+ switch (source._tag) {
99
+ case "InlineBase64": return "inline";
100
+ case "Url": return source.url;
101
+ case "Ref": return source.id;
102
+ }
103
+ };
104
+ const attachmentSourceDataUrl = (source, mimeType) => {
105
+ switch (source._tag) {
106
+ case "InlineBase64": return Option.some(`data:${mimeType};base64,${source.data}`);
107
+ case "Url":
108
+ case "Ref": return Option.none();
109
+ }
110
+ };
111
+ const attachmentSourceBase64 = (source) => {
112
+ switch (source._tag) {
113
+ case "InlineBase64": return Option.some(source.data);
114
+ case "Url":
115
+ case "Ref": return Option.none();
116
+ }
117
+ };
49
118
  //#endregion
50
- export { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToContent, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, isContentEmpty };
119
+ export { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, refAttachmentSource, resolveContentAttachmentSources, urlAttachmentSource };
51
120
 
52
121
  //# sourceMappingURL=content.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"content.mjs","names":["Arr"],"sources":["../../src/protocol/content.ts"],"sourcesContent":["import { Array as Arr, 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 ImagePart extends Schema.TaggedClass<ImagePart>()('Image', {\n data: Schema.String,\n mimeType: Schema.String\n}) {}\n\nexport class AudioPart extends Schema.TaggedClass<AudioPart>()('Audio', {\n data: Schema.String,\n format: Schema.Literals(['pcm16', 'wav', 'mp3', 'opus'])\n}) {}\n\nexport const ContentPart = Schema.Union([TextPart, ImagePart, 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 const contentPartText = (part: ContentPart) => {\n switch (part._tag) {\n case 'Text':\n return part.text\n case 'Image':\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 '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"],"mappings":";;;AAGA,IAAa,WAAb,cAA8B,OAAO,YAAsB,EAAE,QAAQ,EACnE,MAAM,OAAO,OACf,CAAC,EAAE,CAAC;AAEJ,IAAa,YAAb,cAA+B,OAAO,YAAuB,EAAE,SAAS;CACtE,MAAM,OAAO;CACb,UAAU,OAAO;AACnB,CAAC,EAAE,CAAC;AAEJ,IAAa,YAAb,cAA+B,OAAO,YAAuB,EAAE,SAAS;CACtE,MAAM,OAAO;CACb,QAAQ,OAAO,SAAS;EAAC;EAAS;EA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AAK,SAAS,SAC1C,SAAS,KAAK,EAAE,MAAM,GAAG,KAAK,OAAO,OAAO,CAAC,IAC7C,IACN;CACR,CAAC;AACH"}
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 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,CAAC;AAEJ,IAAa,sBAAb,cAAyC,OAAO,YAAiC,EAAE,OAAO,EACxF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AAc,CAAC,SAAS,KAAK,EAAE,KAAK,CAAC,CAAC;EACtC,SAAQ,SACN,KAAK,SAAS,SACV,CAAC,GAAG,SAAS,SAAS,KAAK,EAAE,KAAK,CAAC,CAAC,IACpCA,MAAI,IAAI,UAAU,MAAM,UACtB,UAAU,QAAQ,SAAS,KAAK,KAAK,SAAS,SAC1C,SAAS,KAAK,EAAE,MAAM,GAAG,KAAK,OAAO,OAAO,CAAC,IAC7C,IACN;CACR,CAAC;AACH;AAEA,MAAa,gCAAgC,SAAiB,6BAA6B,KAAK,EAAE,KAAK,CAAC;AAExG,MAAa,uBAAuB,QAAgB,oBAAoB,KAAK,EAAE,IAAI,CAAC;AAEpF,MAAa,uBAAuB,OAAe,oBAAoB,KAAK,EAAE,GAAG,CAAC;AAElF,MAAa,qBAAqB;AAElC,MAAa,2BAA2B,WAA6B;CACnE,QAAQ,OAAO,MAAf;EACE,KAAK,gBACH,OAAO;EACT,KAAK,OACH,OAAO,OAAO;EAChB,KAAK,OACH,OAAO,OAAO;CAClB;AACF;AAEA,MAAa,2BAA2B,QAA0B,aAAqB;CACrF,QAAQ,OAAO,MAAf;EACE,KAAK,gBACH,OAAO,OAAO,KAAK,QAAQ,SAAS,UAAU,OAAO,MAAM;EAC7D,KAAK;EACL,KAAK,OACH,OAAO,OAAO,KAAa;CAC/B;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
- import { AgentContentCapabilities, AgentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
2
- import { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToContent, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, isContentEmpty } from "./content.mjs";
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, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, refAttachmentSource, resolveContentAttachmentSources, 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 } from "./tool.mjs";
4
4
  import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText } 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, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageId, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, 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, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, makeSubagentRunId, textImageModelCapabilities, textOnlyModelCapabilities, 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, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageId, 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, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, makeSubagentRunId, refAttachmentSource, resolveContentAttachmentSources, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, urlAttachmentSource, zeroAgentUsage };
14
14
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KA6GY,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KA6HY,SAAA"}
@@ -1,9 +1,9 @@
1
- import { AgentContentCapabilities, AgentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
2
- import { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToContent, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, isContentEmpty } from "./content.mjs";
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, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, refAttachmentSource, resolveContentAttachmentSources, 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 } from "./tool.mjs";
4
4
  import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText } 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, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, 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, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, 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, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, makeSubagentRunId, textImageModelCapabilities, textOnlyModelCapabilities, 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, 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, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, makeSubagentRunId, refAttachmentSource, resolveContentAttachmentSources, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, urlAttachmentSource, zeroAgentUsage };
@@ -1,14 +1,14 @@
1
- import { AudioPart, Content, ImagePart, TextPart } from "./content.mjs";
1
+ import { AudioPart, Content, DocumentPart, ImagePart, TextPart } from "./content.mjs";
2
2
  import { ToolCall, ToolResult } from "./tool.mjs";
3
3
  import * as Schema from "effect/Schema";
4
4
 
5
5
  //#region src/protocol/message.d.ts
6
6
  declare const UserMessage_base: Schema.Class<UserMessage, Schema.TaggedStruct<"User", {
7
- readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>>]>;
7
+ readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>>]>;
8
8
  }>, {}>;
9
9
  declare class UserMessage extends UserMessage_base {}
10
10
  declare const AssistantTextPart_base: Schema.Class<AssistantTextPart, Schema.TaggedStruct<"Text", {
11
- readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>>]>;
11
+ readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>>]>;
12
12
  }>, {}>;
13
13
  declare class AssistantTextPart extends AssistantTextPart_base {}
14
14
  declare const AssistantReasoningPart_base: Schema.Class<AssistantReasoningPart, Schema.TaggedStruct<"Reasoning", {
@@ -38,7 +38,7 @@ declare const AssistantAgentMessage_base: Schema.Class<AssistantAgentMessage, Sc
38
38
  declare class AssistantAgentMessage extends AssistantAgentMessage_base {}
39
39
  declare const ToolResultMessage_base: Schema.Class<ToolResultMessage, Schema.TaggedStruct<"ToolResult", {
40
40
  readonly toolCallId: Schema.String;
41
- readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>>]>;
41
+ readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>>]>;
42
42
  readonly isError: Schema.optional<Schema.Boolean>;
43
43
  readonly structuredContent: Schema.optional<Schema.Unknown>;
44
44
  }>, {}>;
@@ -1,4 +1,4 @@
1
- import { AudioPart, ImagePart, TextPart } from "./content.mjs";
1
+ import { AudioPart, DocumentPart, ImagePart, TextPart } from "./content.mjs";
2
2
  import * as Schema from "effect/Schema";
3
3
 
4
4
  //#region src/protocol/tool.d.ts
@@ -28,7 +28,7 @@ declare const ToolDef_base: Schema.Class<ToolDef, Schema.Struct<{
28
28
  declare class ToolDef extends ToolDef_base {}
29
29
  declare const ToolResult_base: Schema.Class<ToolResult, Schema.Struct<{
30
30
  readonly toolCallId: Schema.Trimmed;
31
- readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof AudioPart]>>]>;
31
+ readonly content: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.Union<readonly [typeof TextPart, typeof ImagePart, typeof DocumentPart, typeof AudioPart]>>]>;
32
32
  readonly isError: Schema.optional<Schema.Boolean>;
33
33
  readonly structuredContent: Schema.optional<Schema.Unknown>;
34
34
  }>, {}>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk-sdk/agent",
3
- "version": "0.0.1-canary.7",
3
+ "version": "0.0.1-canary.9",
4
4
  "description": "Protocol, loop, runtime, client, and tool primitives for building Yolk agents.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/loop/run.ts CHANGED
@@ -191,6 +191,10 @@ const validateContent = (message: AgentMessage, capabilities: AgentModelCapabili
191
191
  return capabilities.input.image
192
192
  ? Effect.void
193
193
  : Effect.fail(unsupportedInputError('Image input is not supported by this model'))
194
+ case 'Document':
195
+ return capabilities.input.document
196
+ ? Effect.void
197
+ : Effect.fail(unsupportedInputError('Document input is not supported by this model'))
194
198
  case 'Audio':
195
199
  return capabilities.input.audio
196
200
  ? Effect.void
@@ -5,6 +5,7 @@ export class AgentContentCapabilities extends Schema.Class<AgentContentCapabilit
5
5
  )({
6
6
  text: Schema.Boolean,
7
7
  image: Schema.Boolean,
8
+ document: Schema.Boolean,
8
9
  audio: Schema.Boolean
9
10
  }) {}
10
11
 
@@ -17,13 +18,19 @@ export class AgentModelCapabilities extends Schema.Class<AgentModelCapabilities>
17
18
  }) {}
18
19
 
19
20
  export const textOnlyModelCapabilities = AgentModelCapabilities.make({
20
- input: AgentContentCapabilities.make({ text: true, image: false, audio: false }),
21
+ input: AgentContentCapabilities.make({ text: true, image: false, document: false, audio: false }),
21
22
  tools: true,
22
23
  reasoning: true
23
24
  })
24
25
 
25
26
  export const textImageModelCapabilities = AgentModelCapabilities.make({
26
- input: AgentContentCapabilities.make({ text: true, image: true, audio: false }),
27
+ input: AgentContentCapabilities.make({ text: true, image: true, document: false, audio: false }),
28
+ tools: true,
29
+ reasoning: true
30
+ })
31
+
32
+ export const textImageDocumentModelCapabilities = AgentModelCapabilities.make({
33
+ input: AgentContentCapabilities.make({ text: true, image: true, document: true, audio: false }),
27
34
  tools: true,
28
35
  reasoning: true
29
36
  })
@@ -1,31 +1,126 @@
1
- import { Array as Arr, Option } from 'effect'
1
+ import { Array as Arr, Effect, Option } from 'effect'
2
2
  import * as Schema from 'effect/Schema'
3
3
 
4
4
  export class TextPart extends Schema.TaggedClass<TextPart>()('Text', {
5
5
  text: Schema.String
6
6
  }) {}
7
7
 
8
+ export class InlineBase64AttachmentSource extends Schema.TaggedClass<InlineBase64AttachmentSource>()(
9
+ 'InlineBase64',
10
+ {
11
+ data: Schema.String
12
+ }
13
+ ) {}
14
+
15
+ export class UrlAttachmentSource extends Schema.TaggedClass<UrlAttachmentSource>()('Url', {
16
+ url: Schema.String
17
+ }) {}
18
+
19
+ export class RefAttachmentSource extends Schema.TaggedClass<RefAttachmentSource>()('Ref', {
20
+ id: Schema.String
21
+ }) {}
22
+
23
+ export const AttachmentSource = Schema.Union([
24
+ InlineBase64AttachmentSource,
25
+ UrlAttachmentSource,
26
+ RefAttachmentSource
27
+ ])
28
+ export type AttachmentSource = typeof AttachmentSource.Type
29
+
8
30
  export class ImagePart extends Schema.TaggedClass<ImagePart>()('Image', {
9
- data: Schema.String,
10
- mimeType: Schema.String
31
+ source: AttachmentSource,
32
+ mimeType: Schema.String,
33
+ filename: Schema.optional(Schema.String),
34
+ title: Schema.optional(Schema.String),
35
+ width: Schema.optional(Schema.Number),
36
+ height: Schema.optional(Schema.Number)
37
+ }) {}
38
+
39
+ export class DocumentPart extends Schema.TaggedClass<DocumentPart>()('Document', {
40
+ source: AttachmentSource,
41
+ mimeType: Schema.String,
42
+ filename: Schema.String,
43
+ title: Schema.optional(Schema.String)
11
44
  }) {}
12
45
 
13
46
  export class AudioPart extends Schema.TaggedClass<AudioPart>()('Audio', {
14
- data: Schema.String,
15
- format: Schema.Literals(['pcm16', 'wav', 'mp3', 'opus'])
47
+ source: AttachmentSource,
48
+ mimeType: Schema.String,
49
+ filename: Schema.optional(Schema.String),
50
+ durationMs: Schema.optional(Schema.Number)
16
51
  }) {}
17
52
 
18
- export const ContentPart = Schema.Union([TextPart, ImagePart, AudioPart])
53
+ export const ContentPart = Schema.Union([TextPart, ImagePart, DocumentPart, AudioPart])
19
54
  export type ContentPart = typeof ContentPart.Type
20
55
 
21
56
  export const Content = Schema.Union([Schema.String, Schema.Array(ContentPart)])
22
57
  export type Content = typeof Content.Type
23
58
 
59
+ export type AttachmentContentPart = ImagePart | DocumentPart | AudioPart
60
+
61
+ export type AttachmentSourceResolver<E = never, R = never> = (
62
+ part: AttachmentContentPart
63
+ ) => Effect.Effect<AttachmentSource, E, R>
64
+
65
+ const resolveContentPartAttachmentSource = <E, R>(
66
+ part: ContentPart,
67
+ resolver: AttachmentSourceResolver<E, R>
68
+ ): Effect.Effect<ContentPart, E, R> => {
69
+ switch (part._tag) {
70
+ case 'Text':
71
+ return Effect.succeed(part)
72
+ case 'Image':
73
+ return resolver(part).pipe(
74
+ Effect.map(source =>
75
+ ImagePart.make({
76
+ source,
77
+ mimeType: part.mimeType,
78
+ filename: part.filename,
79
+ title: part.title,
80
+ width: part.width,
81
+ height: part.height
82
+ })
83
+ )
84
+ )
85
+ case 'Document':
86
+ return resolver(part).pipe(
87
+ Effect.map(source =>
88
+ DocumentPart.make({
89
+ source,
90
+ mimeType: part.mimeType,
91
+ filename: part.filename,
92
+ title: part.title
93
+ })
94
+ )
95
+ )
96
+ case 'Audio':
97
+ return resolver(part).pipe(
98
+ Effect.map(source =>
99
+ AudioPart.make({
100
+ source,
101
+ mimeType: part.mimeType,
102
+ filename: part.filename,
103
+ durationMs: part.durationMs
104
+ })
105
+ )
106
+ )
107
+ }
108
+ }
109
+
110
+ export const resolveContentAttachmentSources = <E, R>(
111
+ content: Content,
112
+ resolver: AttachmentSourceResolver<E, R>
113
+ ): Effect.Effect<Content, E, R> =>
114
+ typeof content === 'string'
115
+ ? Effect.succeed(content)
116
+ : Effect.forEach(content, part => resolveContentPartAttachmentSource(part, resolver))
117
+
24
118
  export const contentPartText = (part: ContentPart) => {
25
119
  switch (part._tag) {
26
120
  case 'Text':
27
121
  return part.text
28
122
  case 'Image':
123
+ case 'Document':
29
124
  case 'Audio':
30
125
  return ''
31
126
  }
@@ -37,6 +132,8 @@ export const contentPartPreview = (part: ContentPart) => {
37
132
  return part.text
38
133
  case 'Image':
39
134
  return 'Image'
135
+ case 'Document':
136
+ return `Document: ${part.title ?? part.filename}`
40
137
  case 'Audio':
41
138
  return 'Audio'
42
139
  }
@@ -74,3 +171,42 @@ export const appendTextToContent = (content: Content, text: string): Content =>
74
171
  )
75
172
  })
76
173
  }
174
+
175
+ export const inlineBase64AttachmentSource = (data: string) => InlineBase64AttachmentSource.make({ data })
176
+
177
+ export const urlAttachmentSource = (url: string) => UrlAttachmentSource.make({ url })
178
+
179
+ export const refAttachmentSource = (id: string) => RefAttachmentSource.make({ id })
180
+
181
+ export const inlineBase64Source = inlineBase64AttachmentSource
182
+
183
+ export const attachmentSourcePreview = (source: AttachmentSource) => {
184
+ switch (source._tag) {
185
+ case 'InlineBase64':
186
+ return 'inline'
187
+ case 'Url':
188
+ return source.url
189
+ case 'Ref':
190
+ return source.id
191
+ }
192
+ }
193
+
194
+ export const attachmentSourceDataUrl = (source: AttachmentSource, mimeType: string) => {
195
+ switch (source._tag) {
196
+ case 'InlineBase64':
197
+ return Option.some(`data:${mimeType};base64,${source.data}`)
198
+ case 'Url':
199
+ case 'Ref':
200
+ return Option.none<string>()
201
+ }
202
+ }
203
+
204
+ export const attachmentSourceBase64 = (source: AttachmentSource) => {
205
+ switch (source._tag) {
206
+ case 'InlineBase64':
207
+ return Option.some(source.data)
208
+ case 'Url':
209
+ case 'Ref':
210
+ return Option.none<string>()
211
+ }
212
+ }
@@ -1,11 +1,18 @@
1
1
  export {
2
2
  AgentContentCapabilities,
3
3
  AgentModelCapabilities,
4
+ textImageDocumentModelCapabilities,
4
5
  textImageModelCapabilities,
5
6
  textOnlyModelCapabilities
6
7
  } from './capability.ts'
7
8
  export {
8
9
  appendTextToContent,
10
+ attachmentSourceBase64,
11
+ attachmentSourceDataUrl,
12
+ AttachmentSource,
13
+ type AttachmentContentPart,
14
+ type AttachmentSourceResolver,
15
+ attachmentSourcePreview,
9
16
  AudioPart,
10
17
  Content,
11
18
  ContentPart,
@@ -14,8 +21,17 @@ export {
14
21
  contentPartText,
15
22
  contentPreview,
16
23
  contentText,
24
+ DocumentPart,
17
25
  ImagePart,
26
+ InlineBase64AttachmentSource,
27
+ inlineBase64AttachmentSource,
28
+ inlineBase64Source,
18
29
  isContentEmpty,
30
+ refAttachmentSource,
31
+ RefAttachmentSource,
32
+ resolveContentAttachmentSources,
33
+ urlAttachmentSource,
34
+ UrlAttachmentSource,
19
35
  TextPart
20
36
  } from './content.ts'
21
37
  export {