@yolk-sdk/agent 0.0.1-canary.4 → 0.0.1-canary.6
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 +32 -10
- package/dist/loop/run.d.mts.map +1 -1
- package/dist/loop/run.mjs +2 -2
- package/dist/loop/run.mjs.map +1 -1
- package/dist/protocol/event.d.mts +2 -1
- package/dist/protocol/event.d.mts.map +1 -1
- package/dist/protocol/event.mjs +2 -1
- package/dist/protocol/event.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/tools/index.d.mts +2 -2
- package/dist/tools/index.mjs +2 -2
- package/dist/tools/task.d.mts +22 -3
- package/dist/tools/task.d.mts.map +1 -1
- package/dist/tools/task.mjs +31 -2
- package/dist/tools/task.mjs.map +1 -1
- package/package.json +1 -1
- package/src/loop/run.ts +2 -1
- package/src/protocol/event.ts +2 -0
- package/src/protocol/index.ts +1 -0
- package/src/tools/README.md +72 -0
- package/src/tools/index.ts +7 -1
- package/src/tools/task.ts +70 -2
package/README.md
CHANGED
|
@@ -14,23 +14,28 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
14
14
|
|
|
15
15
|
## Subpaths
|
|
16
16
|
|
|
17
|
-
| Subpath
|
|
18
|
-
|
|
|
19
|
-
| `@yolk-sdk/agent/protocol`
|
|
20
|
-
| `@yolk-sdk/agent/loop`
|
|
21
|
-
| `@yolk-sdk/agent/loop/testing` | Faux provider and tool executor test helpers
|
|
22
|
-
| `@yolk-sdk/agent/runtime`
|
|
23
|
-
| `@yolk-sdk/agent/client`
|
|
24
|
-
| `@yolk-sdk/agent/tools`
|
|
17
|
+
| Subpath | Purpose |
|
|
18
|
+
| ------------------------------ | -------------------------------------------------------------- |
|
|
19
|
+
| `@yolk-sdk/agent/protocol` | Wire messages, events, content, usage, tool schemas |
|
|
20
|
+
| `@yolk-sdk/agent/loop` | Stateless LLM/tool loop |
|
|
21
|
+
| `@yolk-sdk/agent/loop/testing` | Faux provider and tool executor test helpers |
|
|
22
|
+
| `@yolk-sdk/agent/runtime` | Transcript or append-backed runtime orchestration |
|
|
23
|
+
| `@yolk-sdk/agent/client` | HTTP/NDJSON transport and client state helpers |
|
|
24
|
+
| `@yolk-sdk/agent/tools` | Tool module registry, `makeTool`, task/question tool contracts |
|
|
25
25
|
|
|
26
26
|
## Imports
|
|
27
27
|
|
|
28
28
|
```ts
|
|
29
|
-
import { UserMessage } from '@yolk-sdk/agent/protocol'
|
|
29
|
+
import { makeSubagentRunId, UserMessage } from '@yolk-sdk/agent/protocol'
|
|
30
30
|
import { run } from '@yolk-sdk/agent/loop'
|
|
31
31
|
import { runRuntime } from '@yolk-sdk/agent/runtime'
|
|
32
32
|
import { initialAgentClientState } from '@yolk-sdk/agent/client'
|
|
33
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
makeNonRecursiveTaskToolModule,
|
|
35
|
+
makeTaskToolResult,
|
|
36
|
+
makeQuestionToolModule,
|
|
37
|
+
resolveTools
|
|
38
|
+
} from '@yolk-sdk/agent/tools'
|
|
34
39
|
```
|
|
35
40
|
|
|
36
41
|
Test helpers live behind their own subpath:
|
|
@@ -67,6 +72,23 @@ HITL is protocol-level, not UI-level:
|
|
|
67
72
|
- Use `makeQuestionToolModule` to expose the package-owned `question` tool; answers resume as structured tool results and model-visible text with selected labels.
|
|
68
73
|
- Approval is a host-enforced per-call gate for normal tools, not a model-callable permission tool or persisted allow-always system.
|
|
69
74
|
|
|
75
|
+
## Task subagents
|
|
76
|
+
|
|
77
|
+
`task` is the package-owned contract for subagent delegation. The SDK provides schema,
|
|
78
|
+
validation, non-recursive module wiring, subagent result extraction, and structured task result
|
|
79
|
+
metadata. Host apps provide the actual nested runtime.
|
|
80
|
+
|
|
81
|
+
Recommended setup:
|
|
82
|
+
|
|
83
|
+
- expose `makeNonRecursiveTaskToolModule` only to the top-level agent
|
|
84
|
+
- resolve subagent tools with `subagent: true`
|
|
85
|
+
- omit `task` from subagent toolsets
|
|
86
|
+
- include only tools that are safe for autonomous delegated work
|
|
87
|
+
- use `makeSubagentRunId(call.id)` for protocol-aligned run ids
|
|
88
|
+
- return `makeTaskToolResult(...)` so UI can show subagent id, type, status, model, and timing
|
|
89
|
+
|
|
90
|
+
See `examples/next/lib/agents/workflow-runtime/text-response.ts` for host-owned execution wiring.
|
|
91
|
+
|
|
70
92
|
## Host responsibilities
|
|
71
93
|
|
|
72
94
|
- Choose models/providers and map provider streams into protocol events.
|
package/dist/loop/run.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;KAsEY,cAAA;AAAA,KAEA,SAAA;EAAA,SACD,QAAA,EAAU,aAAA,CAAc,YAAA;EAAA,SACxB,YAAA;EAAA,SACA,KAAA,EAAO,aAAA,CAAc,OAAA;EAAA,SACrB,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,oBAAA;EAAA,SAClB,YAAA,GAAe,sBAAA;AAAA;AAAA,KAGd,eAAA,GAAkB,SAAS;EAAA,SAC5B,IAAI;AAAA;AAAA,KAGH,eAAA;EAAA,SACD,KAAA,EAAO,aAAA,CAAc,QAAA;EAAA,SACrB,KAAA,GAAQ,aAAA,CAAc,OAAA;EAAA,SACtB,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,aAAA,CAAc,YAAA;EAAA,SAChC,IAAA;EAAA,SACA,KAAA,GAAQ,UAAA;AAAA;AAAA,cAihCN,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,kBAAA,GAAqB,WAAA,GAAc,UAAA;AAAA,cAuBnE,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,UAAA,GAAa,YAAA;AAAA,cA4C7C,GAAA,GACX,MAAA,EAAQ,SAAA,KACP,MAAA,CAAO,MAAA,CACR,UAAA,EACA,cAAA,EACA,kBAAA,GAAqB,WAAA,GAAc,UAAA,GAAa,YAAA"}
|
package/dist/loop/run.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { LoopConfig } from "./services/loop-config.mjs";
|
|
|
6
6
|
import { ToolExecutor } from "./services/tool-executor.mjs";
|
|
7
7
|
import { Clock, Effect, Ref, Stream } from "effect";
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
9
|
-
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, zeroAgentUsage } from "@yolk-sdk/agent/protocol";
|
|
9
|
+
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, makeSubagentRunId, zeroAgentUsage } from "@yolk-sdk/agent/protocol";
|
|
10
10
|
//#region src/loop/run.ts
|
|
11
11
|
const questionToolName = "question";
|
|
12
12
|
const objectField = (input, key) => input !== null && typeof input === "object" ? Object.getOwnPropertyDescriptor(input, key)?.value : void 0;
|
|
@@ -20,7 +20,7 @@ const taskCallMetadata = (call) => {
|
|
|
20
20
|
const description = nonEmptyStringField(call.params, "description");
|
|
21
21
|
if (subagentType === void 0 || description === void 0) return;
|
|
22
22
|
return {
|
|
23
|
-
subagentRunId:
|
|
23
|
+
subagentRunId: makeSubagentRunId(call.id),
|
|
24
24
|
subagentType,
|
|
25
25
|
description
|
|
26
26
|
};
|
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 ToolApprovalDenied,\n ToolApprovalGranted,\n ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionAnswered,\n QuestionCancelled,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n ToolApprovalRequest,\n ToolResultMessage,\n SubagentCompleted,\n SubagentStarted,\n assistantHostToolCalls,\n type ToolCall,\n type AgentReasoningEffort,\n type HitlRequest,\n type HitlResponse,\n type QuestionPrompt,\n type QuestionResponse,\n type ToolApprovalResponse,\n ToolResult,\n TurnEnd,\n TurnStart,\n zeroAgentUsage,\n type AgentEvent,\n type AgentErrorCode,\n type AgentMessage,\n type AgentUsage,\n type AgentModelCapabilities,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport { accumulateAssistantMessage, collectToolCalls } from './accumulator.ts'\nimport {\n AbortError,\n LLMError,\n ToolError,\n type AgentLoopError,\n type LLMProviderError,\n} from './error.ts'\nimport type { LLMEvent } from './llm-event.ts'\nimport { ContextTransformer, type ContextTransformResult } from './services/context-transformer.ts'\nimport { LLMProvider, type LLMRequest } from './services/llm-provider.ts'\nimport { LoopConfig, type LoopConfigShape } from './services/loop-config.ts'\nimport { ToolExecutor } from './services/tool-executor.ts'\n\nexport type AgentLoopRunId = string\n\nexport type RunConfig = {\n readonly messages: ReadonlyArray<AgentMessage>\n readonly systemPrompt: string\n readonly tools: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly capabilities?: AgentModelCapabilities\n}\n\nexport type ModelTurnConfig = RunConfig & {\n readonly turn: number\n}\n\nexport type ToolBatchConfig = {\n readonly calls: ReadonlyArray<ToolCall>\n readonly tools?: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly createdMessages?: ReadonlyArray<AgentMessage>\n readonly turn?: number\n readonly usage?: AgentUsage\n}\n\nconst questionToolName = 'question'\n\ntype TaskCallMetadata = {\n readonly subagentRunId: string\n readonly subagentType: string\n readonly description: string\n}\n\nconst objectField = (input: unknown, key: string) =>\n input !== null && typeof input === 'object' ? Object.getOwnPropertyDescriptor(input, key)?.value : undefined\n\nconst nonEmptyStringField = (input: unknown, key: string) => {\n const value = objectField(input, key)\n\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nconst taskCallMetadata = (call: ToolCall): TaskCallMetadata | undefined => {\n if (call.name !== 'task') {\n return undefined\n }\n\n const subagentType = nonEmptyStringField(call.params, 'subagent_type')\n const description = nonEmptyStringField(call.params, 'description')\n\n if (subagentType === undefined || description === undefined) {\n return undefined\n }\n\n return {\n subagentRunId: `subagent:${call.id}`,\n subagentType,\n description\n }\n}\n\nconst subagentStartedEvent = (input: {\n readonly call: ToolCall\n readonly model: string\n readonly startedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentStarted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n createdAtMs: input.startedAtMs\n })\n}\n\nconst subagentCompletedEvent = (input: {\n readonly call: ToolCall\n readonly result: ToolResult\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentCompleted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n status: input.result.isError === true ? 'error' : 'completed',\n durationMs: Math.max(0, input.endedAtMs - input.startedAtMs),\n summary: contentPreview(input.result.content),\n createdAtMs: input.endedAtMs\n })\n}\n\nconst unsupportedInputError = (message: string) =>\n new LLMError({\n cause: 'validation_error',\n message,\n retryable: false\n })\n\nconst validateContent = (message: AgentMessage, capabilities: AgentModelCapabilities) =>\n Effect.forEach(contentPartsFromMessage(message), part => {\n switch (part._tag) {\n case 'Text':\n return capabilities.input.text\n ? Effect.void\n : Effect.fail(unsupportedInputError('Text input is not supported by this model'))\n case 'Image':\n return capabilities.input.image\n ? Effect.void\n : Effect.fail(unsupportedInputError('Image input is not supported by this model'))\n case 'Audio':\n return capabilities.input.audio\n ? Effect.void\n : Effect.fail(unsupportedInputError('Audio input is not supported by this model'))\n }\n })\n\nconst contentPartsFromMessage = (message: AgentMessage) => {\n switch (message._tag) {\n case 'User':\n case 'ToolResult':\n return contentParts(message.content)\n case 'Assistant':\n return message.parts.flatMap(part => (part._tag === 'Text' ? contentParts(part.content) : []))\n }\n}\n\nconst validateCapabilities = (\n config: RunConfig,\n messages: ReadonlyArray<AgentMessage>\n): Effect.Effect<void, LLMError> => {\n const capabilities = config.capabilities\n\n if (capabilities === undefined) {\n return Effect.void\n }\n\n if (!capabilities.tools && config.tools.length > 0) {\n return Effect.fail(unsupportedInputError('Tools are not supported by this model'))\n }\n\n if (!capabilities.reasoning && config.reasoningEffort !== undefined) {\n return Effect.fail(unsupportedInputError('Reasoning effort is not supported by this model'))\n }\n\n return Effect.forEach(messages, message => validateContent(message, capabilities)).pipe(\n Effect.asVoid\n )\n}\n\nconst toLlmEvent = (event: LLMEvent): ReadonlyArray<AgentEvent> => {\n switch (event._tag) {\n case 'TextDelta':\n return [AgentLLMTextDelta.make({ text: event.text })]\n case 'ReasoningDelta':\n return [AgentLLMReasoningDelta.make({ text: event.text })]\n case 'ToolCall':\n return [ToolInputEnd.make({ call: event.call })]\n case 'ToolInputStart':\n return [ToolInputStart.make({ id: event.id, name: event.name })]\n case 'ToolInputDelta':\n return [ToolInputDelta.make({ id: event.id, delta: event.delta })]\n case 'ProviderToolResult':\n return [ProviderToolResult.make({ call: event.call, result: event.result })]\n case 'Usage':\n return [UsageUpdate.make({ usage: event.usage })]\n case 'Done':\n return []\n }\n}\n\nconst isLlmEvent = (event: LLMEvent | AgentEvent | AgentRetry): event is LLMEvent => {\n switch (event._tag) {\n case 'TextDelta':\n case 'ReasoningDelta':\n case 'Done':\n case 'ToolCall':\n case 'ToolInputStart':\n case 'ToolInputDelta':\n case 'ProviderToolResult':\n case 'Usage':\n return true\n default:\n return false\n }\n}\n\ntype TurnStreamInput = {\n readonly config: RunConfig\n readonly contextTransformer: {\n readonly transform: (\n messages: ReadonlyArray<AgentMessage>\n ) => Effect.Effect<ContextTransformResult, AgentLoopError>\n }\n readonly loopConfig: LoopConfigShape\n readonly provider: {\n readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMProviderError>\n }\n readonly executor: {\n readonly execute: (call: ToolCall) => Effect.Effect<ToolResult, ToolError>\n }\n readonly currentMessages: ReadonlyArray<AgentMessage>\n readonly createdMessages: Ref.Ref<ReadonlyArray<AgentMessage>>\n readonly usage: Ref.Ref<AgentUsage>\n readonly turn: number\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number) =>\n Math.max(0, Math.floor(baseDelayMs * 2 ** Math.max(0, attempt - 1)))\n\nconst retryReason = (error: LLMError): AgentErrorCode => error.cause\n\nconst retrySleep = (delayMs: number) =>\n delayMs === 0 ? Effect.void : Effect.sleep(`${delayMs} millis`)\n\nconst failAgentLoopError = (\n error: AgentLoopError\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> => Stream.fail(error)\n\nconst sleepStream = (delayMs: number): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.fromEffect(retrySleep(delayMs)).pipe(Stream.flatMap(() => Stream.empty))\n\nconst withProviderRetries = (\n stream: Stream.Stream<LLMEvent, LLMProviderError>,\n loopConfig: TurnStreamInput['loopConfig'],\n makeStream: () => Stream.Stream<LLMEvent, LLMProviderError>,\n attempt: number\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.unwrap(\n Ref.make(false).pipe(\n Effect.map(emittedProviderEvent =>\n stream.pipe(\n Stream.tap(() => Ref.set(emittedProviderEvent, true)),\n Stream.catchTags({\n LLMError: error =>\n Stream.unwrap(\n Ref.get(emittedProviderEvent).pipe(\n Effect.map(emitted => {\n if (\n emitted ||\n !error.retryable ||\n error.cause === 'context_overflow' ||\n attempt > loopConfig.maxRetries\n ) {\n return failAgentLoopError(error)\n }\n\n const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message\n })\n ).pipe(\n Stream.concat(sleepStream(delayMs)),\n Stream.concat(\n withProviderRetries(makeStream(), loopConfig, makeStream, attempt + 1)\n )\n )\n })\n )\n ),\n AbortError: failAgentLoopError,\n FauxExhaustedError: failAgentLoopError\n })\n )\n )\n )\n )\n\nconst makeToolExecutionStream = (\n executor: TurnStreamInput['executor'],\n call: ToolCall,\n model: string\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAtMs = yield* Clock.currentTimeMillis\n const started = subagentStartedEvent({ call, model, startedAtMs })\n const startEvents: ReadonlyArray<AgentEvent> = started === undefined\n ? [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs })]\n : [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs }), started]\n\n return Stream.fromIterable(startEvents).pipe(\n Stream.concat(\n Stream.fromEffect(\n executor.execute(call).pipe(\n Effect.flatMap(result =>\n Clock.currentTimeMillis.pipe(\n Effect.map(endedAtMs => {\n const completed = subagentCompletedEvent({\n call,\n result,\n model,\n startedAtMs,\n endedAtMs\n })\n const toolCompleted = ToolExecutionCompleted.make({\n call,\n result,\n createdAtMs: endedAtMs\n })\n\n return completed === undefined\n ? [toolCompleted]\n : [toolCompleted, completed]\n })\n )\n )\n )\n ).pipe(\n Stream.flatMap(Stream.fromIterable),\n Stream.catchTag('ToolError', error =>\n Stream.fromEffect(Clock.currentTimeMillis).pipe(\n Stream.flatMap(endedAtMs =>\n Stream.make(\n ToolExecutionError.make({\n call,\n message: error.message,\n code: toolErrorCode(error),\n createdAtMs: endedAtMs\n })\n )\n ),\n Stream.concat(Stream.fail(error))\n )\n )\n )\n )\n )\n })\n )\n\ntype IndexedToolResultMessage = {\n readonly index: number\n readonly message: AgentMessage\n}\n\ntype IndexedToolCall = {\n readonly index: number\n readonly call: ToolCall\n}\n\ntype PreparedToolCall =\n | {\n readonly _tag: 'Execute'\n readonly index: number\n readonly call: ToolCall\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Result'\n readonly index: number\n readonly call: ToolCall\n readonly result: ToolResult\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Pending'\n readonly request: HitlRequest\n readonly events: ReadonlyArray<AgentEvent>\n }\n\ntype PreparedToolBatch = {\n readonly callsToExecute: ReadonlyArray<IndexedToolCall>\n readonly resultMessages: ReadonlyArray<IndexedToolResultMessage>\n readonly resultEvents: ReadonlyArray<AgentEvent>\n readonly events: ReadonlyArray<AgentEvent>\n readonly pendingRequests: ReadonlyArray<HitlRequest>\n readonly pendingEvents: ReadonlyArray<AgentEvent>\n}\n\ntype NonEmptyHitlRequests = readonly [HitlRequest, ...Array<HitlRequest>]\n\nconst boundedToolConcurrency = (loopConfig: LoopConfigShape) =>\n Math.max(1, loopConfig.toolConcurrency)\n\nconst toolResultMessageFromResult = (result: ToolResult) =>\n ToolResultMessage.make({\n toolCallId: result.toolCallId,\n content: result.content,\n isError: result.isError,\n structuredContent: result.structuredContent\n })\n\nconst toolDefFor = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n tools.find(tool => tool.name === call.name)\n\nconst approvalRequired = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n toolDefFor(tools, call)?.approval?.mode === 'manual'\n\nconst approvalRequestId = (call: ToolCall) => `approval:${call.id}`\n\nconst questionRequestId = (call: ToolCall) => `question:${call.id}`\n\nconst matchesApproval = (response: ToolApprovalResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === approvalRequestId(call)\n\nconst matchesQuestion = (response: QuestionResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === questionRequestId(call)\n\nconst approvalResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'ToolApprovalResponse' && matchesApproval(response, call) ? [response] : []\n )[0]\n\nconst questionResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'QuestionResponse' && matchesQuestion(response, call) ? [response] : []\n )[0]\n\nconst toolApprovalRequest = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall\n): ToolApprovalRequest =>\n ToolApprovalRequest.make({\n requestId: approvalRequestId(call),\n toolCallId: call.id,\n call,\n policy: toolDefFor(tools, call)?.approval\n })\n\nconst deniedToolResult = (call: ToolCall, response: ToolApprovalResponse) => {\n const reason = response.reason ?? 'Denied by user'\n\n return ToolResult.make({\n toolCallId: call.id,\n content: `Tool call denied: ${reason}`,\n isError: true,\n structuredContent: {\n type: 'tool_approval_denied',\n reason,\n source: response.source\n }\n })\n}\n\nconst questionToolResult = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt>\n) => {\n return ToolResult.make({\n toolCallId: response.toolCallId,\n content: formatQuestionResponseContent(response, questions),\n isError: response.outcome === 'cancelled' ? true : undefined,\n structuredContent: {\n type: 'question_response',\n outcome: response.outcome,\n answers: response.answers ?? [],\n reason: response.reason,\n source: response.source\n }\n })\n}\n\nconst invalidQuestionToolResult = (call: ToolCall) =>\n ToolResult.make({\n toolCallId: call.id,\n content: 'Invalid question arguments.',\n isError: true,\n structuredContent: { type: 'question_invalid' }\n })\n\nconst prepareQuestionCall = (\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): Effect.Effect<PreparedToolCall> =>\n Effect.gen(function* () {\n const decoded = yield* Schema.decodeUnknownEffect(QuestionToolParams)(call.params).pipe(\n Effect.result\n )\n\n if (decoded._tag === 'Failure') {\n return {\n _tag: 'Result',\n index,\n call,\n result: invalidQuestionToolResult(call),\n events: []\n }\n }\n\n const response = questionResponseFor(responses, call)\n\n if (response !== undefined) {\n return {\n _tag: 'Result',\n index,\n call,\n result: questionToolResult(response, decoded.success.questions),\n events: [\n response.outcome === 'answered'\n ? QuestionAnswered.make({ response })\n : QuestionCancelled.make({ response })\n ]\n }\n }\n\n const request = QuestionRequest.make({\n requestId: questionRequestId(call),\n toolCallId: call.id,\n call,\n questions: decoded.success.questions\n })\n\n return {\n _tag: 'Pending',\n request,\n events: [QuestionRequested.make({ request })]\n }\n })\n\nconst prepareApprovalCall = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): PreparedToolCall => {\n if (!approvalRequired(tools, call)) {\n return { _tag: 'Execute', index, call, events: [] }\n }\n\n const request = toolApprovalRequest(tools, call)\n const response = approvalResponseFor(responses, call)\n\n if (response === undefined) {\n return {\n _tag: 'Pending',\n request,\n events: [ToolApprovalRequested.make({ call, request })]\n }\n }\n\n if (response.decision === 'denied') {\n return {\n _tag: 'Result',\n index,\n call,\n result: deniedToolResult(call, response),\n events: [ToolApprovalDenied.make({ toolCallId: call.id, reason: response.reason ?? 'Denied by user', response })]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [ToolApprovalGranted.make({ toolCallId: call.id, response })]\n }\n}\n\nconst prepareToolCall = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly call: ToolCall\n readonly index: number\n}): Effect.Effect<PreparedToolCall> =>\n input.call.name === questionToolName\n ? prepareQuestionCall(input.call, input.index, input.responses)\n : Effect.succeed(prepareApprovalCall(input.tools, input.call, input.index, input.responses))\n\nconst prepareToolBatch = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly calls: ReadonlyArray<ToolCall>\n}): Effect.Effect<PreparedToolBatch> =>\n Effect.gen(function* () {\n const prepared = yield* Effect.forEach(input.calls, (call, index) =>\n prepareToolCall({ tools: input.tools, responses: input.responses, call, index })\n )\n\n return {\n callsToExecute: prepared.flatMap(item =>\n item._tag === 'Execute' ? [{ index: item.index, call: item.call }] : []\n ),\n resultMessages: prepared.flatMap(item =>\n item._tag === 'Result'\n ? [{ index: item.index, message: toolResultMessageFromResult(item.result) }]\n : []\n ),\n resultEvents: syntheticToolCompletionEvents(prepared),\n events: prepared.flatMap(item => (item._tag === 'Pending' ? [] : item.events)),\n pendingRequests: prepared.flatMap(item => (item._tag === 'Pending' ? [item.request] : [])),\n pendingEvents: prepared.flatMap(item => (item._tag === 'Pending' ? item.events : []))\n }\n })\n\nconst orderedToolResultMessages = (results: ReadonlyArray<IndexedToolResultMessage>) =>\n [...results].sort((left, right) => left.index - right.index).map(result => result.message)\n\nconst syntheticToolCompletionEvents = (\n prepared: ReadonlyArray<PreparedToolCall>\n): ReadonlyArray<AgentEvent> =>\n prepared.flatMap(item =>\n item._tag === 'Result'\n ? [ToolExecutionCompleted.make({ call: item.call, result: item.result })]\n : []\n )\n\nconst toolResultIds = (messages: ReadonlyArray<AgentMessage>): ReadonlySet<string> =>\n new Set(messages.flatMap(message => (message._tag === 'ToolResult' ? [message.toolCallId] : [])))\n\nconst pendingHostToolCalls = (messages: ReadonlyArray<AgentMessage>) => {\n const completed = toolResultIds(messages)\n\n return messages.flatMap(message =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).filter(call => !completed.has(call.id))\n : []\n )\n}\n\nconst nonEmptyHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): NonEmptyHitlRequests | undefined => {\n const first = requests[0]\n\n return first === undefined ? undefined : [first, ...requests.slice(1)]\n}\n\nconst parallelToolExecutionStream = (input: {\n readonly calls: ReadonlyArray<IndexedToolCall>\n readonly executor: TurnStreamInput['executor']\n readonly loopConfig: LoopConfigShape\n readonly model: string\n readonly results: Ref.Ref<ReadonlyArray<IndexedToolResultMessage>>\n}) =>\n Stream.mergeAll(\n input.calls.map(({ call, index }) =>\n makeToolExecutionStream(input.executor, call, input.model).pipe(\n Stream.tap(event => {\n if (event._tag !== 'ToolExecutionCompleted') {\n return Effect.void\n }\n\n return Ref.update(input.results, results => [\n ...results,\n { index, message: toolResultMessageFromResult(event.result) }\n ])\n })\n )\n ),\n { concurrency: boundedToolConcurrency(input.loopConfig) }\n )\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\ntype TurnCompletion = {\n readonly toolCalls: ReadonlyArray<ToolCall>\n readonly stopReason: 'stop' | 'tool_use'\n}\n\nconst validateTurnCompletion = (\n events: ReadonlyArray<LLMEvent>\n): Effect.Effect<TurnCompletion, LLMError> => {\n const doneEvents = events.filter(event => event._tag === 'Done')\n const toolCalls = collectToolCalls(events)\n const stopReason: TurnCompletion['stopReason'] = toolCalls.length === 0 ? 'stop' : 'tool_use'\n\n if (doneEvents.length !== 1) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `Expected exactly one LLM done event, received ${doneEvents.length}`,\n retryable: false\n })\n )\n }\n\n const doneEvent = doneEvents[0]\n\n if (doneEvent === undefined || doneEvent.stopReason !== stopReason) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `LLM done reason must be ${stopReason}`,\n retryable: false\n })\n )\n }\n\n return Effect.succeed({ toolCalls, stopReason })\n}\n\nconst makeAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n const turnEndEvents: ReadonlyArray<AgentEvent> = [\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage })\n ]\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n if (completion.toolCalls.length === 0) {\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentEnd.make({\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: completion.toolCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n ...prepared.events,\n ...prepared.pendingEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n Stream.make(TurnEnd.make({ turn: input.turn, reason: completion.stopReason })).pipe(\n Stream.concat(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, assistantMessage, ...orderedResults],\n turn: input.turn + 1\n })\n )\n )\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(turnEndEvents).pipe(\n Stream.concat(Stream.fromIterable(prepared.events)),\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst makeModelOnlyAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n return Stream.fromIterable([\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage }),\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason })\n ])\n })\n )\n\nconst makeLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeModelOnlyLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeModelOnlyAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeTurnStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nconst makePendingToolResumeStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const pendingCalls = pendingHostToolCalls(input.currentMessages)\n\n if (pendingCalls.length === 0 || (input.config.hitlResponses ?? []).length === 0) {\n return makeTurnStream(input)\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: pendingCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...prepared.events,\n ...prepared.pendingEvents,\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: Math.max(0, input.turn - 1),\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, ...orderedResults]\n })\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(prepared.events).pipe(\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst unavailableToolExecutor: TurnStreamInput['executor'] = {\n execute: call =>\n Effect.fail(\n new ToolError({\n tool: call.name,\n message: 'Tool execution is not available in model turn step',\n cause: 'execution'\n })\n )\n}\n\nconst makeModelOnlyTurnStream = (\n input: TurnStreamInput\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeModelOnlyLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nexport const runModelTurn = (\n config: ModelTurnConfig\n): Stream.Stream<AgentEvent, AgentLoopError, ContextTransformer | LLMProvider | LoopConfig> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return makeModelOnlyTurnStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor: unavailableToolExecutor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: config.turn\n })\n })\n )\n\nexport const runToolBatch = (\n config: ToolBatchConfig\n): Stream.Stream<AgentEvent, AgentLoopError, LoopConfig | ToolExecutor> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const executor = yield* ToolExecutor\n const loopConfig = yield* LoopConfig\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: config.tools ?? [],\n responses: config.hitlResponses ?? [],\n calls: config.calls\n })\n const hasPendingRequests = prepared.pendingRequests.length > 0\n const resultEvents = hasPendingRequests ? [] : prepared.resultEvents\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n const awaitingEvents: ReadonlyArray<AgentEvent> = pendingRequests === undefined\n ? []\n : [\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages: config.createdMessages ?? [],\n turns: config.turn ?? 0,\n usage: config.usage ?? zeroAgentUsage\n })\n ]\n\n return Stream.fromIterable([\n ...prepared.events,\n ...resultEvents,\n ...prepared.pendingEvents,\n ...awaitingEvents\n ]).pipe(\n Stream.concat(\n parallelToolExecutionStream({\n calls: hasPendingRequests ? [] : prepared.callsToExecute,\n executor,\n loopConfig,\n model: config.model ?? '',\n results: toolResultMessages\n })\n )\n )\n })\n )\n\nexport const run = (\n config: RunConfig\n): Stream.Stream<\n AgentEvent,\n AgentLoopError,\n ContextTransformer | LLMProvider | LoopConfig | ToolExecutor\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const executor = yield* ToolExecutor\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return Stream.make(AgentStart.make({})).pipe(\n Stream.concat(\n makePendingToolResumeStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: 1\n })\n )\n )\n })\n )\n"],"mappings":";;;;;;;;;;AA+FA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAAW,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAAQ,KAAA;AAErG,MAAM,uBAAuB,OAAgB,QAAgB;CAC3D,MAAM,QAAQ,YAAY,OAAO,GAAG;CAEpC,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ,KAAA;AACxE;AAEA,MAAM,oBAAoB,SAAiD;CACzE,IAAI,KAAK,SAAS,QAChB;CAGF,MAAM,eAAe,oBAAoB,KAAK,QAAQ,eAAe;CACrE,MAAM,cAAc,oBAAoB,KAAK,QAAQ,aAAa;CAElE,IAAI,iBAAiB,KAAA,KAAa,gBAAgB,KAAA,GAChD;CAGF,OAAO;EACL,eAAe,YAAY,KAAK;EAChC;EACA;CACF;A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AAC,IAAI,SAAS;CACxD,MAAM,kBAAkB,qBAAqB,SAAS,eAAe;CACrE,MAAM,iBAA4C,oBAAoB,KAAA,IAClE,CAAC,IACD,CACE,mBAAmB,KAAK;EACtB,UAAU;EACV,UAAU,OAAO,mBAAmB,CAAC;EACrC,OAAO,OAAO,QAAQ;EACtB,OAAO,OAAO,SAAS;CACzB,CAAC,CACH;CAEJ,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
|
+
{"version":3,"file":"run.mjs","names":["AgentLLMTextDelta","AgentLLMReasoningDelta"],"sources":["../../src/loop/run.ts"],"sourcesContent":["import { Clock, Effect, Ref, Stream } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentAwaitingInput,\n AgentEnd,\n AgentRetry,\n AgentStart,\n AssistantMessageEvent,\n UsageUpdate,\n addAgentUsage,\n contentParts,\n contentPreview,\n LLMReasoningDelta as AgentLLMReasoningDelta,\n LLMStreamEnd,\n LLMStreamStart,\n LLMTextDelta as AgentLLMTextDelta,\n ToolExecutionCompleted,\n ToolExecutionError,\n ToolExecutionStarted,\n ToolApprovalDenied,\n ToolApprovalGranted,\n ToolApprovalRequested,\n ToolInputEnd,\n ToolInputDelta,\n ToolInputStart,\n QuestionAnswered,\n QuestionCancelled,\n QuestionRequested,\n ProviderToolResult,\n QuestionRequest,\n QuestionToolParams,\n formatQuestionResponseContent,\n makeSubagentRunId,\n ToolApprovalRequest,\n ToolResultMessage,\n SubagentCompleted,\n SubagentStarted,\n assistantHostToolCalls,\n type ToolCall,\n type AgentReasoningEffort,\n type HitlRequest,\n type HitlResponse,\n type QuestionPrompt,\n type QuestionResponse,\n type ToolApprovalResponse,\n ToolResult,\n TurnEnd,\n TurnStart,\n zeroAgentUsage,\n type AgentEvent,\n type AgentErrorCode,\n type AgentMessage,\n type AgentUsage,\n type AgentModelCapabilities,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport { accumulateAssistantMessage, collectToolCalls } from './accumulator.ts'\nimport {\n AbortError,\n LLMError,\n ToolError,\n type AgentLoopError,\n type LLMProviderError,\n} from './error.ts'\nimport type { LLMEvent } from './llm-event.ts'\nimport { ContextTransformer, type ContextTransformResult } from './services/context-transformer.ts'\nimport { LLMProvider, type LLMRequest } from './services/llm-provider.ts'\nimport { LoopConfig, type LoopConfigShape } from './services/loop-config.ts'\nimport { ToolExecutor } from './services/tool-executor.ts'\n\nexport type AgentLoopRunId = string\n\nexport type RunConfig = {\n readonly messages: ReadonlyArray<AgentMessage>\n readonly systemPrompt: string\n readonly tools: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly capabilities?: AgentModelCapabilities\n}\n\nexport type ModelTurnConfig = RunConfig & {\n readonly turn: number\n}\n\nexport type ToolBatchConfig = {\n readonly calls: ReadonlyArray<ToolCall>\n readonly tools?: ReadonlyArray<ToolDef>\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly createdMessages?: ReadonlyArray<AgentMessage>\n readonly turn?: number\n readonly usage?: AgentUsage\n}\n\nconst questionToolName = 'question'\n\ntype TaskCallMetadata = {\n readonly subagentRunId: string\n readonly subagentType: string\n readonly description: string\n}\n\nconst objectField = (input: unknown, key: string) =>\n input !== null && typeof input === 'object' ? Object.getOwnPropertyDescriptor(input, key)?.value : undefined\n\nconst nonEmptyStringField = (input: unknown, key: string) => {\n const value = objectField(input, key)\n\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nconst taskCallMetadata = (call: ToolCall): TaskCallMetadata | undefined => {\n if (call.name !== 'task') {\n return undefined\n }\n\n const subagentType = nonEmptyStringField(call.params, 'subagent_type')\n const description = nonEmptyStringField(call.params, 'description')\n\n if (subagentType === undefined || description === undefined) {\n return undefined\n }\n\n return {\n subagentRunId: makeSubagentRunId(call.id),\n subagentType,\n description\n }\n}\n\nconst subagentStartedEvent = (input: {\n readonly call: ToolCall\n readonly model: string\n readonly startedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentStarted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n createdAtMs: input.startedAtMs\n })\n}\n\nconst subagentCompletedEvent = (input: {\n readonly call: ToolCall\n readonly result: ToolResult\n readonly model: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n}) => {\n const metadata = taskCallMetadata(input.call)\n\n return metadata === undefined\n ? undefined\n : SubagentCompleted.make({\n parentToolCallId: input.call.id,\n subagentRunId: metadata.subagentRunId,\n subagentType: metadata.subagentType,\n description: metadata.description,\n model: input.model,\n status: input.result.isError === true ? 'error' : 'completed',\n durationMs: Math.max(0, input.endedAtMs - input.startedAtMs),\n summary: contentPreview(input.result.content),\n createdAtMs: input.endedAtMs\n })\n}\n\nconst unsupportedInputError = (message: string) =>\n new LLMError({\n cause: 'validation_error',\n message,\n retryable: false\n })\n\nconst validateContent = (message: AgentMessage, capabilities: AgentModelCapabilities) =>\n Effect.forEach(contentPartsFromMessage(message), part => {\n switch (part._tag) {\n case 'Text':\n return capabilities.input.text\n ? Effect.void\n : Effect.fail(unsupportedInputError('Text input is not supported by this model'))\n case 'Image':\n return capabilities.input.image\n ? Effect.void\n : Effect.fail(unsupportedInputError('Image input is not supported by this model'))\n case 'Audio':\n return capabilities.input.audio\n ? Effect.void\n : Effect.fail(unsupportedInputError('Audio input is not supported by this model'))\n }\n })\n\nconst contentPartsFromMessage = (message: AgentMessage) => {\n switch (message._tag) {\n case 'User':\n case 'ToolResult':\n return contentParts(message.content)\n case 'Assistant':\n return message.parts.flatMap(part => (part._tag === 'Text' ? contentParts(part.content) : []))\n }\n}\n\nconst validateCapabilities = (\n config: RunConfig,\n messages: ReadonlyArray<AgentMessage>\n): Effect.Effect<void, LLMError> => {\n const capabilities = config.capabilities\n\n if (capabilities === undefined) {\n return Effect.void\n }\n\n if (!capabilities.tools && config.tools.length > 0) {\n return Effect.fail(unsupportedInputError('Tools are not supported by this model'))\n }\n\n if (!capabilities.reasoning && config.reasoningEffort !== undefined) {\n return Effect.fail(unsupportedInputError('Reasoning effort is not supported by this model'))\n }\n\n return Effect.forEach(messages, message => validateContent(message, capabilities)).pipe(\n Effect.asVoid\n )\n}\n\nconst toLlmEvent = (event: LLMEvent): ReadonlyArray<AgentEvent> => {\n switch (event._tag) {\n case 'TextDelta':\n return [AgentLLMTextDelta.make({ text: event.text })]\n case 'ReasoningDelta':\n return [AgentLLMReasoningDelta.make({ text: event.text })]\n case 'ToolCall':\n return [ToolInputEnd.make({ call: event.call })]\n case 'ToolInputStart':\n return [ToolInputStart.make({ id: event.id, name: event.name })]\n case 'ToolInputDelta':\n return [ToolInputDelta.make({ id: event.id, delta: event.delta })]\n case 'ProviderToolResult':\n return [ProviderToolResult.make({ call: event.call, result: event.result })]\n case 'Usage':\n return [UsageUpdate.make({ usage: event.usage })]\n case 'Done':\n return []\n }\n}\n\nconst isLlmEvent = (event: LLMEvent | AgentEvent | AgentRetry): event is LLMEvent => {\n switch (event._tag) {\n case 'TextDelta':\n case 'ReasoningDelta':\n case 'Done':\n case 'ToolCall':\n case 'ToolInputStart':\n case 'ToolInputDelta':\n case 'ProviderToolResult':\n case 'Usage':\n return true\n default:\n return false\n }\n}\n\ntype TurnStreamInput = {\n readonly config: RunConfig\n readonly contextTransformer: {\n readonly transform: (\n messages: ReadonlyArray<AgentMessage>\n ) => Effect.Effect<ContextTransformResult, AgentLoopError>\n }\n readonly loopConfig: LoopConfigShape\n readonly provider: {\n readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMProviderError>\n }\n readonly executor: {\n readonly execute: (call: ToolCall) => Effect.Effect<ToolResult, ToolError>\n }\n readonly currentMessages: ReadonlyArray<AgentMessage>\n readonly createdMessages: Ref.Ref<ReadonlyArray<AgentMessage>>\n readonly usage: Ref.Ref<AgentUsage>\n readonly turn: number\n}\n\nconst retryDelayMs = (baseDelayMs: number, attempt: number) =>\n Math.max(0, Math.floor(baseDelayMs * 2 ** Math.max(0, attempt - 1)))\n\nconst retryReason = (error: LLMError): AgentErrorCode => error.cause\n\nconst retrySleep = (delayMs: number) =>\n delayMs === 0 ? Effect.void : Effect.sleep(`${delayMs} millis`)\n\nconst failAgentLoopError = (\n error: AgentLoopError\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> => Stream.fail(error)\n\nconst sleepStream = (delayMs: number): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.fromEffect(retrySleep(delayMs)).pipe(Stream.flatMap(() => Stream.empty))\n\nconst withProviderRetries = (\n stream: Stream.Stream<LLMEvent, LLMProviderError>,\n loopConfig: TurnStreamInput['loopConfig'],\n makeStream: () => Stream.Stream<LLMEvent, LLMProviderError>,\n attempt: number\n): Stream.Stream<LLMEvent | AgentRetry, AgentLoopError> =>\n Stream.unwrap(\n Ref.make(false).pipe(\n Effect.map(emittedProviderEvent =>\n stream.pipe(\n Stream.tap(() => Ref.set(emittedProviderEvent, true)),\n Stream.catchTags({\n LLMError: error =>\n Stream.unwrap(\n Ref.get(emittedProviderEvent).pipe(\n Effect.map(emitted => {\n if (\n emitted ||\n !error.retryable ||\n error.cause === 'context_overflow' ||\n attempt > loopConfig.maxRetries\n ) {\n return failAgentLoopError(error)\n }\n\n const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt)\n return Stream.make(\n AgentRetry.make({\n attempt,\n reason: retryReason(error),\n delayMs,\n message: error.message\n })\n ).pipe(\n Stream.concat(sleepStream(delayMs)),\n Stream.concat(\n withProviderRetries(makeStream(), loopConfig, makeStream, attempt + 1)\n )\n )\n })\n )\n ),\n AbortError: failAgentLoopError,\n FauxExhaustedError: failAgentLoopError\n })\n )\n )\n )\n )\n\nconst makeToolExecutionStream = (\n executor: TurnStreamInput['executor'],\n call: ToolCall,\n model: string\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const startedAtMs = yield* Clock.currentTimeMillis\n const started = subagentStartedEvent({ call, model, startedAtMs })\n const startEvents: ReadonlyArray<AgentEvent> = started === undefined\n ? [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs })]\n : [ToolExecutionStarted.make({ call, createdAtMs: startedAtMs }), started]\n\n return Stream.fromIterable(startEvents).pipe(\n Stream.concat(\n Stream.fromEffect(\n executor.execute(call).pipe(\n Effect.flatMap(result =>\n Clock.currentTimeMillis.pipe(\n Effect.map(endedAtMs => {\n const completed = subagentCompletedEvent({\n call,\n result,\n model,\n startedAtMs,\n endedAtMs\n })\n const toolCompleted = ToolExecutionCompleted.make({\n call,\n result,\n createdAtMs: endedAtMs\n })\n\n return completed === undefined\n ? [toolCompleted]\n : [toolCompleted, completed]\n })\n )\n )\n )\n ).pipe(\n Stream.flatMap(Stream.fromIterable),\n Stream.catchTag('ToolError', error =>\n Stream.fromEffect(Clock.currentTimeMillis).pipe(\n Stream.flatMap(endedAtMs =>\n Stream.make(\n ToolExecutionError.make({\n call,\n message: error.message,\n code: toolErrorCode(error),\n createdAtMs: endedAtMs\n })\n )\n ),\n Stream.concat(Stream.fail(error))\n )\n )\n )\n )\n )\n })\n )\n\ntype IndexedToolResultMessage = {\n readonly index: number\n readonly message: AgentMessage\n}\n\ntype IndexedToolCall = {\n readonly index: number\n readonly call: ToolCall\n}\n\ntype PreparedToolCall =\n | {\n readonly _tag: 'Execute'\n readonly index: number\n readonly call: ToolCall\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Result'\n readonly index: number\n readonly call: ToolCall\n readonly result: ToolResult\n readonly events: ReadonlyArray<AgentEvent>\n }\n | {\n readonly _tag: 'Pending'\n readonly request: HitlRequest\n readonly events: ReadonlyArray<AgentEvent>\n }\n\ntype PreparedToolBatch = {\n readonly callsToExecute: ReadonlyArray<IndexedToolCall>\n readonly resultMessages: ReadonlyArray<IndexedToolResultMessage>\n readonly resultEvents: ReadonlyArray<AgentEvent>\n readonly events: ReadonlyArray<AgentEvent>\n readonly pendingRequests: ReadonlyArray<HitlRequest>\n readonly pendingEvents: ReadonlyArray<AgentEvent>\n}\n\ntype NonEmptyHitlRequests = readonly [HitlRequest, ...Array<HitlRequest>]\n\nconst boundedToolConcurrency = (loopConfig: LoopConfigShape) =>\n Math.max(1, loopConfig.toolConcurrency)\n\nconst toolResultMessageFromResult = (result: ToolResult) =>\n ToolResultMessage.make({\n toolCallId: result.toolCallId,\n content: result.content,\n isError: result.isError,\n structuredContent: result.structuredContent\n })\n\nconst toolDefFor = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n tools.find(tool => tool.name === call.name)\n\nconst approvalRequired = (tools: ReadonlyArray<ToolDef>, call: ToolCall) =>\n toolDefFor(tools, call)?.approval?.mode === 'manual'\n\nconst approvalRequestId = (call: ToolCall) => `approval:${call.id}`\n\nconst questionRequestId = (call: ToolCall) => `question:${call.id}`\n\nconst matchesApproval = (response: ToolApprovalResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === approvalRequestId(call)\n\nconst matchesQuestion = (response: QuestionResponse, call: ToolCall) =>\n response.toolCallId === call.id && response.requestId === questionRequestId(call)\n\nconst approvalResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'ToolApprovalResponse' && matchesApproval(response, call) ? [response] : []\n )[0]\n\nconst questionResponseFor = (responses: ReadonlyArray<HitlResponse>, call: ToolCall) =>\n responses.flatMap(response =>\n response._tag === 'QuestionResponse' && matchesQuestion(response, call) ? [response] : []\n )[0]\n\nconst toolApprovalRequest = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall\n): ToolApprovalRequest =>\n ToolApprovalRequest.make({\n requestId: approvalRequestId(call),\n toolCallId: call.id,\n call,\n policy: toolDefFor(tools, call)?.approval\n })\n\nconst deniedToolResult = (call: ToolCall, response: ToolApprovalResponse) => {\n const reason = response.reason ?? 'Denied by user'\n\n return ToolResult.make({\n toolCallId: call.id,\n content: `Tool call denied: ${reason}`,\n isError: true,\n structuredContent: {\n type: 'tool_approval_denied',\n reason,\n source: response.source\n }\n })\n}\n\nconst questionToolResult = (\n response: QuestionResponse,\n questions: ReadonlyArray<QuestionPrompt>\n) => {\n return ToolResult.make({\n toolCallId: response.toolCallId,\n content: formatQuestionResponseContent(response, questions),\n isError: response.outcome === 'cancelled' ? true : undefined,\n structuredContent: {\n type: 'question_response',\n outcome: response.outcome,\n answers: response.answers ?? [],\n reason: response.reason,\n source: response.source\n }\n })\n}\n\nconst invalidQuestionToolResult = (call: ToolCall) =>\n ToolResult.make({\n toolCallId: call.id,\n content: 'Invalid question arguments.',\n isError: true,\n structuredContent: { type: 'question_invalid' }\n })\n\nconst prepareQuestionCall = (\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): Effect.Effect<PreparedToolCall> =>\n Effect.gen(function* () {\n const decoded = yield* Schema.decodeUnknownEffect(QuestionToolParams)(call.params).pipe(\n Effect.result\n )\n\n if (decoded._tag === 'Failure') {\n return {\n _tag: 'Result',\n index,\n call,\n result: invalidQuestionToolResult(call),\n events: []\n }\n }\n\n const response = questionResponseFor(responses, call)\n\n if (response !== undefined) {\n return {\n _tag: 'Result',\n index,\n call,\n result: questionToolResult(response, decoded.success.questions),\n events: [\n response.outcome === 'answered'\n ? QuestionAnswered.make({ response })\n : QuestionCancelled.make({ response })\n ]\n }\n }\n\n const request = QuestionRequest.make({\n requestId: questionRequestId(call),\n toolCallId: call.id,\n call,\n questions: decoded.success.questions\n })\n\n return {\n _tag: 'Pending',\n request,\n events: [QuestionRequested.make({ request })]\n }\n })\n\nconst prepareApprovalCall = (\n tools: ReadonlyArray<ToolDef>,\n call: ToolCall,\n index: number,\n responses: ReadonlyArray<HitlResponse>\n): PreparedToolCall => {\n if (!approvalRequired(tools, call)) {\n return { _tag: 'Execute', index, call, events: [] }\n }\n\n const request = toolApprovalRequest(tools, call)\n const response = approvalResponseFor(responses, call)\n\n if (response === undefined) {\n return {\n _tag: 'Pending',\n request,\n events: [ToolApprovalRequested.make({ call, request })]\n }\n }\n\n if (response.decision === 'denied') {\n return {\n _tag: 'Result',\n index,\n call,\n result: deniedToolResult(call, response),\n events: [ToolApprovalDenied.make({ toolCallId: call.id, reason: response.reason ?? 'Denied by user', response })]\n }\n }\n\n return {\n _tag: 'Execute',\n index,\n call,\n events: [ToolApprovalGranted.make({ toolCallId: call.id, response })]\n }\n}\n\nconst prepareToolCall = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly call: ToolCall\n readonly index: number\n}): Effect.Effect<PreparedToolCall> =>\n input.call.name === questionToolName\n ? prepareQuestionCall(input.call, input.index, input.responses)\n : Effect.succeed(prepareApprovalCall(input.tools, input.call, input.index, input.responses))\n\nconst prepareToolBatch = (input: {\n readonly tools: ReadonlyArray<ToolDef>\n readonly responses: ReadonlyArray<HitlResponse>\n readonly calls: ReadonlyArray<ToolCall>\n}): Effect.Effect<PreparedToolBatch> =>\n Effect.gen(function* () {\n const prepared = yield* Effect.forEach(input.calls, (call, index) =>\n prepareToolCall({ tools: input.tools, responses: input.responses, call, index })\n )\n\n return {\n callsToExecute: prepared.flatMap(item =>\n item._tag === 'Execute' ? [{ index: item.index, call: item.call }] : []\n ),\n resultMessages: prepared.flatMap(item =>\n item._tag === 'Result'\n ? [{ index: item.index, message: toolResultMessageFromResult(item.result) }]\n : []\n ),\n resultEvents: syntheticToolCompletionEvents(prepared),\n events: prepared.flatMap(item => (item._tag === 'Pending' ? [] : item.events)),\n pendingRequests: prepared.flatMap(item => (item._tag === 'Pending' ? [item.request] : [])),\n pendingEvents: prepared.flatMap(item => (item._tag === 'Pending' ? item.events : []))\n }\n })\n\nconst orderedToolResultMessages = (results: ReadonlyArray<IndexedToolResultMessage>) =>\n [...results].sort((left, right) => left.index - right.index).map(result => result.message)\n\nconst syntheticToolCompletionEvents = (\n prepared: ReadonlyArray<PreparedToolCall>\n): ReadonlyArray<AgentEvent> =>\n prepared.flatMap(item =>\n item._tag === 'Result'\n ? [ToolExecutionCompleted.make({ call: item.call, result: item.result })]\n : []\n )\n\nconst toolResultIds = (messages: ReadonlyArray<AgentMessage>): ReadonlySet<string> =>\n new Set(messages.flatMap(message => (message._tag === 'ToolResult' ? [message.toolCallId] : [])))\n\nconst pendingHostToolCalls = (messages: ReadonlyArray<AgentMessage>) => {\n const completed = toolResultIds(messages)\n\n return messages.flatMap(message =>\n message._tag === 'Assistant'\n ? assistantHostToolCalls(message).filter(call => !completed.has(call.id))\n : []\n )\n}\n\nconst nonEmptyHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): NonEmptyHitlRequests | undefined => {\n const first = requests[0]\n\n return first === undefined ? undefined : [first, ...requests.slice(1)]\n}\n\nconst parallelToolExecutionStream = (input: {\n readonly calls: ReadonlyArray<IndexedToolCall>\n readonly executor: TurnStreamInput['executor']\n readonly loopConfig: LoopConfigShape\n readonly model: string\n readonly results: Ref.Ref<ReadonlyArray<IndexedToolResultMessage>>\n}) =>\n Stream.mergeAll(\n input.calls.map(({ call, index }) =>\n makeToolExecutionStream(input.executor, call, input.model).pipe(\n Stream.tap(event => {\n if (event._tag !== 'ToolExecutionCompleted') {\n return Effect.void\n }\n\n return Ref.update(input.results, results => [\n ...results,\n { index, message: toolResultMessageFromResult(event.result) }\n ])\n })\n )\n ),\n { concurrency: boundedToolConcurrency(input.loopConfig) }\n )\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\ntype TurnCompletion = {\n readonly toolCalls: ReadonlyArray<ToolCall>\n readonly stopReason: 'stop' | 'tool_use'\n}\n\nconst validateTurnCompletion = (\n events: ReadonlyArray<LLMEvent>\n): Effect.Effect<TurnCompletion, LLMError> => {\n const doneEvents = events.filter(event => event._tag === 'Done')\n const toolCalls = collectToolCalls(events)\n const stopReason: TurnCompletion['stopReason'] = toolCalls.length === 0 ? 'stop' : 'tool_use'\n\n if (doneEvents.length !== 1) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `Expected exactly one LLM done event, received ${doneEvents.length}`,\n retryable: false\n })\n )\n }\n\n const doneEvent = doneEvents[0]\n\n if (doneEvent === undefined || doneEvent.stopReason !== stopReason) {\n return Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: `LLM done reason must be ${stopReason}`,\n retryable: false\n })\n )\n }\n\n return Effect.succeed({ toolCalls, stopReason })\n}\n\nconst makeAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n const turnEndEvents: ReadonlyArray<AgentEvent> = [\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage })\n ]\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n if (completion.toolCalls.length === 0) {\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentEnd.make({\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: completion.toolCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...turnEndEvents,\n ...prepared.events,\n ...prepared.pendingEvents,\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason }),\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: input.turn,\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n Stream.make(TurnEnd.make({ turn: input.turn, reason: completion.stopReason })).pipe(\n Stream.concat(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, assistantMessage, ...orderedResults],\n turn: input.turn + 1\n })\n )\n )\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(turnEndEvents).pipe(\n Stream.concat(Stream.fromIterable(prepared.events)),\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst makeModelOnlyAfterLlmStream = (\n input: TurnStreamInput,\n llmEventsRef: Ref.Ref<ReadonlyArray<LLMEvent>>\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.get(llmEventsRef)\n const completion = yield* validateTurnCompletion(llmEvents)\n const assistantMessage = accumulateAssistantMessage(llmEvents)\n\n yield* Ref.update(input.createdMessages, messages => [...messages, assistantMessage])\n\n return Stream.fromIterable([\n LLMStreamEnd.make({ turn: input.turn }),\n AssistantMessageEvent.make({ message: assistantMessage }),\n TurnEnd.make({ turn: input.turn, reason: completion.stopReason })\n ])\n })\n )\n\nconst makeLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeModelOnlyLlmStream = (\n input: TurnStreamInput,\n llmEvents: Ref.Ref<ReadonlyArray<LLMEvent>>,\n result: ContextTransformResult\n): Stream.Stream<AgentEvent, AgentLoopError> => {\n const makeStream = () =>\n input.provider.stream({\n messages: result.messages,\n tools: input.config.tools,\n model: input.config.model,\n reasoningEffort: input.config.reasoningEffort,\n systemPrompt: input.config.systemPrompt\n })\n\n return Stream.fromIterable(result.events)\n .pipe(Stream.concat(withProviderRetries(makeStream(), input.loopConfig, makeStream, 1)))\n .pipe(\n Stream.tap(event => {\n if (!isLlmEvent(event)) {\n return Effect.void\n }\n\n const appendEvent = Ref.update(llmEvents, events => [...events, event])\n\n if (event._tag !== 'Usage') {\n return appendEvent\n }\n\n return Ref.update(input.usage, usage => addAgentUsage(usage, event.usage)).pipe(\n Effect.flatMap(() => appendEvent)\n )\n }),\n Stream.flatMap(event =>\n event._tag === 'AgentRetry'\n ? Stream.make(event)\n : isLlmEvent(event)\n ? Stream.fromIterable(toLlmEvent(event))\n : Stream.make(event)\n ),\n Stream.concat(makeModelOnlyAfterLlmStream(input, llmEvents))\n )\n}\n\nconst makeTurnStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nconst makePendingToolResumeStream = (input: TurnStreamInput): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const pendingCalls = pendingHostToolCalls(input.currentMessages)\n\n if (pendingCalls.length === 0 || (input.config.hitlResponses ?? []).length === 0) {\n return makeTurnStream(input)\n }\n\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: input.config.tools,\n responses: input.config.hitlResponses ?? [],\n calls: pendingCalls\n })\n\n if (prepared.resultMessages.length > 0) {\n yield* Ref.update(toolResultMessages, results => [...results, ...prepared.resultMessages])\n }\n\n if (prepared.pendingRequests.length > 0) {\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n\n if (pendingRequests === undefined) {\n return Stream.empty\n }\n\n const readyResults = orderedToolResultMessages(yield* Ref.get(toolResultMessages))\n if (readyResults.length > 0) {\n yield* Ref.update(input.createdMessages, messages => [...messages, ...readyResults])\n }\n\n const messages = yield* Ref.get(input.createdMessages)\n const usage = yield* Ref.get(input.usage)\n\n return Stream.fromIterable([\n ...prepared.events,\n ...prepared.pendingEvents,\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages,\n turns: Math.max(0, input.turn - 1),\n usage\n })\n ])\n }\n\n const toolExecutionStream = parallelToolExecutionStream({\n calls: prepared.callsToExecute,\n executor: input.executor,\n loopConfig: input.loopConfig,\n model: input.config.model,\n results: toolResultMessages\n })\n const nextTurnStream = Stream.unwrap(\n Ref.get(toolResultMessages).pipe(\n Effect.flatMap(results => {\n const orderedResults = orderedToolResultMessages(results)\n\n return Ref.update(input.createdMessages, messages => [...messages, ...orderedResults]).pipe(\n Effect.as(\n makeTurnStream({\n ...input,\n currentMessages: [...input.currentMessages, ...orderedResults]\n })\n )\n )\n })\n )\n )\n\n return Stream.fromIterable(prepared.events).pipe(\n Stream.concat(toolExecutionStream),\n Stream.concat(nextTurnStream)\n )\n })\n )\n\nconst unavailableToolExecutor: TurnStreamInput['executor'] = {\n execute: call =>\n Effect.fail(\n new ToolError({\n tool: call.name,\n message: 'Tool execution is not available in model turn step',\n cause: 'execution'\n })\n )\n}\n\nconst makeModelOnlyTurnStream = (\n input: TurnStreamInput\n): Stream.Stream<AgentEvent, AgentLoopError> =>\n Stream.suspend(() => {\n if (input.turn > input.loopConfig.maxTurns) {\n return Stream.fail(new AbortError({ reason: 'max_turns' }))\n }\n\n const llmStream = Stream.unwrap(\n Effect.gen(function* () {\n const llmEvents = yield* Ref.make<ReadonlyArray<LLMEvent>>([])\n const result = yield* input.contextTransformer.transform(input.currentMessages)\n yield* validateCapabilities(input.config, result.messages)\n\n return makeModelOnlyLlmStream(input, llmEvents, result)\n })\n )\n\n return Stream.fromIterable([\n TurnStart.make({ turn: input.turn }),\n LLMStreamStart.make({ turn: input.turn })\n ]).pipe(Stream.concat(llmStream))\n })\n\nexport const runModelTurn = (\n config: ModelTurnConfig\n): Stream.Stream<AgentEvent, AgentLoopError, ContextTransformer | LLMProvider | LoopConfig> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return makeModelOnlyTurnStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor: unavailableToolExecutor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: config.turn\n })\n })\n )\n\nexport const runToolBatch = (\n config: ToolBatchConfig\n): Stream.Stream<AgentEvent, AgentLoopError, LoopConfig | ToolExecutor> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const executor = yield* ToolExecutor\n const loopConfig = yield* LoopConfig\n const toolResultMessages = yield* Ref.make<ReadonlyArray<IndexedToolResultMessage>>([])\n const prepared = yield* prepareToolBatch({\n tools: config.tools ?? [],\n responses: config.hitlResponses ?? [],\n calls: config.calls\n })\n const hasPendingRequests = prepared.pendingRequests.length > 0\n const resultEvents = hasPendingRequests ? [] : prepared.resultEvents\n const pendingRequests = nonEmptyHitlRequests(prepared.pendingRequests)\n const awaitingEvents: ReadonlyArray<AgentEvent> = pendingRequests === undefined\n ? []\n : [\n AgentAwaitingInput.make({\n requests: pendingRequests,\n messages: config.createdMessages ?? [],\n turns: config.turn ?? 0,\n usage: config.usage ?? zeroAgentUsage\n })\n ]\n\n return Stream.fromIterable([\n ...prepared.events,\n ...resultEvents,\n ...prepared.pendingEvents,\n ...awaitingEvents\n ]).pipe(\n Stream.concat(\n parallelToolExecutionStream({\n calls: hasPendingRequests ? [] : prepared.callsToExecute,\n executor,\n loopConfig,\n model: config.model ?? '',\n results: toolResultMessages\n })\n )\n )\n })\n )\n\nexport const run = (\n config: RunConfig\n): Stream.Stream<\n AgentEvent,\n AgentLoopError,\n ContextTransformer | LLMProvider | LoopConfig | ToolExecutor\n> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const contextTransformer = yield* ContextTransformer\n const loopConfig = yield* LoopConfig\n const provider = yield* LLMProvider\n const executor = yield* ToolExecutor\n const createdMessages = yield* Ref.make<ReadonlyArray<AgentMessage>>([])\n const usage = yield* Ref.make(zeroAgentUsage)\n\n return Stream.make(AgentStart.make({})).pipe(\n Stream.concat(\n makePendingToolResumeStream({\n config,\n contextTransformer,\n loopConfig,\n provider,\n executor,\n currentMessages: config.messages,\n createdMessages,\n usage,\n turn: 1\n })\n )\n )\n })\n )\n"],"mappings":";;;;;;;;;;AAgGA,MAAM,mBAAmB;AAQzB,MAAM,eAAe,OAAgB,QACnC,UAAU,QAAQ,OAAO,UAAU,WAAW,OAAO,yBAAyB,OAAO,GAAG,GAAG,QAAQ,KAAA;AAErG,MAAM,uBAAuB,OAAgB,QAAgB;CAC3D,MAAM,QAAQ,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EACA;EACA,MAAM;CACR,CAAC,CACH,CACF;AACF,CAAC,CACH"}
|
|
@@ -221,8 +221,9 @@ declare const SubagentCompleted_base: Schema.Class<SubagentCompleted, Schema.Tag
|
|
|
221
221
|
readonly createdAtMs: Schema.optional<Schema.Number>;
|
|
222
222
|
}>, {}>;
|
|
223
223
|
declare class SubagentCompleted extends SubagentCompleted_base {}
|
|
224
|
+
declare const makeSubagentRunId: (parentToolCallId: string) => string;
|
|
224
225
|
declare const AgentEvent: Schema.Union<readonly [typeof AgentStart, typeof AgentError, typeof AgentEnd, typeof AgentAwaitingInput, typeof UsageUpdate, typeof AgentRetry, typeof CompactionStart, typeof CompactionEnd, typeof TurnStart, typeof TurnEnd, typeof LLMStreamStart, typeof LLMTextDelta, typeof LLMReasoningDelta, typeof ToolInputStart, typeof ToolInputDelta, typeof ToolInputEnd, typeof LLMStreamEnd, typeof AssistantMessageEvent, typeof ToolApprovalRequested, typeof ToolApprovalGranted, typeof ToolApprovalDenied, typeof QuestionRequested, typeof QuestionAnswered, typeof QuestionCancelled, typeof ToolExecutionStarted, typeof ToolExecutionCompleted, typeof ToolExecutionError, typeof ProviderToolResult, typeof SubagentStarted, typeof SubagentCompleted]>;
|
|
225
226
|
type AgentEvent = typeof AgentEvent.Type;
|
|
226
227
|
//#endregion
|
|
227
|
-
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate };
|
|
228
|
+
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, makeSubagentRunId };
|
|
228
229
|
//# sourceMappingURL=event.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.mts","names":[],"sources":["../../src/protocol/event.ts"],"mappings":";;;;;;cAoBa,cAAA,EAAc,MAAA,CAAA,QAAA;AAAA,KACf,cAAA,UAAwB,cAAA,CAAe,IAAI;AAAA,cAE1C,cAAA,EAAc,MAAA,CAAA,QAAA;AAAA,KAef,cAAA,UAAwB,cAAA,CAAe,IAAI;AAAA,cAAA,eAAA;;;;cAE1C,UAAA,SAAmB,eAE9B;AAAA,cAAG,eAAA;;;;;;;cAEQ,UAAA,SAAmB,eAK9B;AAAA,cAAG,aAAA;;;;;;;cAEQ,QAAA,SAAiB,aAK5B;AAAA,cAAG,uBAAA;;;;;;;;cAEQ,kBAAA,SAA2B,uBASvC;AAAA,cAAG,gBAAA;;;;;cAES,WAAA,SAAoB,gBAG/B;AAAA,cAAG,eAAA;;;;;;;;cAEQ,UAAA,SAAmB,eAM9B;AAAA,cAAG,oBAAA;;;;;cAEQ,eAAA,SAAwB,oBAGnC;AAAA,cAAG,kBAAA;;;;;;;cAEQ,aAAA,SAAsB,kBAKjC;AAAA,cAAG,cAAA;;;;;cAEQ,SAAA,SAAkB,cAG7B;AAAA,cAAG,YAAA;;;;;;cAEQ,OAAA,SAAgB,YAI3B;AAAA,cAAG,mBAAA;;;;;cAEQ,cAAA,SAAuB,mBAGlC;AAAA,cAAG,iBAAA;;;;;cAEQ,YAAA,SAAqB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A,SAAA,kBAAA,SAAA,kBAAA,SAAA,eAAA,SAAA,iBAAA;AAAA,KAgCX,UAAA,UAAoB,UAAA,CAAW,IAAI"}
|
package/dist/protocol/event.mjs
CHANGED
|
@@ -179,6 +179,7 @@ var SubagentCompleted = class extends Schema.TaggedClass()("SubagentCompleted",
|
|
|
179
179
|
durationMs: Schema.Number,
|
|
180
180
|
summary: Schema.optional(Schema.String)
|
|
181
181
|
}) {};
|
|
182
|
+
const makeSubagentRunId = (parentToolCallId) => `subagent:${parentToolCallId}`;
|
|
182
183
|
const AgentEvent = Schema.Union([
|
|
183
184
|
AgentStart,
|
|
184
185
|
AgentError,
|
|
@@ -212,6 +213,6 @@ const AgentEvent = Schema.Union([
|
|
|
212
213
|
SubagentCompleted
|
|
213
214
|
]);
|
|
214
215
|
//#endregion
|
|
215
|
-
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate };
|
|
216
|
+
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, makeSubagentRunId };
|
|
216
217
|
|
|
217
218
|
//# sourceMappingURL=event.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.mjs","names":[],"sources":["../../src/protocol/event.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AssistantAgentMessage, AgentMessage } from './message.ts'\nimport {\n HitlRequest,\n QuestionRequest,\n QuestionResponse,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolCall,\n ToolResult\n} from './tool.ts'\nimport { AgentUsage } from './usage.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nconst EventIdentity = {\n eventId: Schema.optional(NonEmptyTrimmedString),\n createdAtMs: Schema.optional(Schema.Number)\n}\n\nexport const SubagentStatus = Schema.Literals(['running', 'completed', 'error'])\nexport type SubagentStatus = typeof SubagentStatus.Type\n\nexport const AgentErrorCode = Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'context_overflow',\n 'invalid_response',\n 'tool_error',\n 'tool_denied',\n 'tool_timeout',\n 'store_error',\n 'aborted',\n 'session_not_found',\n 'conflict',\n 'unknown'\n])\nexport type AgentErrorCode = typeof AgentErrorCode.Type\n\nexport class AgentStart extends Schema.TaggedClass<AgentStart>()('AgentStart', {\n ...EventIdentity\n}) {}\n\nexport class AgentError extends Schema.TaggedClass<AgentError>()('AgentError', {\n ...EventIdentity,\n code: AgentErrorCode,\n message: Schema.String,\n retryable: Schema.Boolean\n}) {}\n\nexport class AgentEnd extends Schema.TaggedClass<AgentEnd>()('AgentEnd', {\n ...EventIdentity,\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n}) {}\n\nexport class AgentAwaitingInput extends Schema.TaggedClass<AgentAwaitingInput>()(\n 'AgentAwaitingInput',\n {\n ...EventIdentity,\n requests: Schema.NonEmptyArray(HitlRequest),\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n }\n) {}\n\nexport class UsageUpdate extends Schema.TaggedClass<UsageUpdate>()('UsageUpdate', {\n ...EventIdentity,\n usage: AgentUsage\n}) {}\n\nexport class AgentRetry extends Schema.TaggedClass<AgentRetry>()('AgentRetry', {\n ...EventIdentity,\n attempt: Schema.Number,\n reason: AgentErrorCode,\n delayMs: Schema.Number,\n message: Schema.String\n}) {}\n\nexport class CompactionStart extends Schema.TaggedClass<CompactionStart>()('CompactionStart', {\n ...EventIdentity,\n strategy: Schema.String\n}) {}\n\nexport class CompactionEnd extends Schema.TaggedClass<CompactionEnd>()('CompactionEnd', {\n ...EventIdentity,\n strategy: Schema.String,\n beforeTokens: Schema.optional(Schema.Number),\n afterTokens: Schema.optional(Schema.Number)\n}) {}\n\nexport class TurnStart extends Schema.TaggedClass<TurnStart>()('TurnStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class TurnEnd extends Schema.TaggedClass<TurnEnd>()('TurnEnd', {\n ...EventIdentity,\n turn: Schema.Number,\n reason: Schema.Literals(['stop', 'tool_use'])\n}) {}\n\nexport class LLMStreamStart extends Schema.TaggedClass<LLMStreamStart>()('LLMStreamStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class LLMTextDelta extends Schema.TaggedClass<LLMTextDelta>()('LLMTextDelta', {\n ...EventIdentity,\n text: Schema.String\n}) {}\n\nexport class LLMReasoningDelta extends Schema.TaggedClass<LLMReasoningDelta>()(\n 'LLMReasoningDelta',\n {\n ...EventIdentity,\n text: Schema.String\n }\n) {}\n\nexport class ToolInputStart extends Schema.TaggedClass<ToolInputStart>()('ToolInputStart', {\n ...EventIdentity,\n id: Schema.String,\n name: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolInputDelta extends Schema.TaggedClass<ToolInputDelta>()('ToolInputDelta', {\n ...EventIdentity,\n id: Schema.String,\n delta: Schema.String\n}) {}\n\nexport class ToolInputEnd extends Schema.TaggedClass<ToolInputEnd>()('ToolInputEnd', {\n ...EventIdentity,\n call: ToolCall\n}) {}\n\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>()(\n 'ToolApprovalRequested',\n {\n ...EventIdentity,\n call: ToolCall,\n request: Schema.optional(ToolApprovalRequest)\n }\n) {}\n\nexport class ToolApprovalGranted extends Schema.TaggedClass<ToolApprovalGranted>()(\n 'ToolApprovalGranted',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class ToolApprovalDenied extends Schema.TaggedClass<ToolApprovalDenied>()(\n 'ToolApprovalDenied',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n reason: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class QuestionRequested extends Schema.TaggedClass<QuestionRequested>()('QuestionRequested', {\n ...EventIdentity,\n request: QuestionRequest\n}) {}\n\nexport class QuestionAnswered extends Schema.TaggedClass<QuestionAnswered>()('QuestionAnswered', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class QuestionCancelled extends Schema.TaggedClass<QuestionCancelled>()('QuestionCancelled', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class LLMStreamEnd extends Schema.TaggedClass<LLMStreamEnd>()('LLMStreamEnd', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class AssistantMessageEvent extends Schema.TaggedClass<AssistantMessageEvent>()(\n 'AssistantMessage',\n {\n ...EventIdentity,\n message: AssistantAgentMessage\n }\n) {}\n\nexport class ToolExecutionStarted extends Schema.TaggedClass<ToolExecutionStarted>()(\n 'ToolExecutionStarted',\n {\n ...EventIdentity,\n call: ToolCall\n }\n) {}\n\nexport class ToolExecutionCompleted extends Schema.TaggedClass<ToolExecutionCompleted>()(\n 'ToolExecutionCompleted',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class ToolExecutionError extends Schema.TaggedClass<ToolExecutionError>()(\n 'ToolExecutionError',\n {\n ...EventIdentity,\n call: ToolCall,\n message: Schema.String,\n code: AgentErrorCode\n }\n) {}\n\nexport class ProviderToolResult extends Schema.TaggedClass<ProviderToolResult>()(\n 'ProviderToolResult',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>()('SubagentStarted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String\n}) {}\n\nexport class SubagentCompleted extends Schema.TaggedClass<SubagentCompleted>()('SubagentCompleted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String,\n status: SubagentStatus,\n durationMs: Schema.Number,\n summary: Schema.optional(Schema.String)\n}) {}\n\nexport const AgentEvent = Schema.Union([\n AgentStart,\n AgentError,\n AgentEnd,\n AgentAwaitingInput,\n UsageUpdate,\n AgentRetry,\n CompactionStart,\n CompactionEnd,\n TurnStart,\n TurnEnd,\n LLMStreamStart,\n LLMTextDelta,\n LLMReasoningDelta,\n ToolInputStart,\n ToolInputDelta,\n ToolInputEnd,\n LLMStreamEnd,\n AssistantMessageEvent,\n ToolApprovalRequested,\n ToolApprovalGranted,\n ToolApprovalDenied,\n QuestionRequested,\n QuestionAnswered,\n QuestionCancelled,\n ToolExecutionStarted,\n ToolExecutionCompleted,\n ToolExecutionError,\n ProviderToolResult,\n SubagentStarted,\n SubagentCompleted\n])\nexport type AgentEvent = typeof AgentEvent.Type\n"],"mappings":";;;;;AAaA,MAAM,wBAAwB,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO,WAAW,CAAC,CAAC;AAEnF,MAAM,gBAAgB;CACpB,SAAS,OAAO,SAAS,qBAAqB;CAC9C,aAAa,OAAO,SAAS,OAAO,MAAM;AAC5C;AAEA,MAAa,iBAAiB,OA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CAAC;AAEJ,IAAa,oBAAb,cAAuC,OAAO,YAA+B,EAAE,qBAAqB;CAClG,GAAG;CACH,kBAAkB;CAClB,eAAe;CACf,cAAc;CACd,aAAa,OAAO;CACpB,OAAO,OAAO;CACd,QAAQ;CACR,YAAY,OAAO;CACnB,SAAS,OAAO,SAAS,OAAO,MAAM;AACxC,CAAC,EAAE,CAAC;AAEJ,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"event.mjs","names":[],"sources":["../../src/protocol/event.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AssistantAgentMessage, AgentMessage } from './message.ts'\nimport {\n HitlRequest,\n QuestionRequest,\n QuestionResponse,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolCall,\n ToolResult\n} from './tool.ts'\nimport { AgentUsage } from './usage.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nconst EventIdentity = {\n eventId: Schema.optional(NonEmptyTrimmedString),\n createdAtMs: Schema.optional(Schema.Number)\n}\n\nexport const SubagentStatus = Schema.Literals(['running', 'completed', 'error'])\nexport type SubagentStatus = typeof SubagentStatus.Type\n\nexport const AgentErrorCode = Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'context_overflow',\n 'invalid_response',\n 'tool_error',\n 'tool_denied',\n 'tool_timeout',\n 'store_error',\n 'aborted',\n 'session_not_found',\n 'conflict',\n 'unknown'\n])\nexport type AgentErrorCode = typeof AgentErrorCode.Type\n\nexport class AgentStart extends Schema.TaggedClass<AgentStart>()('AgentStart', {\n ...EventIdentity\n}) {}\n\nexport class AgentError extends Schema.TaggedClass<AgentError>()('AgentError', {\n ...EventIdentity,\n code: AgentErrorCode,\n message: Schema.String,\n retryable: Schema.Boolean\n}) {}\n\nexport class AgentEnd extends Schema.TaggedClass<AgentEnd>()('AgentEnd', {\n ...EventIdentity,\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n}) {}\n\nexport class AgentAwaitingInput extends Schema.TaggedClass<AgentAwaitingInput>()(\n 'AgentAwaitingInput',\n {\n ...EventIdentity,\n requests: Schema.NonEmptyArray(HitlRequest),\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n }\n) {}\n\nexport class UsageUpdate extends Schema.TaggedClass<UsageUpdate>()('UsageUpdate', {\n ...EventIdentity,\n usage: AgentUsage\n}) {}\n\nexport class AgentRetry extends Schema.TaggedClass<AgentRetry>()('AgentRetry', {\n ...EventIdentity,\n attempt: Schema.Number,\n reason: AgentErrorCode,\n delayMs: Schema.Number,\n message: Schema.String\n}) {}\n\nexport class CompactionStart extends Schema.TaggedClass<CompactionStart>()('CompactionStart', {\n ...EventIdentity,\n strategy: Schema.String\n}) {}\n\nexport class CompactionEnd extends Schema.TaggedClass<CompactionEnd>()('CompactionEnd', {\n ...EventIdentity,\n strategy: Schema.String,\n beforeTokens: Schema.optional(Schema.Number),\n afterTokens: Schema.optional(Schema.Number)\n}) {}\n\nexport class TurnStart extends Schema.TaggedClass<TurnStart>()('TurnStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class TurnEnd extends Schema.TaggedClass<TurnEnd>()('TurnEnd', {\n ...EventIdentity,\n turn: Schema.Number,\n reason: Schema.Literals(['stop', 'tool_use'])\n}) {}\n\nexport class LLMStreamStart extends Schema.TaggedClass<LLMStreamStart>()('LLMStreamStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class LLMTextDelta extends Schema.TaggedClass<LLMTextDelta>()('LLMTextDelta', {\n ...EventIdentity,\n text: Schema.String\n}) {}\n\nexport class LLMReasoningDelta extends Schema.TaggedClass<LLMReasoningDelta>()(\n 'LLMReasoningDelta',\n {\n ...EventIdentity,\n text: Schema.String\n }\n) {}\n\nexport class ToolInputStart extends Schema.TaggedClass<ToolInputStart>()('ToolInputStart', {\n ...EventIdentity,\n id: Schema.String,\n name: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolInputDelta extends Schema.TaggedClass<ToolInputDelta>()('ToolInputDelta', {\n ...EventIdentity,\n id: Schema.String,\n delta: Schema.String\n}) {}\n\nexport class ToolInputEnd extends Schema.TaggedClass<ToolInputEnd>()('ToolInputEnd', {\n ...EventIdentity,\n call: ToolCall\n}) {}\n\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>()(\n 'ToolApprovalRequested',\n {\n ...EventIdentity,\n call: ToolCall,\n request: Schema.optional(ToolApprovalRequest)\n }\n) {}\n\nexport class ToolApprovalGranted extends Schema.TaggedClass<ToolApprovalGranted>()(\n 'ToolApprovalGranted',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class ToolApprovalDenied extends Schema.TaggedClass<ToolApprovalDenied>()(\n 'ToolApprovalDenied',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n reason: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class QuestionRequested extends Schema.TaggedClass<QuestionRequested>()('QuestionRequested', {\n ...EventIdentity,\n request: QuestionRequest\n}) {}\n\nexport class QuestionAnswered extends Schema.TaggedClass<QuestionAnswered>()('QuestionAnswered', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class QuestionCancelled extends Schema.TaggedClass<QuestionCancelled>()('QuestionCancelled', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class LLMStreamEnd extends Schema.TaggedClass<LLMStreamEnd>()('LLMStreamEnd', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class AssistantMessageEvent extends Schema.TaggedClass<AssistantMessageEvent>()(\n 'AssistantMessage',\n {\n ...EventIdentity,\n message: AssistantAgentMessage\n }\n) {}\n\nexport class ToolExecutionStarted extends Schema.TaggedClass<ToolExecutionStarted>()(\n 'ToolExecutionStarted',\n {\n ...EventIdentity,\n call: ToolCall\n }\n) {}\n\nexport class ToolExecutionCompleted extends Schema.TaggedClass<ToolExecutionCompleted>()(\n 'ToolExecutionCompleted',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class ToolExecutionError extends Schema.TaggedClass<ToolExecutionError>()(\n 'ToolExecutionError',\n {\n ...EventIdentity,\n call: ToolCall,\n message: Schema.String,\n code: AgentErrorCode\n }\n) {}\n\nexport class ProviderToolResult extends Schema.TaggedClass<ProviderToolResult>()(\n 'ProviderToolResult',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>()('SubagentStarted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String\n}) {}\n\nexport class SubagentCompleted extends Schema.TaggedClass<SubagentCompleted>()('SubagentCompleted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String,\n status: SubagentStatus,\n durationMs: Schema.Number,\n summary: Schema.optional(Schema.String)\n}) {}\n\nexport const makeSubagentRunId = (parentToolCallId: string) => `subagent:${parentToolCallId}`\n\nexport const AgentEvent = Schema.Union([\n AgentStart,\n AgentError,\n AgentEnd,\n AgentAwaitingInput,\n UsageUpdate,\n AgentRetry,\n CompactionStart,\n CompactionEnd,\n TurnStart,\n TurnEnd,\n LLMStreamStart,\n LLMTextDelta,\n LLMReasoningDelta,\n ToolInputStart,\n ToolInputDelta,\n ToolInputEnd,\n LLMStreamEnd,\n AssistantMessageEvent,\n ToolApprovalRequested,\n ToolApprovalGranted,\n ToolApprovalDenied,\n QuestionRequested,\n QuestionAnswered,\n QuestionCancelled,\n ToolExecutionStarted,\n ToolExecutionCompleted,\n ToolExecutionError,\n ProviderToolResult,\n SubagentStarted,\n SubagentCompleted\n])\nexport type AgentEvent = typeof AgentEvent.Type\n"],"mappings":";;;;;AAaA,MAAM,wBAAwB,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO,WAAW,CAAC,CAAC;AAEnF,MAAM,gBAAgB;CACpB,SAAS,OAAO,SAAS,qBAAqB;CAC9C,aAAa,OAAO,SAAS,OAAO,MAAM;AAC5C;AAEA,MAAa,iBAAiB,OAAO,SAAS;CAAC;CAAW;CAAa;AAAO,CAAC;AAG/E,MAAa,iBAAiB,OAAO,SAAS;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,IAAa,aAAb,cAAgC,OAAO,YAAwB,EAAE,cAAc,EAC7E,GAAG,cACL,CAAC,EAAE,CAAC;AAEJ,IAAa,aAAb,cAAgC,OAAO,YAAwB,EAAE,cAAc;CAC7E,GAAG;CACH,MAAM;CACN,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CAAC,EAAE,CAAC;AAEJ,IAAa,WAAb,cAA8B,OAAO,YAAsB,EAAE,YAAY;CACvE,GAAG;CACH,UAAU,OAAO,MAAM,YAAY;CACnC,OAAO,OAAO;CACd,OAAO;AACT,CAAC,EAAE,CAAC;AAEJ,IAAa,qBAAb,cAAwC,OAAO,YAAgC,EAC7E,sBACA;CACE,GAAG;CACH,UAAU,OAAO,cAAc,WAAW;CAC1C,UAAU,OAAO,MAAM,YAAY;CACnC,OAAO,OAAO;CACd,OAAO;AACT,CACF,EAAE,CAAC;AAEH,IAAa,cAAb,cAAiC,OAAO,YAAyB,EAAE,eAAe;CAChF,GAAG;CACH,OAAO;AACT,CAAC,EAAE,CAAC;AAEJ,IAAa,aAAb,cAAgC,OAAO,YAAwB,EAAE,cAA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CAAC;AAEH,IAAa,qBAAb,cAAwC,OAAO,YAAgC,EAC7E,sBACA;CACE,GAAG;CACH,MAAM;CACN,SAAS,OAAO;CAChB,MAAM;AACR,CACF,EAAE,CAAC;AAEH,IAAa,qBAAb,cAAwC,OAAO,YAAgC,EAC7E,sBACA;CACE,GAAG;CACH,MAAM;CACN,QAAQ;AACV,CACF,EAAE,CAAC;AAEH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,EAAE,mBAAmB;CAC5F,GAAG;CACH,kBAAkB;CAClB,eAAe;CACf,cAAc;CACd,aAAa,OAAO;CACpB,OAAO,OAAO;AAChB,CAAC,EAAE,CAAC;AAEJ,IAAa,oBAAb,cAAuC,OAAO,YAA+B,EAAE,qBAAqB;CAClG,GAAG;CACH,kBAAkB;CAClB,eAAe;CACf,cAAc;CACd,aAAa,OAAO;CACpB,OAAO,OAAO;CACd,QAAQ;CACR,YAAY,OAAO;CACnB,SAAS,OAAO,SAAS,OAAO,MAAM;AACxC,CAAC,EAAE,CAAC;AAEJ,MAAa,qBAAqB,qBAA6B,YAAY;AAE3E,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
@@ -3,12 +3,12 @@ import { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToConte
|
|
|
3
3
|
import { HitlRequest, HitlResponse, HitlResponseSource, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent } from "./tool.mjs";
|
|
4
4
|
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
|
-
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate } from "./event.mjs";
|
|
6
|
+
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
8
8
|
import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
|
|
9
9
|
|
|
10
10
|
//#region src/protocol/index.d.ts
|
|
11
11
|
type MessageId = string;
|
|
12
12
|
//#endregion
|
|
13
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageId, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, textImageModelCapabilities, textOnlyModelCapabilities, zeroAgentUsage };
|
|
13
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageId, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, makeSubagentRunId, textImageModelCapabilities, textOnlyModelCapabilities, zeroAgentUsage };
|
|
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":";;;;;;;;;;KA6GY,SAAA"}
|
package/dist/protocol/index.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { AudioPart, Content, ContentPart, ImagePart, TextPart, appendTextToConte
|
|
|
3
3
|
import { HitlRequest, HitlResponse, HitlResponseSource, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent } from "./tool.mjs";
|
|
4
4
|
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
|
-
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate } from "./event.mjs";
|
|
6
|
+
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
8
8
|
import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
|
|
9
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, textImageModelCapabilities, textOnlyModelCapabilities, zeroAgentUsage };
|
|
9
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, formatQuestionResponseContent, isContentEmpty, makeSubagentRunId, textImageModelCapabilities, textOnlyModelCapabilities, zeroAgentUsage };
|
package/dist/tools/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { EmptyToolParams, ResolvedToolSet, SchemaToolExecutionInput, ToolAccess, ToolExecutionInput, ToolMetadata, ToolModule, ToolRegistration, ToolRegistryError, makeTool, makeToolExecutorLayer, resolveTools } from "./registry.mjs";
|
|
2
2
|
import { QuestionExecutionInput, QuestionToolOptions, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, questionToolName } from "./question.mjs";
|
|
3
|
-
import { TaskExecutionInput, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, formatTaskResult, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, taskToolName } from "./task.mjs";
|
|
4
|
-
export { EmptyToolParams, type QuestionExecutionInput, type QuestionToolOptions, type ResolvedToolSet, type SchemaToolExecutionInput, type TaskExecutionInput, type TaskSubagentDefinition, type TaskToolOptions, type TaskToolParams, ToolAccess, type ToolExecutionInput, type ToolMetadata, type ToolModule, type ToolRegistration, ToolRegistryError, formatTaskResult, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTool, makeToolExecutorLayer, questionToolName, resolveTools, taskToolName };
|
|
3
|
+
import { TaskExecutionInput, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName } from "./task.mjs";
|
|
4
|
+
export { EmptyToolParams, type QuestionExecutionInput, type QuestionToolOptions, type ResolvedToolSet, type SchemaToolExecutionInput, type TaskExecutionInput, type TaskSubagentContext, type TaskSubagentDefinition, type TaskToolOptions, type TaskToolParams, type TaskToolResultInput, ToolAccess, type ToolExecutionInput, type ToolMetadata, type ToolModule, type ToolRegistration, ToolRegistryError, formatTaskResult, makeNonRecursiveTaskToolModule, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, makeTool, makeToolExecutorLayer, questionToolName, resolveTools, subagentResultText, taskSubagentRunId, taskToolName };
|
package/dist/tools/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { EmptyToolParams, ToolAccess, ToolRegistryError, makeTool, makeToolExecutorLayer, resolveTools } from "./registry.mjs";
|
|
2
2
|
import { makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, questionToolName } from "./question.mjs";
|
|
3
|
-
import { formatTaskResult, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, taskToolName } from "./task.mjs";
|
|
4
|
-
export { EmptyToolParams, ToolAccess, ToolRegistryError, formatTaskResult, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTool, makeToolExecutorLayer, questionToolName, resolveTools, taskToolName };
|
|
3
|
+
import { formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName } from "./task.mjs";
|
|
4
|
+
export { EmptyToolParams, ToolAccess, ToolRegistryError, formatTaskResult, makeNonRecursiveTaskToolModule, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, makeTool, makeToolExecutorLayer, questionToolName, resolveTools, subagentResultText, taskSubagentRunId, taskToolName };
|
package/dist/tools/task.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ToolModule, ToolRegistration } from "./registry.mjs";
|
|
1
|
+
import { ToolModule, ToolRegistration, ToolRegistryError } from "./registry.mjs";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
|
-
import { ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
4
|
+
import { AgentEvent, ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
5
5
|
import { ToolError } from "@yolk-sdk/agent/loop";
|
|
6
6
|
|
|
7
7
|
//#region src/tools/task.d.ts
|
|
@@ -16,6 +16,9 @@ type TaskSubagentDefinition = {
|
|
|
16
16
|
readonly name: string;
|
|
17
17
|
readonly description: string;
|
|
18
18
|
};
|
|
19
|
+
type TaskSubagentContext = {
|
|
20
|
+
readonly subagent?: boolean;
|
|
21
|
+
};
|
|
19
22
|
type TaskExecutionInput<Context> = {
|
|
20
23
|
readonly call: ToolCall;
|
|
21
24
|
readonly context: Context;
|
|
@@ -23,12 +26,28 @@ type TaskExecutionInput<Context> = {
|
|
|
23
26
|
};
|
|
24
27
|
type TaskToolOptions<Context> = {
|
|
25
28
|
readonly subagents: ReadonlyArray<TaskSubagentDefinition>;
|
|
29
|
+
readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>;
|
|
26
30
|
readonly execute: (input: TaskExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>;
|
|
27
31
|
};
|
|
32
|
+
type TaskToolResultInput = {
|
|
33
|
+
readonly callId: string;
|
|
34
|
+
readonly output: string;
|
|
35
|
+
readonly subagentType: string;
|
|
36
|
+
readonly description: string;
|
|
37
|
+
readonly subagentRunId: string;
|
|
38
|
+
readonly startedAtMs: number;
|
|
39
|
+
readonly endedAtMs: number;
|
|
40
|
+
readonly model: string;
|
|
41
|
+
readonly isError?: boolean;
|
|
42
|
+
};
|
|
28
43
|
declare const makeTaskToolRegistration: <Context>(options: TaskToolOptions<Context>) => ToolRegistration<Context>;
|
|
29
44
|
declare const makeTaskToolDef: (subagents: ReadonlyArray<TaskSubagentDefinition>) => import("@yolk-sdk/agent/protocol").ToolDef;
|
|
30
45
|
declare const makeTaskToolModule: <Context>(options: TaskToolOptions<Context>) => ToolModule<Context>;
|
|
46
|
+
declare const makeNonRecursiveTaskToolModule: <Context extends TaskSubagentContext>(options: TaskToolOptions<Context>) => ToolModule<Context>;
|
|
31
47
|
declare const formatTaskResult: (output: string) => string;
|
|
48
|
+
declare const taskSubagentRunId: (parentToolCallId: string) => string;
|
|
49
|
+
declare const subagentResultText: (events: ReadonlyArray<AgentEvent>) => string;
|
|
50
|
+
declare const makeTaskToolResult: (input: TaskToolResultInput) => ToolResult;
|
|
32
51
|
//#endregion
|
|
33
|
-
export { TaskExecutionInput, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, formatTaskResult, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, taskToolName };
|
|
52
|
+
export { TaskExecutionInput, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName };
|
|
34
53
|
//# sourceMappingURL=task.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task.d.mts","names":[],"sources":["../../src/tools/task.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"task.d.mts","names":[],"sources":["../../src/tools/task.ts"],"mappings":";;;;;;;cAca,YAAA;AAAA,cAEP,cAAA,EAAc,MAAA,CAAA,MAAA;EAAA;;;;KAYR,cAAA,UAAwB,cAAA,CAAe,IAAI;AAAA,KAE3C,sBAAA;EAAA,SACD,IAAA;EAAA,SACA,WAAW;AAAA;AAAA,KAGV,mBAAA;EAAA,SACD,QAAQ;AAAA;AAAA,KAGP,kBAAA;EAAA,SACD,IAAA,EAAM,QAAA;EAAA,SACN,OAAA,EAAS,OAAA;EAAA,SACT,MAAA,EAAQ,cAAA;AAAA;AAAA,KAGP,eAAA;EAAA,SACD,SAAA,EAAW,aAAA,CAAc,sBAAA;EAAA,SACzB,SAAA,IAAa,OAAA,EAAS,OAAA,KAAY,MAAA,CAAO,MAAA,UAAgB,iBAAA;EAAA,SACzD,OAAA,GAAU,KAAA,EAAO,kBAAA,CAAmB,OAAA,MAAa,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,SAAA;AAAA;AAAA,KAG1E,mBAAA;EAAA,SACD,MAAA;EAAA,SACA,MAAA;EAAA,SACA,YAAA;EAAA,SACA,WAAA;EAAA,SACA,aAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;AAAA;AAAA,cAgEE,wBAAA,YACX,OAAA,EAAS,eAAA,CAAgB,OAAA,MACxB,gBAAA,CAAiB,OAAA;AAAA,cAoBP,eAAA,GAAmB,SAAA,EAAW,aAAa,CAAC,sBAAA,yCAAuB,OAAA;AAAA,cAMnE,kBAAA,YAA+B,OAAA,EAAS,eAAA,CAAgB,OAAA,MAAW,UAAA,CAAW,OAAA;AAAA,cAK9E,8BAAA,mBAAkD,mBAAA,EAC7D,OAAA,EAAS,eAAA,CAAgB,OAAA,MACxB,UAAA,CAAW,OAAA;AAAA,cASD,gBAAA,GAAoB,MAAc;AAAA,cAElC,iBAAA,GAAiB,gBAAA;AAAA,cAQjB,kBAAA,GAAsB,MAAA,EAAQ,aAAa,CAAC,UAAA;AAAA,cAO5C,kBAAA,GAAsB,KAAA,EAAO,mBAAA,KAAmB,UAc3D"}
|
package/dist/tools/task.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { makeTool } from "./registry.mjs";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
|
-
import { ToolResult } from "@yolk-sdk/agent/protocol";
|
|
4
|
+
import { ToolResult, assistantContent, contentText, makeSubagentRunId } from "@yolk-sdk/agent/protocol";
|
|
5
5
|
import { ToolError } from "@yolk-sdk/agent/loop";
|
|
6
6
|
//#region src/tools/task.ts
|
|
7
7
|
const taskToolName = "task";
|
|
@@ -47,6 +47,7 @@ const makeTaskToolRegistration = (options) => makeTool({
|
|
|
47
47
|
description: taskToolDescription(options.subagents),
|
|
48
48
|
parameters: TaskToolParams,
|
|
49
49
|
access: "read",
|
|
50
|
+
isEnabled: options.isEnabled,
|
|
50
51
|
invalidParamsMessage: (error) => `Invalid task arguments: ${error instanceof Error ? error.message : String(error)}`,
|
|
51
52
|
execute: ({ call, context, params }) => Effect.gen(function* () {
|
|
52
53
|
if (call.name !== "task") return yield* Effect.fail(taskToolError(`Tool is not configured: ${call.name}`, "not_found"));
|
|
@@ -70,12 +71,40 @@ const makeTaskToolModule = (options) => ({
|
|
|
70
71
|
id: "task",
|
|
71
72
|
tools: [makeTaskToolRegistration(options)]
|
|
72
73
|
});
|
|
74
|
+
const makeNonRecursiveTaskToolModule = (options) => makeTaskToolModule({
|
|
75
|
+
...options,
|
|
76
|
+
isEnabled: (context) => context.subagent === true ? Effect.succeed(false) : options.isEnabled === void 0 ? Effect.succeed(true) : options.isEnabled(context)
|
|
77
|
+
});
|
|
73
78
|
const formatTaskResult = (output) => [
|
|
74
79
|
"<task_result>",
|
|
75
80
|
output,
|
|
76
81
|
"</task_result>"
|
|
77
82
|
].join("\n");
|
|
83
|
+
const taskSubagentRunId = makeSubagentRunId;
|
|
84
|
+
const latestAssistantText = (messages) => {
|
|
85
|
+
const assistant = [...messages].reverse().find((message) => message._tag === "Assistant");
|
|
86
|
+
return assistant === void 0 ? "" : contentText(assistantContent(assistant));
|
|
87
|
+
};
|
|
88
|
+
const subagentResultText = (events) => {
|
|
89
|
+
const text = latestAssistantText([...events].reverse().find((event) => event._tag === "AgentEnd")?.messages ?? []).trim();
|
|
90
|
+
return text.length === 0 ? "Subagent completed without a final text response." : text;
|
|
91
|
+
};
|
|
92
|
+
const makeTaskToolResult = (input) => ToolResult.make({
|
|
93
|
+
toolCallId: input.callId,
|
|
94
|
+
content: formatTaskResult(input.output),
|
|
95
|
+
isError: input.isError,
|
|
96
|
+
structuredContent: {
|
|
97
|
+
subagent_run_id: input.subagentRunId,
|
|
98
|
+
subagent_type: input.subagentType,
|
|
99
|
+
description: input.description,
|
|
100
|
+
started_at_ms: input.startedAtMs,
|
|
101
|
+
ended_at_ms: input.endedAtMs,
|
|
102
|
+
duration_ms: Math.max(0, input.endedAtMs - input.startedAtMs),
|
|
103
|
+
status: input.isError === true ? "error" : "completed",
|
|
104
|
+
model: input.model
|
|
105
|
+
}
|
|
106
|
+
});
|
|
78
107
|
//#endregion
|
|
79
|
-
export { formatTaskResult, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, taskToolName };
|
|
108
|
+
export { formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName };
|
|
80
109
|
|
|
81
110
|
//# sourceMappingURL=task.mjs.map
|
package/dist/tools/task.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task.mjs","names":[],"sources":["../../src/tools/task.ts"],"sourcesContent":["import { Effect } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { ToolError } from '@yolk-sdk/agent/loop'\nimport {
|
|
1
|
+
{"version":3,"file":"task.mjs","names":[],"sources":["../../src/tools/task.ts"],"sourcesContent":["import { Effect } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { ToolError } from '@yolk-sdk/agent/loop'\nimport {\n assistantContent,\n contentText,\n makeSubagentRunId,\n ToolResult,\n type AgentEvent,\n type AgentMessage,\n type ToolCall\n} from '@yolk-sdk/agent/protocol'\nimport { makeTool, type ToolModule, type ToolRegistration, type ToolRegistryError } from './registry.ts'\n\nexport const taskToolName = 'task'\n\nconst TaskToolParams = Schema.Struct({\n description: Schema.String.pipe(Schema.annotate({ description: 'A short 3-5 word description of the task.' })),\n prompt: Schema.String.pipe(\n Schema.annotate({\n description: 'The complete task instructions for the subagent, including all context it needs.'\n })\n ),\n subagent_type: Schema.String.pipe(\n Schema.annotate({ description: 'The specialized subagent type to use for this task.' })\n )\n})\n\nexport type TaskToolParams = typeof TaskToolParams.Type\n\nexport type TaskSubagentDefinition = {\n readonly name: string\n readonly description: string\n}\n\nexport type TaskSubagentContext = {\n readonly subagent?: boolean\n}\n\nexport type TaskExecutionInput<Context> = {\n readonly call: ToolCall\n readonly context: Context\n readonly params: TaskToolParams\n}\n\nexport type TaskToolOptions<Context> = {\n readonly subagents: ReadonlyArray<TaskSubagentDefinition>\n readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>\n readonly execute: (input: TaskExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>\n}\n\nexport type TaskToolResultInput = {\n readonly callId: string\n readonly output: string\n readonly subagentType: string\n readonly description: string\n readonly subagentRunId: string\n readonly startedAtMs: number\n readonly endedAtMs: number\n readonly model: string\n readonly isError?: boolean\n}\n\nconst taskToolError = (message: string, cause: ToolError['cause']) =>\n new ToolError({\n tool: taskToolName,\n message,\n cause\n })\n\nconst trimmedTaskParams = (params: TaskToolParams) => ({\n description: params.description.trim(),\n prompt: params.prompt.trim(),\n subagent_type: params.subagent_type.trim()\n})\n\nconst validateTaskParams = (params: TaskToolParams) => {\n const trimmed = trimmedTaskParams(params)\n\n if (trimmed.description.length === 0) {\n return Effect.fail(taskToolError('description must not be empty', 'validation'))\n }\n\n if (trimmed.prompt.length === 0) {\n return Effect.fail(taskToolError('prompt must not be empty', 'validation'))\n }\n\n if (trimmed.subagent_type.length === 0) {\n return Effect.fail(taskToolError('subagent_type must not be empty', 'validation'))\n }\n\n return Effect.succeed(trimmed)\n}\n\nconst findSubagent = (subagents: ReadonlyArray<TaskSubagentDefinition>, name: string) =>\n subagents.find(subagent => subagent.name === name)\n\nconst requireKnownSubagent = (\n subagents: ReadonlyArray<TaskSubagentDefinition>,\n name: string\n) => {\n const subagent = findSubagent(subagents, name)\n\n return subagent === undefined\n ? Effect.fail(taskToolError(`Unknown subagent type: ${name}`, 'validation'))\n : Effect.succeed(subagent)\n}\n\nconst subagentDescription = (subagent: TaskSubagentDefinition) =>\n `- ${subagent.name}: ${subagent.description}`\n\nconst taskToolDescription = (subagents: ReadonlyArray<TaskSubagentDefinition>) =>\n [\n 'Launch a new agent to handle complex, multistep tasks autonomously.',\n 'Use this when delegating focused work to a specialized subagent would save context or allow parallel exploration.',\n 'To run subagents in parallel, call this task tool multiple times in the same assistant response.',\n 'Yolk runs same-turn task calls concurrently automatically.',\n 'A fresh subagent only sees the prompt you provide, so include all required context.',\n 'Subagents can use their normal tools but cannot launch further task subagents in v1.',\n subagents.length === 0\n ? 'No subagent types are currently available.'\n : `Available subagent types:\\n${subagents.map(subagentDescription).join('\\n')}`\n ].join('\\n\\n')\n\nexport const makeTaskToolRegistration = <Context>(\n options: TaskToolOptions<Context>\n): ToolRegistration<Context> => makeTool({\n name: taskToolName,\n description: taskToolDescription(options.subagents),\n parameters: TaskToolParams,\n access: 'read',\n isEnabled: options.isEnabled,\n invalidParamsMessage: error => `Invalid task arguments: ${error instanceof Error ? error.message : String(error)}`,\n execute: ({ call, context, params }) =>\n Effect.gen(function* () {\n if (call.name !== taskToolName) {\n return yield* Effect.fail(taskToolError(`Tool is not configured: ${call.name}`, 'not_found'))\n }\n\n const normalizedParams = yield* validateTaskParams(params)\n yield* requireKnownSubagent(options.subagents, normalizedParams.subagent_type)\n\n return yield* options.execute({ call, context, params: normalizedParams })\n })\n})\n\nexport const makeTaskToolDef = (subagents: ReadonlyArray<TaskSubagentDefinition>) =>\n makeTaskToolRegistration({\n subagents,\n execute: ({ call }) => Effect.succeed(ToolResult.make({ toolCallId: call.id, content: '' }))\n }).def\n\nexport const makeTaskToolModule = <Context>(options: TaskToolOptions<Context>): ToolModule<Context> => ({\n id: 'task',\n tools: [makeTaskToolRegistration(options)]\n})\n\nexport const makeNonRecursiveTaskToolModule = <Context extends TaskSubagentContext>(\n options: TaskToolOptions<Context>\n): ToolModule<Context> => makeTaskToolModule({\n ...options,\n isEnabled: context => context.subagent === true\n ? Effect.succeed(false)\n : options.isEnabled === undefined\n ? Effect.succeed(true)\n : options.isEnabled(context)\n})\n\nexport const formatTaskResult = (output: string) => ['<task_result>', output, '</task_result>'].join('\\n')\n\nexport const taskSubagentRunId = makeSubagentRunId\n\nconst latestAssistantText = (messages: ReadonlyArray<AgentMessage>) => {\n const assistant = [...messages].reverse().find(message => message._tag === 'Assistant')\n\n return assistant === undefined ? '' : contentText(assistantContent(assistant))\n}\n\nexport const subagentResultText = (events: ReadonlyArray<AgentEvent>) => {\n const messages = [...events].reverse().find(event => event._tag === 'AgentEnd')?.messages ?? []\n const text = latestAssistantText(messages).trim()\n\n return text.length === 0 ? 'Subagent completed without a final text response.' : text\n}\n\nexport const makeTaskToolResult = (input: TaskToolResultInput) => ToolResult.make({\n toolCallId: input.callId,\n content: formatTaskResult(input.output),\n isError: input.isError,\n structuredContent: {\n subagent_run_id: input.subagentRunId,\n subagent_type: input.subagentType,\n description: input.description,\n started_at_ms: input.startedAtMs,\n ended_at_ms: input.endedAtMs,\n duration_ms: Math.max(0, input.endedAtMs - input.startedAtMs),\n status: input.isError === true ? 'error' : 'completed',\n model: input.model\n }\n})\n"],"mappings":";;;;;;AAcA,MAAa,eAAe;AAE5B,MAAM,iBAAiB,OAAO,OAAO;CACnC,aAAa,OAAO,OAAO,KAAK,OAAO,SAAS,EAAE,aAAa,4CAA4C,CAAC,CAAC;CAC7G,QAAQ,OAAO,OAAO,KACpB,OAAO,SAAS,EACd,aAAa,mFACf,CAAC,CACH;CACA,eAAe,OAAO,OAAO,KAC3B,OAAO,SAAS,EAAE,aAAa,sDAAsD,CAAC,CACxF;AACF,CAAC;AAqCD,MAAM,iBAAiB,SAAiB,UACtC,IAAI,UAAU;CACZ,MAAM;CACN;CACA;AACF,CAAC;AAEH,MAAM,qBAAqB,YAA4B;CACrD,aAAa,OAAO,YAAY,KAAK;CACrC,QAAQ,OAAO,OAAO,KAAK;CAC3B,eAAe,OAAO,cAAc,KAAK;AAC3C;AAEA,MAAM,sBAAsB,WAA2B;CACrD,MAAM,UAAU,kBAAkB,MAAM;CAExC,IAAI,QAAQ,YAAY,WAAW,GACjC,OAAO,OAAO,KAAK,cAAc,iCAAiC,YAAY,CAAC;CAGjF,IAAI,QAAQ,OAAO,WAAW,GAC5B,OAAO,OAAO,KAAK,cAAc,4BAA4B,YAAY,CAAC;CAG5E,IAAI,QAAQ,cAAc,WAAW,GACnC,OAAO,OAAO,KAAK,cAAc,mCAAmC,YAAY,CAAC;CAGnF,OAAO,OAAO,QAAQ,OAAO;AAC/B;AAEA,MAAM,gBAAgB,WAAkD,SACtE,UAAU,MAAK,aAAY,SAAS,SAAS,IAAI;AAEnD,MAAM,wBACJ,WACA,SACG;CACH,MAAM,WAAW,aAAa,WAAW,IAAI;CAE7C,OAAO,aAAa,KAAA,IAChB,OAAO,KAAK,cAAc,0BAA0B,QAAQ,YAAY,CAAC,IACzE,OAAO,QAAQ,QAAQ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AAE,KAAK,IAAI;AAEzG,MAAa,oBAAoB;AAEjC,MAAM,uBAAuB,aAA0C;CACrE,MAAM,YAAY,CAAC,GAAG,QAAQ,EAAE,QAAQ,EAAE,MAAK,YAAW,QAAQ,SAAS,WAAW;CAEtF,OAAO,cAAc,KAAA,IAAY,KAAK,YAAY,iBAAiB,SAAS,CAAC;AAC/E;AAEA,MAAa,sBAAsB,WAAsC;CAEvE,MAAM,OAAO,oBADI,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAK,UAAS,MAAM,SAAS,UAAU,GAAG,YAAY,CAAC,CACrD,EAAE,KAAK;CAEhD,OAAO,KAAK,WAAW,IAAI,sDAAsD;AACnF;AAEA,MAAa,sBAAsB,UAA+B,WAAW,KAAK;CAChF,YAAY,MAAM;CAClB,SAAS,iBAAiB,MAAM,MAAM;CACtC,SAAS,MAAM;CACf,mBAAmB;EACjB,iBAAiB,MAAM;EACvB,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,aAAa,KAAK,IAAI,GAAG,MAAM,YAAY,MAAM,WAAW;EAC5D,QAAQ,MAAM,YAAY,OAAO,UAAU;EAC3C,OAAO,MAAM;CACf;AACF,CAAC"}
|
package/package.json
CHANGED
package/src/loop/run.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
QuestionRequest,
|
|
31
31
|
QuestionToolParams,
|
|
32
32
|
formatQuestionResponseContent,
|
|
33
|
+
makeSubagentRunId,
|
|
33
34
|
ToolApprovalRequest,
|
|
34
35
|
ToolResultMessage,
|
|
35
36
|
SubagentCompleted,
|
|
@@ -123,7 +124,7 @@ const taskCallMetadata = (call: ToolCall): TaskCallMetadata | undefined => {
|
|
|
123
124
|
}
|
|
124
125
|
|
|
125
126
|
return {
|
|
126
|
-
subagentRunId:
|
|
127
|
+
subagentRunId: makeSubagentRunId(call.id),
|
|
127
128
|
subagentType,
|
|
128
129
|
description
|
|
129
130
|
}
|
package/src/protocol/event.ts
CHANGED
|
@@ -251,6 +251,8 @@ export class SubagentCompleted extends Schema.TaggedClass<SubagentCompleted>()('
|
|
|
251
251
|
summary: Schema.optional(Schema.String)
|
|
252
252
|
}) {}
|
|
253
253
|
|
|
254
|
+
export const makeSubagentRunId = (parentToolCallId: string) => `subagent:${parentToolCallId}`
|
|
255
|
+
|
|
254
256
|
export const AgentEvent = Schema.Union([
|
|
255
257
|
AgentStart,
|
|
256
258
|
AgentError,
|
package/src/protocol/index.ts
CHANGED
package/src/tools/README.md
CHANGED
|
@@ -9,6 +9,7 @@ Generic host tool registration and resolution.
|
|
|
9
9
|
- Duplicate tool name validation.
|
|
10
10
|
- Adapter from resolved tools to `@yolk-sdk/agent/loop` `ToolExecutor`.
|
|
11
11
|
- Package-owned `task` and `question` tool contracts.
|
|
12
|
+
- Helpers for task subagent result metadata and non-recursive task tool exposure.
|
|
12
13
|
|
|
13
14
|
## Use it when
|
|
14
15
|
|
|
@@ -20,3 +21,74 @@ Generic host tool registration and resolution.
|
|
|
20
21
|
- No app tool catalogs.
|
|
21
22
|
- No provider SDKs.
|
|
22
23
|
- Tool access/approval is metadata; host apps enforce product policy.
|
|
24
|
+
|
|
25
|
+
## Task subagents
|
|
26
|
+
|
|
27
|
+
`task` is the standard tool for delegating focused work to a subagent. The SDK owns the
|
|
28
|
+
tool schema, validation, event metadata shape, and result formatting. Host apps still own
|
|
29
|
+
execution: model choice, provider layer, prompt, auth, concrete tools, storage, and policy.
|
|
30
|
+
|
|
31
|
+
Use `makeNonRecursiveTaskToolModule` for the top-level agent so nested subagents do not receive
|
|
32
|
+
`task` again:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { Clock, Effect, Stream } from 'effect'
|
|
36
|
+
import { run } from '@yolk-sdk/agent/loop'
|
|
37
|
+
import { makeSubagentRunId, UserMessage } from '@yolk-sdk/agent/protocol'
|
|
38
|
+
import {
|
|
39
|
+
makeNonRecursiveTaskToolModule,
|
|
40
|
+
makeTaskToolResult,
|
|
41
|
+
makeToolExecutorLayer,
|
|
42
|
+
subagentResultText,
|
|
43
|
+
type TaskSubagentContext
|
|
44
|
+
} from '@yolk-sdk/agent/tools'
|
|
45
|
+
|
|
46
|
+
type ToolContext = TaskSubagentContext & {
|
|
47
|
+
readonly sessionId: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const taskToolModule = makeNonRecursiveTaskToolModule<ToolContext>({
|
|
51
|
+
subagents: [
|
|
52
|
+
{ name: 'general', description: 'Handle complex multi-step work.' },
|
|
53
|
+
{ name: 'explore', description: 'Explore code and docs.' }
|
|
54
|
+
],
|
|
55
|
+
execute: ({ call, context, params }) =>
|
|
56
|
+
Effect.gen(function* () {
|
|
57
|
+
const startedAtMs = yield* Clock.currentTimeMillis
|
|
58
|
+
const subagentRunId = makeSubagentRunId(call.id)
|
|
59
|
+
const subagentToolSet = yield* resolveSubagentToolSet({
|
|
60
|
+
...context,
|
|
61
|
+
subagent: true
|
|
62
|
+
})
|
|
63
|
+
const events = yield* run({
|
|
64
|
+
messages: [UserMessage.make({ content: params.prompt })],
|
|
65
|
+
systemPrompt: subagentSystemPrompt(params.subagent_type),
|
|
66
|
+
tools: subagentToolSet.tools,
|
|
67
|
+
model: 'gpt-5.5'
|
|
68
|
+
}).pipe(Stream.runCollect, Effect.provide(makeToolExecutorLayer(subagentToolSet)))
|
|
69
|
+
const endedAtMs = yield* Clock.currentTimeMillis
|
|
70
|
+
|
|
71
|
+
return makeTaskToolResult({
|
|
72
|
+
callId: call.id,
|
|
73
|
+
output: subagentResultText(Array.from(events)),
|
|
74
|
+
subagentType: params.subagent_type,
|
|
75
|
+
description: params.description,
|
|
76
|
+
subagentRunId,
|
|
77
|
+
startedAtMs,
|
|
78
|
+
endedAtMs,
|
|
79
|
+
model: 'gpt-5.5'
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
})
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Host apps should usually resolve a smaller subagent toolset:
|
|
86
|
+
|
|
87
|
+
- include read/search tools that help delegated work
|
|
88
|
+
- exclude `task` to prevent recursion
|
|
89
|
+
- exclude write/destructive tools unless explicitly safe for autonomous subagents
|
|
90
|
+
- pass a fresh or derived session id so subagent work is traceable
|
|
91
|
+
|
|
92
|
+
The loop emits normal tool lifecycle events plus `SubagentStarted` / `SubagentCompleted` around
|
|
93
|
+
`task` calls. Same-turn sibling `task` calls run concurrently through the standard parallel tool
|
|
94
|
+
batch behavior.
|
package/src/tools/index.ts
CHANGED
|
@@ -7,9 +7,13 @@ export {
|
|
|
7
7
|
} from './question.ts'
|
|
8
8
|
export {
|
|
9
9
|
formatTaskResult,
|
|
10
|
+
makeNonRecursiveTaskToolModule,
|
|
11
|
+
makeTaskToolResult,
|
|
10
12
|
makeTaskToolDef,
|
|
11
13
|
makeTaskToolModule,
|
|
12
14
|
makeTaskToolRegistration,
|
|
15
|
+
subagentResultText,
|
|
16
|
+
taskSubagentRunId,
|
|
13
17
|
taskToolName
|
|
14
18
|
} from './task.ts'
|
|
15
19
|
export type {
|
|
@@ -23,7 +27,9 @@ export type {
|
|
|
23
27
|
export type { QuestionExecutionInput, QuestionToolOptions } from './question.ts'
|
|
24
28
|
export type {
|
|
25
29
|
TaskExecutionInput,
|
|
30
|
+
TaskSubagentContext,
|
|
26
31
|
TaskSubagentDefinition,
|
|
27
32
|
TaskToolOptions,
|
|
28
|
-
TaskToolParams
|
|
33
|
+
TaskToolParams,
|
|
34
|
+
TaskToolResultInput
|
|
29
35
|
} from './task.ts'
|
package/src/tools/task.ts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
import { Effect } from 'effect'
|
|
2
2
|
import * as Schema from 'effect/Schema'
|
|
3
3
|
import { ToolError } from '@yolk-sdk/agent/loop'
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import {
|
|
5
|
+
assistantContent,
|
|
6
|
+
contentText,
|
|
7
|
+
makeSubagentRunId,
|
|
8
|
+
ToolResult,
|
|
9
|
+
type AgentEvent,
|
|
10
|
+
type AgentMessage,
|
|
11
|
+
type ToolCall
|
|
12
|
+
} from '@yolk-sdk/agent/protocol'
|
|
13
|
+
import { makeTool, type ToolModule, type ToolRegistration, type ToolRegistryError } from './registry.ts'
|
|
6
14
|
|
|
7
15
|
export const taskToolName = 'task'
|
|
8
16
|
|
|
@@ -25,6 +33,10 @@ export type TaskSubagentDefinition = {
|
|
|
25
33
|
readonly description: string
|
|
26
34
|
}
|
|
27
35
|
|
|
36
|
+
export type TaskSubagentContext = {
|
|
37
|
+
readonly subagent?: boolean
|
|
38
|
+
}
|
|
39
|
+
|
|
28
40
|
export type TaskExecutionInput<Context> = {
|
|
29
41
|
readonly call: ToolCall
|
|
30
42
|
readonly context: Context
|
|
@@ -33,9 +45,22 @@ export type TaskExecutionInput<Context> = {
|
|
|
33
45
|
|
|
34
46
|
export type TaskToolOptions<Context> = {
|
|
35
47
|
readonly subagents: ReadonlyArray<TaskSubagentDefinition>
|
|
48
|
+
readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>
|
|
36
49
|
readonly execute: (input: TaskExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>
|
|
37
50
|
}
|
|
38
51
|
|
|
52
|
+
export type TaskToolResultInput = {
|
|
53
|
+
readonly callId: string
|
|
54
|
+
readonly output: string
|
|
55
|
+
readonly subagentType: string
|
|
56
|
+
readonly description: string
|
|
57
|
+
readonly subagentRunId: string
|
|
58
|
+
readonly startedAtMs: number
|
|
59
|
+
readonly endedAtMs: number
|
|
60
|
+
readonly model: string
|
|
61
|
+
readonly isError?: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
39
64
|
const taskToolError = (message: string, cause: ToolError['cause']) =>
|
|
40
65
|
new ToolError({
|
|
41
66
|
tool: taskToolName,
|
|
@@ -104,6 +129,7 @@ export const makeTaskToolRegistration = <Context>(
|
|
|
104
129
|
description: taskToolDescription(options.subagents),
|
|
105
130
|
parameters: TaskToolParams,
|
|
106
131
|
access: 'read',
|
|
132
|
+
isEnabled: options.isEnabled,
|
|
107
133
|
invalidParamsMessage: error => `Invalid task arguments: ${error instanceof Error ? error.message : String(error)}`,
|
|
108
134
|
execute: ({ call, context, params }) =>
|
|
109
135
|
Effect.gen(function* () {
|
|
@@ -129,4 +155,46 @@ export const makeTaskToolModule = <Context>(options: TaskToolOptions<Context>):
|
|
|
129
155
|
tools: [makeTaskToolRegistration(options)]
|
|
130
156
|
})
|
|
131
157
|
|
|
158
|
+
export const makeNonRecursiveTaskToolModule = <Context extends TaskSubagentContext>(
|
|
159
|
+
options: TaskToolOptions<Context>
|
|
160
|
+
): ToolModule<Context> => makeTaskToolModule({
|
|
161
|
+
...options,
|
|
162
|
+
isEnabled: context => context.subagent === true
|
|
163
|
+
? Effect.succeed(false)
|
|
164
|
+
: options.isEnabled === undefined
|
|
165
|
+
? Effect.succeed(true)
|
|
166
|
+
: options.isEnabled(context)
|
|
167
|
+
})
|
|
168
|
+
|
|
132
169
|
export const formatTaskResult = (output: string) => ['<task_result>', output, '</task_result>'].join('\n')
|
|
170
|
+
|
|
171
|
+
export const taskSubagentRunId = makeSubagentRunId
|
|
172
|
+
|
|
173
|
+
const latestAssistantText = (messages: ReadonlyArray<AgentMessage>) => {
|
|
174
|
+
const assistant = [...messages].reverse().find(message => message._tag === 'Assistant')
|
|
175
|
+
|
|
176
|
+
return assistant === undefined ? '' : contentText(assistantContent(assistant))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export const subagentResultText = (events: ReadonlyArray<AgentEvent>) => {
|
|
180
|
+
const messages = [...events].reverse().find(event => event._tag === 'AgentEnd')?.messages ?? []
|
|
181
|
+
const text = latestAssistantText(messages).trim()
|
|
182
|
+
|
|
183
|
+
return text.length === 0 ? 'Subagent completed without a final text response.' : text
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const makeTaskToolResult = (input: TaskToolResultInput) => ToolResult.make({
|
|
187
|
+
toolCallId: input.callId,
|
|
188
|
+
content: formatTaskResult(input.output),
|
|
189
|
+
isError: input.isError,
|
|
190
|
+
structuredContent: {
|
|
191
|
+
subagent_run_id: input.subagentRunId,
|
|
192
|
+
subagent_type: input.subagentType,
|
|
193
|
+
description: input.description,
|
|
194
|
+
started_at_ms: input.startedAtMs,
|
|
195
|
+
ended_at_ms: input.endedAtMs,
|
|
196
|
+
duration_ms: Math.max(0, input.endedAtMs - input.startedAtMs),
|
|
197
|
+
status: input.isError === true ? 'error' : 'completed',
|
|
198
|
+
model: input.model
|
|
199
|
+
}
|
|
200
|
+
})
|