@yolk-sdk/agent 0.1.0-canary.21 → 0.1.0-canary.22
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 +18 -5
- package/dist/loop/run.d.mts.map +1 -1
- package/dist/loop/run.mjs +38 -19
- package/dist/loop/run.mjs.map +1 -1
- package/dist/protocol/index.d.mts +2 -2
- package/dist/protocol/index.d.mts.map +1 -1
- package/dist/protocol/index.mjs +2 -2
- package/dist/protocol/message.d.mts +20 -1
- package/dist/protocol/message.d.mts.map +1 -1
- package/dist/protocol/message.mjs +59 -1
- package/dist/protocol/message.mjs.map +1 -1
- package/dist/providers/anthropic/claude-provider.d.mts.map +1 -1
- package/dist/providers/anthropic/claude-provider.mjs +2 -0
- package/dist/providers/anthropic/claude-provider.mjs.map +1 -1
- package/dist/providers/openai/codex-provider.d.mts.map +1 -1
- package/dist/providers/openai/codex-provider.mjs +2 -0
- package/dist/providers/openai/codex-provider.mjs.map +1 -1
- package/dist/providers/openai/provider.d.mts.map +1 -1
- package/dist/providers/openai/provider.mjs +2 -0
- package/dist/providers/openai/provider.mjs.map +1 -1
- package/dist/providers/transcript.d.mts +9 -0
- package/dist/providers/transcript.d.mts.map +1 -0
- package/dist/providers/transcript.mjs +17 -0
- package/dist/providers/transcript.mjs.map +1 -0
- package/package.json +1 -1
- package/src/loop/run.ts +56 -17
- package/src/protocol/index.ts +9 -1
- package/src/protocol/message.ts +127 -0
- package/src/providers/anthropic/claude-provider.ts +2 -0
- package/src/providers/openai/codex-provider.ts +2 -0
- package/src/providers/openai/provider.ts +2 -0
- package/src/providers/transcript.ts +24 -0
- package/src/tools/README.md +3 -2
package/README.md
CHANGED
|
@@ -27,11 +27,11 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
27
27
|
| `@yolk-sdk/agent/tools` | Tool module registry, `makeTool`, task/question tool contracts |
|
|
28
28
|
| `@yolk-sdk/agent/react` | Headless React chat hook, reducer, selectors, and render model |
|
|
29
29
|
| `@yolk-sdk/agent/oauth` | Provider-neutral OAuth token and broker contracts |
|
|
30
|
-
| `@yolk-sdk/agent/providers/openai` | OpenAI/Codex OAuth and
|
|
30
|
+
| `@yolk-sdk/agent/providers/openai` | OpenAI/Codex OAuth and broker helpers |
|
|
31
31
|
| `@yolk-sdk/agent/providers/openai/codex` | OpenAI Codex request and auth helpers |
|
|
32
32
|
| `@yolk-sdk/agent/providers/openai/codex-provider` | Codex LLM provider factory |
|
|
33
33
|
| `@yolk-sdk/agent/providers/openai/provider` | OpenAI-compatible LLM provider factory |
|
|
34
|
-
| `@yolk-sdk/agent/providers/anthropic` | Anthropic/Claude OAuth and
|
|
34
|
+
| `@yolk-sdk/agent/providers/anthropic` | Anthropic/Claude OAuth and broker helpers |
|
|
35
35
|
| `@yolk-sdk/agent/providers/anthropic/claude` | Claude request and auth helpers |
|
|
36
36
|
| `@yolk-sdk/agent/providers/anthropic/claude-provider` | Claude LLM provider factory |
|
|
37
37
|
| `@yolk-sdk/agent/skillset` | Portable skill and slash-command parsing/catalogs |
|
|
@@ -41,11 +41,14 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
41
41
|
|
|
42
42
|
```ts
|
|
43
43
|
import {
|
|
44
|
+
danglingHostToolCalls,
|
|
44
45
|
hitlResponseEvent,
|
|
45
46
|
makeSubagentRunId,
|
|
46
47
|
ProviderErrorInfo,
|
|
47
48
|
questionResponseStructuredContent,
|
|
48
|
-
|
|
49
|
+
repairDanglingHostToolCalls,
|
|
50
|
+
UserMessage,
|
|
51
|
+
validateNoDanglingHostToolCalls
|
|
49
52
|
} from '@yolk-sdk/agent/protocol'
|
|
50
53
|
import { run } from '@yolk-sdk/agent/loop'
|
|
51
54
|
import { runRuntime } from '@yolk-sdk/agent/runtime'
|
|
@@ -189,6 +192,14 @@ Annotations must be JSON-compatible. Use stable app-owned keys, preferably `snak
|
|
|
189
192
|
strings for dates inside annotations. Never put secrets, credentials, private ids, auth state, or
|
|
190
193
|
hidden policy in annotations, author, or timestamps; providers may send them to models.
|
|
191
194
|
|
|
195
|
+
## Transcript invariants
|
|
196
|
+
|
|
197
|
+
Every assistant host tool call must be followed by a matching `ToolResultMessage` before the next
|
|
198
|
+
non-tool message/provider request. Use `validateNoDanglingHostToolCalls` for preflight checks,
|
|
199
|
+
`danglingHostToolCalls` for diagnostics, and `repairDanglingHostToolCalls` only when loading older
|
|
200
|
+
persisted transcripts that already have gaps. Built-in providers reject dangling host tool calls
|
|
201
|
+
before vendor lowering with a non-retryable validation error.
|
|
202
|
+
|
|
192
203
|
## Human-in-the-loop
|
|
193
204
|
|
|
194
205
|
HITL is protocol-level, not UI-level:
|
|
@@ -232,13 +243,15 @@ data. `makeTool` converts these failures into `ToolResult.isError = true` so the
|
|
|
232
243
|
see the message and continue. The result includes structured content with `type`, `tool`,
|
|
233
244
|
`reason`, `message`, and optional `details` for UI/runtime handling.
|
|
234
245
|
|
|
235
|
-
|
|
236
|
-
|
|
246
|
+
Thrown `ToolError`s become model-visible failed tool results plus `ToolExecutionError` events,
|
|
247
|
+
so keep messages safe and non-secret. Reserve stream failure for provider/runtime defects,
|
|
248
|
+
aborts, and implementation bugs outside typed tool execution.
|
|
237
249
|
|
|
238
250
|
## Host responsibilities
|
|
239
251
|
|
|
240
252
|
- Choose models/providers and map provider streams into protocol events.
|
|
241
253
|
- Persist sessions, transcripts, and append logs.
|
|
254
|
+
- Persist/return one `ToolResultMessage` for every host tool call, including `isError` failures.
|
|
242
255
|
- Persist terminal provider failures and clear active run ids where applicable.
|
|
243
256
|
- Provide tools, approval policy, auth, storage, and observability.
|
|
244
257
|
- Compact context and decide memory/search policy.
|
package/dist/loop/run.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;KAoEY,cAAA;AAAA,KAEA,SAAA;EAAA,SACD,QAAA,EAAU,aAAA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,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,cA6C7C,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
|
@@ -50,6 +50,32 @@ const subagentCompletedEvent = (input) => {
|
|
|
50
50
|
createdAtMs: input.endedAtMs
|
|
51
51
|
});
|
|
52
52
|
};
|
|
53
|
+
const toolCompletionEvents = (input) => {
|
|
54
|
+
const completed = subagentCompletedEvent(input);
|
|
55
|
+
const toolCompleted = ToolExecutionCompleted.make({
|
|
56
|
+
call: input.call,
|
|
57
|
+
result: input.result,
|
|
58
|
+
createdAtMs: input.endedAtMs
|
|
59
|
+
});
|
|
60
|
+
return completed === void 0 ? [toolCompleted] : [toolCompleted, completed];
|
|
61
|
+
};
|
|
62
|
+
const toolErrorResult = (call, error) => ToolResult.make({
|
|
63
|
+
toolCallId: call.id,
|
|
64
|
+
content: error.message,
|
|
65
|
+
isError: true
|
|
66
|
+
});
|
|
67
|
+
const toolErrorEvents = (input) => [ToolExecutionError.make({
|
|
68
|
+
call: input.call,
|
|
69
|
+
message: input.error.message,
|
|
70
|
+
code: toolErrorCode(input.error),
|
|
71
|
+
createdAtMs: input.endedAtMs
|
|
72
|
+
}), ...toolCompletionEvents({
|
|
73
|
+
call: input.call,
|
|
74
|
+
result: toolErrorResult(input.call, input.error),
|
|
75
|
+
model: input.model,
|
|
76
|
+
startedAtMs: input.startedAtMs,
|
|
77
|
+
endedAtMs: input.endedAtMs
|
|
78
|
+
})];
|
|
53
79
|
const unsupportedInputError = (message) => new LLMError({
|
|
54
80
|
cause: "validation_error",
|
|
55
81
|
message,
|
|
@@ -158,26 +184,19 @@ const makeToolExecutionStream = (executor, call, model) => Stream.unwrap(Effect.
|
|
|
158
184
|
call,
|
|
159
185
|
createdAtMs: startedAtMs
|
|
160
186
|
}), started];
|
|
161
|
-
return Stream.fromIterable(startEvents).pipe(Stream.concat(Stream.fromEffect(executor.execute(call).pipe(Effect.flatMap((result) => Clock.currentTimeMillis.pipe(Effect.map((endedAtMs) => {
|
|
162
|
-
const completed = subagentCompletedEvent({
|
|
163
|
-
call,
|
|
164
|
-
result,
|
|
165
|
-
model,
|
|
166
|
-
startedAtMs,
|
|
167
|
-
endedAtMs
|
|
168
|
-
});
|
|
169
|
-
const toolCompleted = ToolExecutionCompleted.make({
|
|
170
|
-
call,
|
|
171
|
-
result,
|
|
172
|
-
createdAtMs: endedAtMs
|
|
173
|
-
});
|
|
174
|
-
return completed === void 0 ? [toolCompleted] : [toolCompleted, completed];
|
|
175
|
-
}))))).pipe(Stream.flatMap(Stream.fromIterable), Stream.catchTag("ToolError", (error) => Stream.fromEffect(Clock.currentTimeMillis).pipe(Stream.flatMap((endedAtMs) => Stream.make(ToolExecutionError.make({
|
|
187
|
+
return Stream.fromIterable(startEvents).pipe(Stream.concat(Stream.fromEffect(executor.execute(call).pipe(Effect.flatMap((result) => Clock.currentTimeMillis.pipe(Effect.map((endedAtMs) => toolCompletionEvents({
|
|
176
188
|
call,
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
189
|
+
result,
|
|
190
|
+
model,
|
|
191
|
+
startedAtMs,
|
|
192
|
+
endedAtMs
|
|
193
|
+
})))))).pipe(Stream.flatMap(Stream.fromIterable), Stream.catchTag("ToolError", (error) => Stream.fromEffect(Clock.currentTimeMillis).pipe(Stream.flatMap((endedAtMs) => Stream.fromIterable(toolErrorEvents({
|
|
194
|
+
call,
|
|
195
|
+
error,
|
|
196
|
+
model,
|
|
197
|
+
startedAtMs,
|
|
198
|
+
endedAtMs
|
|
199
|
+
}))))))));
|
|
181
200
|
}));
|
|
182
201
|
const boundedToolConcurrency = (loopConfig) => Math.max(1, loopConfig.toolConcurrency);
|
|
183
202
|
const toolResultMessageFromResult = (result) => ToolResultMessage.make({
|
package/dist/loop/run.mjs.map
CHANGED
|
@@ -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 ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n hitlResponseEvent,\n questionResponseStructuredContent,\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'\n ? Object.getOwnPropertyDescriptor(input, key)?.value\n : 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 maxUnhintedRetryDelayMs = 30_000\nconst maxHintedRetryDelayMs = 2_147_483_647\n\nconst validDelayMs = (delayMs: number) =>\n Number.isFinite(delayMs) && delayMs >= 0 ? Math.floor(delayMs) : undefined\n\nconst hintedRetryDelayMs = (error: LLMError) => {\n const delayMs = error.provider?.retryAfterMs\n const validDelay = delayMs === undefined ? undefined : validDelayMs(delayMs)\n\n return validDelay === undefined ? undefined : Math.min(validDelay, maxHintedRetryDelayMs)\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number, error: LLMError) => {\n const hintedDelay = hintedRetryDelayMs(error)\n\n if (hintedDelay !== undefined) {\n return hintedDelay\n }\n\n const delayMs = validDelayMs(baseDelayMs * 2 ** Math.max(0, attempt - 1)) ?? 0\n\n return Math.min(delayMs, maxUnhintedRetryDelayMs)\n}\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, error)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message,\n ...(error.provider === undefined ? {} : { provider: error.provider })\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> =\n 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 ? [toolCompleted] : [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 = (tools: ReadonlyArray<ToolDef>, call: ToolCall): 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: questionResponseStructuredContent(response)\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: [hitlResponseEvent(response)]\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: [hitlResponseEvent(response)]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [hitlResponseEvent(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 => [\n ...messages,\n ...orderedResults\n ]).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: [\n ...input.currentMessages,\n assistantMessage,\n ...orderedResults\n ],\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 = (\n input: TurnStreamInput\n): 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 => [\n ...messages,\n ...orderedResults\n ]).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> =\n 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":";;;;;;;;;;AA8FA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAC/B,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAC7C,KAAA;AAEN,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;C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MAAM;CACR,CAAC,CACH,CACF;AACF,CAAC,CACH"}
|
|
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 ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n hitlResponseEvent,\n questionResponseStructuredContent,\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'\n ? Object.getOwnPropertyDescriptor(input, key)?.value\n : 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 toolCompletionEvents = (input: {\n readonly call: ToolCall\n readonly result: ToolResult\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}): ReadonlyArray<AgentEvent> => {\n const completed = subagentCompletedEvent(input)\n const toolCompleted = ToolExecutionCompleted.make({\n call: input.call,\n result: input.result,\n createdAtMs: input.endedAtMs\n })\n\n return completed === undefined ? [toolCompleted] : [toolCompleted, completed]\n}\n\nconst toolErrorResult = (call: ToolCall, error: ToolError) =>\n ToolResult.make({\n toolCallId: call.id,\n content: error.message,\n isError: true\n })\n\nconst toolErrorEvents = (input: {\n readonly call: ToolCall\n readonly error: ToolError\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}): ReadonlyArray<AgentEvent> => [\n ToolExecutionError.make({\n call: input.call,\n message: input.error.message,\n code: toolErrorCode(input.error),\n createdAtMs: input.endedAtMs\n }),\n ...toolCompletionEvents({\n call: input.call,\n result: toolErrorResult(input.call, input.error),\n model: input.model,\n startedAtMs: input.startedAtMs,\n endedAtMs: 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 maxUnhintedRetryDelayMs = 30_000\nconst maxHintedRetryDelayMs = 2_147_483_647\n\nconst validDelayMs = (delayMs: number) =>\n Number.isFinite(delayMs) && delayMs >= 0 ? Math.floor(delayMs) : undefined\n\nconst hintedRetryDelayMs = (error: LLMError) => {\n const delayMs = error.provider?.retryAfterMs\n const validDelay = delayMs === undefined ? undefined : validDelayMs(delayMs)\n\n return validDelay === undefined ? undefined : Math.min(validDelay, maxHintedRetryDelayMs)\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number, error: LLMError) => {\n const hintedDelay = hintedRetryDelayMs(error)\n\n if (hintedDelay !== undefined) {\n return hintedDelay\n }\n\n const delayMs = validDelayMs(baseDelayMs * 2 ** Math.max(0, attempt - 1)) ?? 0\n\n return Math.min(delayMs, maxUnhintedRetryDelayMs)\n}\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, error)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message,\n ...(error.provider === undefined ? {} : { provider: error.provider })\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> =\n 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 toolCompletionEvents({\n call,\n result,\n model,\n startedAtMs,\n endedAtMs\n })\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.fromIterable(\n toolErrorEvents({\n call,\n error,\n model,\n startedAtMs,\n endedAtMs\n })\n )\n )\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 = (tools: ReadonlyArray<ToolDef>, call: ToolCall): 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: questionResponseStructuredContent(response)\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: [hitlResponseEvent(response)]\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: [hitlResponseEvent(response)]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [hitlResponseEvent(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 => [\n ...messages,\n ...orderedResults\n ]).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: [\n ...input.currentMessages,\n assistantMessage,\n ...orderedResults\n ],\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 = (\n input: TurnStreamInput\n): 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 => [\n ...messages,\n ...orderedResults\n ]).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> =\n 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":";;;;;;;;;;AA8FA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAC/B,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAC7C,KAAA;AAEN,MAAM,uBAAuB,OAAgB,QAAgB;CAC3D,M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,CACE,mBAAmB,KAAK;EACtB,UAAU;EACV,UAAU,OAAO,mBAAmB,CAAC;EACrC,OAAO,OAAO,QAAQ;EACtB,OAAO,OAAO,SAAS;CACzB,CAAC,CACH;CAEN,OAAO,OAAO,aAAa;EACzB,GAAG,SAAS;EACZ,GAAG;EACH,GAAG,SAAS;EACZ,GAAG;CACL,CAAC,EAAE,KACD,OAAO,OACL,4BAA4B;EAC1B,OAAO,qBAAqB,CAAC,IAAI,SAAS;EAC1C;EACA;EACA,OAAO,OAAO,SAAS;EACvB,SAAS;CACX,CAAC,CACH,CACF;AACF,CAAC,CACH;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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
|
|
2
2
|
import { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
|
|
3
3
|
import { ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, PlainHitlResponse, PlainQuestionAnswer, PlainQuestionResponse, PlainToolApprovalResponse, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionResponseStructuredContent, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
|
|
4
|
-
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, messageContextText, prependMessageContextToContent } from "./message.mjs";
|
|
4
|
+
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, DanglingHostToolCall, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, RepairDanglingHostToolCallsOptions, ToolResultMessage, TranscriptInvariantValidation, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
6
|
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
@@ -10,5 +10,5 @@ import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionRespo
|
|
|
10
10
|
//#region src/protocol/index.d.ts
|
|
11
11
|
type MessageId = string;
|
|
12
12
|
//#endregion
|
|
13
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, zeroAgentUsage };
|
|
13
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, type DanglingHostToolCall, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, type RepairDanglingHostToolCallsOptions, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, type TranscriptInvariantValidation, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
|
14
14
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KAiKY,SAAA"}
|
package/dist/protocol/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { AgentContentCapabilities, AgentModelCapabilities, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities } from "./capability.mjs";
|
|
2
2
|
import { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImagePart, InlineBase64AttachmentSource, RefAttachmentSource, TextPart, UrlAttachmentSource, appendTextToContent, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textToBase64Utf8, urlAttachmentSource } from "./content.mjs";
|
|
3
3
|
import { HitlRequest, HitlResponse, HitlResponseSource, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
|
|
4
|
-
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, messageContextText, prependMessageContextToContent } from "./message.mjs";
|
|
4
|
+
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
6
|
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
8
8
|
import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
|
|
9
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, zeroAgentUsage };
|
|
9
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
|
@@ -71,11 +71,30 @@ declare const ToolResultMessage_base: Schema.Class<ToolResultMessage, Schema.Tag
|
|
|
71
71
|
declare class ToolResultMessage extends ToolResultMessage_base {}
|
|
72
72
|
declare const AgentMessage: Schema.Union<readonly [typeof UserMessage, typeof AssistantAgentMessage, typeof ToolResultMessage]>;
|
|
73
73
|
type AgentMessage = typeof AgentMessage.Type;
|
|
74
|
+
type DanglingHostToolCall = {
|
|
75
|
+
readonly call: ToolCall;
|
|
76
|
+
readonly assistantMessageIndex: number;
|
|
77
|
+
readonly beforeMessageIndex?: number;
|
|
78
|
+
};
|
|
79
|
+
type TranscriptInvariantValidation = {
|
|
80
|
+
readonly _tag: 'Valid';
|
|
81
|
+
} | {
|
|
82
|
+
readonly _tag: 'DanglingHostToolCalls';
|
|
83
|
+
readonly calls: ReadonlyArray<DanglingHostToolCall>;
|
|
84
|
+
readonly message: string;
|
|
85
|
+
};
|
|
86
|
+
type RepairDanglingHostToolCallsOptions = {
|
|
87
|
+
readonly content?: (call: ToolCall) => Content;
|
|
88
|
+
readonly structuredContent?: (call: ToolCall) => unknown;
|
|
89
|
+
};
|
|
74
90
|
declare const assistantContent: (message: AssistantAgentMessage) => Content;
|
|
75
91
|
declare const assistantReasoningText: (message: AssistantAgentMessage) => string;
|
|
76
92
|
declare const assistantHostToolCalls: (message: AssistantAgentMessage) => ToolCall[];
|
|
93
|
+
declare const danglingHostToolCalls: (messages: ReadonlyArray<AgentMessage>) => ReadonlyArray<DanglingHostToolCall>;
|
|
94
|
+
declare const validateNoDanglingHostToolCalls: (messages: ReadonlyArray<AgentMessage>) => TranscriptInvariantValidation;
|
|
95
|
+
declare const repairDanglingHostToolCalls: (messages: ReadonlyArray<AgentMessage>, options?: RepairDanglingHostToolCallsOptions) => ReadonlyArray<AgentMessage>;
|
|
77
96
|
declare const messageContextText: (message: MessageEnvelope) => string;
|
|
78
97
|
declare const prependMessageContextToContent: (content: Content, context: string) => Content;
|
|
79
98
|
//#endregion
|
|
80
|
-
export { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, messageContextText, prependMessageContextToContent };
|
|
99
|
+
export { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, DanglingHostToolCall, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, RepairDanglingHostToolCallsOptions, ToolResultMessage, TranscriptInvariantValidation, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls };
|
|
81
100
|
//# sourceMappingURL=message.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message.d.mts","names":[],"sources":["../../src/protocol/message.ts"],"mappings":";;;;;cAIa,aAAA,EAAa,MAAA,CAAA,MAAA;EAAA;;KAGd,aAAA,UAAuB,aAAA,CAAc,IAAI;AAAA,cAExC,kBAAA,EAAkB,MAAA,CAAA,OAAA,CAAA,MAAA,CAAA,MAAA,EAAA,MAAA,CAAA,KAAA,CAAA,MAAA,CAAA,IAAA,EAAA,MAAA,CAAA,IAAA;AAAA,KACnB,kBAAA,UAA4B,kBAAA,CAAmB,IAAI;AAAA,KAEnD,eAAA;EAAA,SACD,WAAA;EAAA,SACA,MAAA,GAAS,aAAA;EAAA,SACT,WAAA,GAAc,kBAAkB;AAAA;AAAA,cAC1C,gBAAA;;;;;;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,aAAA,CAAc,YAAA,MACvB,6BAAA;AAAA,cAcU,2BAAA,GACX,QAAA,EAAU,aAAA,CAAc,YAAA,GACxB,OAAA,GAAU,kCAAA,KACT,aAAA,CAAc,YAAA;AAAA,cA+BJ,kBAAA,GAAsB,OAAwB,EAAf,eAAe;AAAA,cAqB9C,8BAAA,GAAkC,OAAA,EAAS,OAAA,EAAS,OAAA,aAAkB,OAQlF"}
|
|
@@ -57,6 +57,64 @@ const assistantContent = (message) => {
|
|
|
57
57
|
};
|
|
58
58
|
const assistantReasoningText = (message) => message.parts.flatMap((part) => part._tag === "Reasoning" ? [part.text] : []).join("");
|
|
59
59
|
const assistantHostToolCalls = (message) => message.parts.flatMap((part) => part._tag === "HostToolCall" ? [part.call] : []);
|
|
60
|
+
const pendingHostToolCalls = (message, messageIndex) => message._tag === "Assistant" ? assistantHostToolCalls(message).map((call) => ({
|
|
61
|
+
call,
|
|
62
|
+
assistantMessageIndex: messageIndex
|
|
63
|
+
})) : [];
|
|
64
|
+
const danglingHostToolCall = (pending, beforeMessageIndex) => ({
|
|
65
|
+
call: pending.call,
|
|
66
|
+
assistantMessageIndex: pending.assistantMessageIndex,
|
|
67
|
+
...beforeMessageIndex === void 0 ? {} : { beforeMessageIndex }
|
|
68
|
+
});
|
|
69
|
+
const danglingHostToolCallSummary = (calls) => calls.map(({ call }) => `${call.name} (${call.id})`).join(", ");
|
|
70
|
+
const danglingHostToolResultContent = (call) => `Tool ${call.name} did not return a result before the transcript continued.`;
|
|
71
|
+
const danglingHostToolResultMessage = (call, options) => {
|
|
72
|
+
const structuredContent = options?.structuredContent?.(call);
|
|
73
|
+
return ToolResultMessage.make({
|
|
74
|
+
toolCallId: call.id,
|
|
75
|
+
content: options?.content?.(call) ?? danglingHostToolResultContent(call),
|
|
76
|
+
isError: true,
|
|
77
|
+
...structuredContent === void 0 ? {} : { structuredContent }
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
const danglingHostToolCalls = (messages) => {
|
|
81
|
+
const dangling = [];
|
|
82
|
+
let pending = [];
|
|
83
|
+
for (const [messageIndex, message] of messages.entries()) {
|
|
84
|
+
if (message._tag !== "ToolResult" && pending.length > 0) {
|
|
85
|
+
dangling.push(...pending.map((call) => danglingHostToolCall(call, messageIndex)));
|
|
86
|
+
pending = [];
|
|
87
|
+
}
|
|
88
|
+
pending = [...pending, ...pendingHostToolCalls(message, messageIndex)];
|
|
89
|
+
if (message._tag === "ToolResult") pending = pending.filter((call) => call.call.id !== message.toolCallId);
|
|
90
|
+
}
|
|
91
|
+
dangling.push(...pending.map((call) => danglingHostToolCall(call, void 0)));
|
|
92
|
+
return dangling;
|
|
93
|
+
};
|
|
94
|
+
const validateNoDanglingHostToolCalls = (messages) => {
|
|
95
|
+
const dangling = danglingHostToolCalls(messages);
|
|
96
|
+
if (dangling.length === 0) return { _tag: "Valid" };
|
|
97
|
+
return {
|
|
98
|
+
_tag: "DanglingHostToolCalls",
|
|
99
|
+
calls: dangling,
|
|
100
|
+
message: `Transcript has host tool calls without tool results: ${danglingHostToolCallSummary(dangling)}`
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
const repairDanglingHostToolCalls = (messages, options) => {
|
|
104
|
+
const repaired = [];
|
|
105
|
+
let pending = [];
|
|
106
|
+
for (const message of messages) {
|
|
107
|
+
if (message._tag !== "ToolResult" && pending.length > 0) {
|
|
108
|
+
repaired.push(...pending.map((call) => danglingHostToolResultMessage(call, options)));
|
|
109
|
+
pending = [];
|
|
110
|
+
}
|
|
111
|
+
repaired.push(message);
|
|
112
|
+
if (message._tag === "Assistant") pending = [...pending, ...assistantHostToolCalls(message)];
|
|
113
|
+
if (message._tag === "ToolResult") pending = pending.filter((call) => call.id !== message.toolCallId);
|
|
114
|
+
}
|
|
115
|
+
repaired.push(...pending.map((call) => danglingHostToolResultMessage(call, options)));
|
|
116
|
+
return repaired;
|
|
117
|
+
};
|
|
60
118
|
const formatCreatedAtMs = (createdAtMs) => Number.isFinite(createdAtMs) ? new Date(createdAtMs).toISOString() : String(createdAtMs);
|
|
61
119
|
const formatAnnotationValue = (value) => JSON.stringify(value) ?? "null";
|
|
62
120
|
const messageContextText = (message) => {
|
|
@@ -70,6 +128,6 @@ const prependMessageContextToContent = (content, context) => {
|
|
|
70
128
|
return typeof content === "string" ? `${prefix}\n${content}` : [TextPart.make({ text: prefix }), ...content];
|
|
71
129
|
};
|
|
72
130
|
//#endregion
|
|
73
|
-
export { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, messageContextText, prependMessageContextToContent };
|
|
131
|
+
export { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls };
|
|
74
132
|
|
|
75
133
|
//# sourceMappingURL=message.mjs.map
|