@yolk-sdk/agent 0.1.0-canary.51 → 0.1.0-canary.53
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 +11 -7
- package/dist/providers/openai/codex-provider.d.mts +0 -1
- package/dist/providers/openai/codex-provider.d.mts.map +1 -1
- package/dist/providers/openai/codex-provider.mjs +0 -1
- package/dist/providers/openai/codex-provider.mjs.map +1 -1
- package/dist/skillset/merge.d.mts +1 -1
- package/dist/tools/index.d.mts +2 -2
- package/dist/tools/task.d.mts +24 -11
- package/dist/tools/task.d.mts.map +1 -1
- package/dist/tools/task.mjs +52 -10
- package/dist/tools/task.mjs.map +1 -1
- package/package.json +1 -1
- package/src/providers/openai/codex-provider.ts +0 -2
- package/src/tools/README.md +23 -3
- package/src/tools/index.ts +3 -0
- package/src/tools/task.ts +117 -14
package/README.md
CHANGED
|
@@ -113,14 +113,16 @@ Provider output limits are required and host-owned. Yolk does not infer model li
|
|
|
113
113
|
fallbacks.
|
|
114
114
|
|
|
115
115
|
| Provider factory | Required output-limit field |
|
|
116
|
-
|
|
|
117
|
-
| `makeOpenAiProviderLayer` | `maxCompletionTokens`
|
|
118
|
-
| `makeOpenAiCodexProviderLayer` | `maxOutputTokens`
|
|
119
|
-
| `makeAnthropicClaudeProviderLayer` | `maxTokens`
|
|
116
|
+
| -------------------------------------- | --------------------------- |
|
|
117
|
+
| `makeOpenAiProviderLayer` | `maxCompletionTokens` |
|
|
118
|
+
| `makeOpenAiCodexProviderLayer` | `maxOutputTokens` |
|
|
119
|
+
| `makeAnthropicClaudeProviderLayer` | `maxTokens` |
|
|
120
120
|
|
|
121
121
|
The public `toOpenAiRequestBody`, `toOpenAiCodexRequestBody`, and
|
|
122
|
-
`toAnthropicClaudeRequestBody` helpers require the same limit configuration.
|
|
123
|
-
|
|
122
|
+
`toAnthropicClaudeRequestBody` helpers require the same limit configuration. ChatGPT subscription
|
|
123
|
+
Codex rejects vendor `max_output_tokens`, so the Codex adapter retains the required host config but
|
|
124
|
+
omits that field from requests. `OpenAiProviderLayer` reads both `OPENAI_API_KEY` and integer
|
|
125
|
+
`OPENAI_MAX_COMPLETION_TOKENS` through Effect Config.
|
|
124
126
|
|
|
125
127
|
## Provider failures and retries
|
|
126
128
|
|
|
@@ -387,7 +389,9 @@ Recommended setup:
|
|
|
387
389
|
- omit `task` from subagent toolsets
|
|
388
390
|
- include only tools that are safe for autonomous delegated work
|
|
389
391
|
- use `makeSubagentRunId(call.id)` for protocol-aligned run ids
|
|
390
|
-
-
|
|
392
|
+
- optionally configure model and reasoning-effort choices so the parent can select child runtime settings
|
|
393
|
+
- treat omitted `model` and `reasoning_effort` parameters as inheritance of host runtime settings
|
|
394
|
+
- return `makeTaskToolResult(...)` so UI can show subagent id, type, status, model, reasoning effort, and timing
|
|
391
395
|
|
|
392
396
|
Keep host-owned subagent execution wiring outside this package; pass only the package task contract across the boundary.
|
|
393
397
|
|
|
@@ -58,7 +58,6 @@ type OpenAiCodexRequestBody = {
|
|
|
58
58
|
readonly model: string;
|
|
59
59
|
readonly instructions: string;
|
|
60
60
|
readonly input: ReadonlyArray<OpenAiCodexInputItem>;
|
|
61
|
-
readonly max_output_tokens: number;
|
|
62
61
|
readonly store: false;
|
|
63
62
|
readonly stream: true;
|
|
64
63
|
readonly reasoning: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codex-provider.d.mts","names":[],"sources":["../../../src/providers/openai/codex-provider.ts"],"mappings":";;;;;;;KAiDY,2BAAA;AAAA,KAEA,yBAAA;EAAA,SACD,KAAA,EAAO,gBAAA;EAAA,SACP,eAAA;EAAA,SACA,YAAA;EAAA,SACA,YAAA,GAAe,QAAA,CAAS,MAAA;EAAA,SACxB,sBAAA,GAAyB,oBAAA;EAAA,SACzB,gBAAA,GAAmB,2BAAA;AAAA;AAAA,KAGzB,uBAAA;EAAA,SACM,IAAA;EAAA,SACA,OAAA,WAAkB,aAAa,CAAC,2BAAA;AAAA;AAAA,KAGtC,wBAAA;EAAA,SACM,IAAA;EAAA,SACA,IAAI;AAAA;AAAA,KAGV,yBAAA;EAAA,SACM,IAAA;EAAA,SACA,SAAS;AAAA;AAAA,KAGf,wBAAA;EAAA,SAEU,IAAA;EAAA,SACA,QAAA;EAAA,SACA,SAAA;AAAA;EAAA,SAGA,IAAA;EAAA,SACA,QAAA;AAAA;AAAA,KAGV,2BAAA,GACD,wBAAA,GACA,yBAAA,GACA,wBAAA;AAAA,KAEC,yBAAA,YAAqC,aAAa,CAAC,2BAAA;AAAA,KAEnD,4BAAA;EAAA,SACM,IAAA;EAAA,SACA,OAAA;EAAA,SACA,IAAA;EAAA,SACA,SAAA;AAAA;AAAA,KAGN,8BAAA;EAAA,SACM,IAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA,EAAQ,yBAAyB;AAAA;AAAA,KAGvC,oBAAA,GACD,uBAAA,GACA,4BAAA,GACA,8BAAA;AAAA,KAEC,eAAA;EAAA,SACM,IAAA;EAAA,SACA,IAAA;EAAA,SACA,WAAA;EAAA,SACA,UAAA;AAAA;AAAA,KAGN,sBAAA;EAAA,SACM,KAAA;EAAA,SACA,YAAA;EAAA,SACA,KAAA,EAAO,aAAA,CAAc,oBAAA;EAAA,SACrB,
|
|
1
|
+
{"version":3,"file":"codex-provider.d.mts","names":[],"sources":["../../../src/providers/openai/codex-provider.ts"],"mappings":";;;;;;;KAiDY,2BAAA;AAAA,KAEA,yBAAA;EAAA,SACD,KAAA,EAAO,gBAAA;EAAA,SACP,eAAA;EAAA,SACA,YAAA;EAAA,SACA,YAAA,GAAe,QAAA,CAAS,MAAA;EAAA,SACxB,sBAAA,GAAyB,oBAAA;EAAA,SACzB,gBAAA,GAAmB,2BAAA;AAAA;AAAA,KAGzB,uBAAA;EAAA,SACM,IAAA;EAAA,SACA,OAAA,WAAkB,aAAa,CAAC,2BAAA;AAAA;AAAA,KAGtC,wBAAA;EAAA,SACM,IAAA;EAAA,SACA,IAAI;AAAA;AAAA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AQ,yBAAA,KAAyB,KAAA,CAAA,KAAA,CAAA,WAAA,SAAA,UAAA,CAAA,UAAA"}
|
|
@@ -168,7 +168,6 @@ const toOpenAiCodexRequestBody = (request, config) => Effect.gen(function* () {
|
|
|
168
168
|
model: request.model,
|
|
169
169
|
instructions: request.systemPrompt,
|
|
170
170
|
input,
|
|
171
|
-
max_output_tokens: config.maxOutputTokens,
|
|
172
171
|
store: false,
|
|
173
172
|
stream: true,
|
|
174
173
|
reasoning: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codex-provider.mjs","names":["Arr","LLMReasoningDelta","LLMTextDelta"],"sources":["../../../src/providers/openai/codex-provider.ts"],"sourcesContent":["import { Array as Arr, Effect, Layer, Option, Ref, Stream } from 'effect'\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentInputUsage,\n AgentOutputUsage,\n AgentUsage,\n ToolCall,\n attachmentSourceDataUrl,\n attachmentSourceUrl,\n assistantContent,\n assistantHostToolCalls,\n contentParts,\n messageContextText,\n replaceLoneSurrogatesDeep,\n prependMessageContextToContent,\n type AgentMessage,\n type AgentReasoningEffort,\n type Content,\n type ContentPart,\n type ProviderFailureKind,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport {\n LLMError,\n LLMDone,\n LLMProvider,\n LLMReasoningDelta,\n LLMTextDelta,\n LLMToolCall,\n LLMUsage,\n type LLMEvent,\n type LLMRequest\n} from '@yolk-sdk/agent/loop'\nimport { openAiCodexAuthorizationHeaders, openAiCodexResponsesUrl } from './codex.ts'\nimport type { OAuthAccessToken } from '@yolk-sdk/agent/oauth'\nimport {\n classifyProviderFailure,\n providerErrorInfo,\n providerFailureCause,\n providerFailureRetryable\n} from '../provider-error.ts'\nimport { validateProviderTranscript } from '../transcript.ts'\n\nexport type OpenAiCodexReasoningSummary = 'auto' | 'concise' | 'detailed'\n\nexport type OpenAiCodexProviderConfig = {\n readonly token: OAuthAccessToken\n readonly maxOutputTokens: number\n readonly responsesUrl?: string\n readonly extraHeaders?: Readonly<Record<string, string>>\n readonly defaultReasoningEffort?: AgentReasoningEffort\n readonly reasoningSummary?: OpenAiCodexReasoningSummary\n}\n\ntype OpenAiCodexMessageInput = {\n readonly role: 'user' | 'assistant'\n readonly content: string | ReadonlyArray<OpenAiCodexInputContentPart>\n}\n\ntype OpenAiCodexInputTextPart = {\n readonly type: 'input_text'\n readonly text: string\n}\n\ntype OpenAiCodexInputImagePart = {\n readonly type: 'input_image'\n readonly image_url: string\n}\n\ntype OpenAiCodexInputFilePart =\n | {\n readonly type: 'input_file'\n readonly filename: string\n readonly file_data: string\n }\n | {\n readonly type: 'input_file'\n readonly file_url: string\n }\n\ntype OpenAiCodexInputContentPart =\n | OpenAiCodexInputTextPart\n | OpenAiCodexInputImagePart\n | OpenAiCodexInputFilePart\n\ntype OpenAiCodexFunctionOutput = string | ReadonlyArray<OpenAiCodexInputContentPart>\n\ntype OpenAiCodexFunctionCallInput = {\n readonly type: 'function_call'\n readonly call_id: string\n readonly name: string\n readonly arguments: string\n}\n\ntype OpenAiCodexFunctionOutputInput = {\n readonly type: 'function_call_output'\n readonly call_id: string\n readonly output: OpenAiCodexFunctionOutput\n}\n\ntype OpenAiCodexInputItem =\n | OpenAiCodexMessageInput\n | OpenAiCodexFunctionCallInput\n | OpenAiCodexFunctionOutputInput\n\ntype OpenAiCodexTool = {\n readonly type: 'function'\n readonly name: string\n readonly description: string\n readonly parameters: unknown\n}\n\ntype OpenAiCodexRequestBody = {\n readonly model: string\n readonly instructions: string\n readonly input: ReadonlyArray<OpenAiCodexInputItem>\n readonly max_output_tokens: number\n readonly store: false\n readonly stream: true\n readonly reasoning: {\n readonly effort: AgentReasoningEffort\n readonly summary: OpenAiCodexReasoningSummary\n }\n readonly tools?: ReadonlyArray<OpenAiCodexTool>\n readonly parallel_tool_calls?: true\n}\n\nclass OpenAiCodexReasoningSummaryText extends Schema.Class<OpenAiCodexReasoningSummaryText>(\n 'OpenAiCodexReasoningSummaryText'\n)({\n type: Schema.Literals(['summary_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexReasoningText extends Schema.Class<OpenAiCodexReasoningText>(\n 'OpenAiCodexReasoningText'\n)({\n type: Schema.Literals(['reasoning_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexOutputText extends Schema.Class<OpenAiCodexOutputText>('OpenAiCodexOutputText')({\n type: Schema.Literals(['output_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexMessageOutput extends Schema.Class<OpenAiCodexMessageOutput>(\n 'OpenAiCodexMessageOutput'\n)({\n type: Schema.Literals(['message']),\n content: Schema.Array(OpenAiCodexOutputText)\n}) {}\n\nclass OpenAiCodexFunctionCallOutput extends Schema.Class<OpenAiCodexFunctionCallOutput>(\n 'OpenAiCodexFunctionCallOutput'\n)({\n type: Schema.Literals(['function_call']),\n call_id: Schema.String,\n name: Schema.String,\n arguments: Schema.String\n}) {}\n\nclass OpenAiCodexReasoningOutput extends Schema.Class<OpenAiCodexReasoningOutput>(\n 'OpenAiCodexReasoningOutput'\n)({\n type: Schema.Literals(['reasoning']),\n summary: Schema.optional(Schema.Array(OpenAiCodexReasoningSummaryText)),\n content: Schema.optional(Schema.Array(OpenAiCodexReasoningText))\n}) {}\n\nclass OpenAiCodexInputTokensDetails extends Schema.Class<OpenAiCodexInputTokensDetails>(\n 'OpenAiCodexInputTokensDetails'\n)({\n cached_tokens: Schema.optional(Schema.Number)\n}) {}\n\nclass OpenAiCodexOutputTokensDetails extends Schema.Class<OpenAiCodexOutputTokensDetails>(\n 'OpenAiCodexOutputTokensDetails'\n)({\n reasoning_tokens: Schema.optional(Schema.Number)\n}) {}\n\nclass OpenAiCodexUsageResponse extends Schema.Class<OpenAiCodexUsageResponse>(\n 'OpenAiCodexUsageResponse'\n)({\n input_tokens: Schema.Number,\n output_tokens: Schema.Number,\n input_tokens_details: Schema.optional(OpenAiCodexInputTokensDetails),\n output_tokens_details: Schema.optional(OpenAiCodexOutputTokensDetails)\n}) {}\n\nconst OpenAiCodexOutputItem = Schema.Union([\n OpenAiCodexMessageOutput,\n OpenAiCodexFunctionCallOutput,\n OpenAiCodexReasoningOutput\n])\ntype OpenAiCodexOutputItem = typeof OpenAiCodexOutputItem.Type\n\nclass OpenAiCodexResponse extends Schema.Class<OpenAiCodexResponse>('OpenAiCodexResponse')({\n output_text: Schema.optional(Schema.String),\n output: Schema.Array(OpenAiCodexOutputItem),\n usage: Schema.optional(OpenAiCodexUsageResponse)\n}) {}\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst unsupportedContentError = (contentType: string) =>\n new LLMError({\n cause: 'provider_error',\n message: `${contentType} content is not supported by the OpenAI Codex OAuth provider yet`,\n retryable: false\n })\n\nconst contentPartToText = (part: ContentPart, owner: string): Effect.Effect<string, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part.text)\n case 'Image':\n return Effect.fail(unsupportedContentError(`${owner} image`))\n case 'Document':\n return Effect.fail(unsupportedContentError(`${owner} document`))\n case 'Audio':\n return Effect.fail(unsupportedContentError(`${owner} audio`))\n }\n}\n\nconst contentToText = (content: Content, owner: string): Effect.Effect<string, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => contentPartToText(part, owner)).pipe(\n Effect.map(textParts => textParts.join('\\n'))\n )\n\nconst contentPartToCodexInputPart = (\n part: ContentPart\n): Effect.Effect<\n OpenAiCodexInputTextPart | OpenAiCodexInputImagePart | OpenAiCodexInputFilePart,\n LLMError\n> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed({ type: 'input_text', text: part.text })\n case 'Image':\n return Option.match(attachmentSourceUrl(part.source, part.mimeType), {\n onNone: () => Effect.fail(unsupportedContentError('Unresolved image source')),\n onSome: url =>\n Effect.succeed({\n type: 'input_image',\n image_url: url\n })\n })\n case 'Document':\n switch (part.source._tag) {\n case 'InlineBase64':\n return Option.match(attachmentSourceDataUrl(part.source, part.mimeType), {\n onNone: () => Effect.fail(unsupportedContentError('Invalid document source')),\n onSome: url =>\n Effect.succeed({\n type: 'input_file',\n filename: part.filename,\n file_data: url\n })\n })\n case 'Url':\n return Effect.succeed({ type: 'input_file', file_url: part.source.url })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved document source'))\n }\n case 'Audio':\n return Effect.fail(unsupportedContentError('Audio'))\n }\n}\n\nconst contentToUserInput = (\n content: Content\n): Effect.Effect<OpenAiCodexMessageInput['content'], LLMError> => {\n if (typeof content === 'string') {\n return Effect.succeed(content)\n }\n\n const parts = contentParts(content)\n const onlyPart = parts[0]\n\n if (onlyPart !== undefined && parts.length === 1 && onlyPart._tag === 'Text') {\n return Effect.succeed(onlyPart.text)\n }\n\n return Effect.forEach(parts, contentPartToCodexInputPart)\n}\n\nconst contentToCodexFunctionOutput = (\n content: Content\n): Effect.Effect<OpenAiCodexFunctionOutput, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, contentPartToCodexInputPart)\n\nconst codexToolResultOutput = (\n content: Content,\n isError: boolean | undefined\n): Effect.Effect<OpenAiCodexFunctionOutput, LLMError> =>\n contentToCodexFunctionOutput(content).pipe(\n Effect.map(output => {\n if (isError !== true) return output\n\n const errorPart: OpenAiCodexInputTextPart = {\n type: 'input_text',\n text: 'Tool execution failed.'\n }\n\n return typeof output === 'string' ? `${errorPart.text}\\n\\n${output}` : [errorPart, ...output]\n })\n )\n\nconst serializeToolArguments = (params: unknown) =>\n encodeJsonString(params, 'Could not serialize OpenAI Codex tool arguments')\n\nconst toolCallToCodexInput = (\n call: ToolCall\n): Effect.Effect<OpenAiCodexFunctionCallInput, LLMError> =>\n Effect.gen(function* () {\n return {\n type: 'function_call',\n call_id: call.id,\n name: call.name,\n arguments: yield* serializeToolArguments(call.params)\n }\n })\n\nconst messageToCodexInput = (\n message: AgentMessage\n): Effect.Effect<ReadonlyArray<OpenAiCodexInputItem>, LLMError> =>\n Effect.gen(function* () {\n switch (message._tag) {\n case 'User':\n return [\n {\n role: 'user',\n content: yield* contentToUserInput(\n prependMessageContextToContent(message.content, messageContextText(message))\n )\n }\n ]\n case 'Assistant': {\n const content = yield* contentToText(\n prependMessageContextToContent(assistantContent(message), messageContextText(message)),\n 'Assistant'\n )\n const toolCallInputs = yield* Effect.forEach(\n assistantHostToolCalls(message),\n toolCallToCodexInput\n )\n\n if (content.length > 0) {\n const assistantMessage: OpenAiCodexInputItem = { role: 'assistant', content }\n\n return [assistantMessage, ...toolCallInputs]\n }\n\n return toolCallInputs\n }\n case 'ToolResult':\n return [\n {\n type: 'function_call_output',\n call_id: message.toolCallId,\n output: yield* codexToolResultOutput(\n prependMessageContextToContent(message.content, messageContextText(message)),\n message.isError\n )\n }\n ]\n }\n })\n\nconst toOpenAiCodexTool = (tool: ToolDef): OpenAiCodexTool => ({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters\n})\n\nexport const toOpenAiCodexRequestBody = (\n request: LLMRequest,\n config: {\n readonly maxOutputTokens: number\n readonly defaultReasoningEffort?: AgentReasoningEffort\n readonly reasoningSummary?: OpenAiCodexReasoningSummary\n }\n): Effect.Effect<OpenAiCodexRequestBody, LLMError> =>\n Effect.gen(function* () {\n yield* validateProviderTranscript(request.messages)\n const input = Arr.flatten(yield* Effect.forEach(request.messages, messageToCodexInput))\n\n const body: Omit<OpenAiCodexRequestBody, 'tools'> = {\n model: request.model,\n instructions: request.systemPrompt,\n input,\n max_output_tokens: config.maxOutputTokens,\n store: false,\n stream: true,\n reasoning: {\n effort: request.reasoningEffort ?? config.defaultReasoningEffort ?? 'low',\n summary: config.reasoningSummary ?? 'auto'\n }\n }\n\n if (request.tools.length === 0) {\n return body\n }\n\n return {\n ...body,\n tools: request.tools.map(toOpenAiCodexTool),\n parallel_tool_calls: true\n }\n })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\nconst stringField = (value: unknown, key: string) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n const field = Object.getOwnPropertyDescriptor(value, key)?.value\n\n return typeof field === 'string' ? field : undefined\n}\n\nconst recordField = (value: unknown, key: string) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n const field = Object.getOwnPropertyDescriptor(value, key)?.value\n\n return isRecord(field) ? field : undefined\n}\n\nconst openAiCodexProvider = 'openai_codex'\n\nconst providerSignalError = (input: {\n readonly message: string\n readonly providerCode?: string\n readonly fallbackKind?: ProviderFailureKind\n}) => {\n const provider = classifyProviderFailure({\n provider: openAiCodexProvider,\n message: input.message,\n ...(input.providerCode === undefined ? {} : { providerCode: input.providerCode }),\n ...(input.fallbackKind === undefined ? {} : { fallbackKind: input.fallbackKind })\n })\n\n return new LLMError({\n cause: providerFailureCause(provider.kind),\n message: `OpenAI Codex stream error: ${input.message}`,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n}\n\nconst parseToolArguments = (raw: string) =>\n decodeJsonString(raw, 'Invalid OpenAI Codex tool arguments JSON')\n\nconst textFromOutputItem = (item: OpenAiCodexOutputItem) => {\n switch (item.type) {\n case 'message':\n return Arr.map(item.content, content => content.text)\n case 'function_call':\n case 'reasoning':\n return []\n }\n}\n\nconst textFromOutputItems = (items: ReadonlyArray<OpenAiCodexOutputItem>) => {\n const textParts = Arr.flatten(Arr.map(items, textFromOutputItem))\n\n return textParts.join('')\n}\n\nconst reasoningFromOutputItem = (item: OpenAiCodexOutputItem) => {\n switch (item.type) {\n case 'reasoning':\n return [\n ...(item.summary ?? []).map(summary => summary.text),\n ...(item.content ?? []).map(content => content.text)\n ]\n case 'message':\n case 'function_call':\n return []\n }\n}\n\nconst reasoningFromOutputItems = (items: ReadonlyArray<OpenAiCodexOutputItem>) => {\n const reasoningParts = Arr.flatten(Arr.map(items, reasoningFromOutputItem))\n\n return reasoningParts.join('')\n}\n\nconst toAgentUsage = (usage: OpenAiCodexUsageResponse) =>\n AgentUsage.make({\n input: AgentInputUsage.make({\n total: usage.input_tokens,\n uncached: usage.input_tokens - (usage.input_tokens_details?.cached_tokens ?? 0),\n cacheRead: usage.input_tokens_details?.cached_tokens\n }),\n output: AgentOutputUsage.make({\n total: usage.output_tokens,\n reasoning: usage.output_tokens_details?.reasoning_tokens,\n text: usage.output_tokens - (usage.output_tokens_details?.reasoning_tokens ?? 0)\n })\n })\n\ntype ToLlmEventsOptions = {\n readonly allowEmptyStop: boolean\n}\n\nconst toLlmEvents = (\n response: OpenAiCodexResponse,\n options: ToLlmEventsOptions\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const text = response.output_text ?? textFromOutputItems(response.output)\n const reasoning = reasoningFromOutputItems(response.output)\n const reasoningEvents =\n reasoning.length > 0 ? [LLMReasoningDelta.make({ text: reasoning })] : []\n const textEvents = text.length > 0 ? [LLMTextDelta.make({ text })] : []\n const toolCallEvents = Arr.getSomes(\n yield* Effect.forEach(response.output, item => {\n switch (item.type) {\n case 'message':\n case 'reasoning':\n return Effect.succeed(Option.none())\n case 'function_call':\n return parseToolArguments(item.arguments).pipe(\n Effect.map(params =>\n Option.some(\n LLMToolCall.make({\n call: ToolCall.make({\n id: item.call_id,\n name: item.name,\n params\n })\n })\n )\n )\n )\n }\n })\n )\n\n if (textEvents.length === 0 && toolCallEvents.length === 0 && !options.allowEmptyStop) {\n return yield* Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: 'OpenAI Codex response did not include text or tool calls',\n retryable: false\n })\n )\n }\n\n const events: Array<LLMEvent> = [\n ...reasoningEvents,\n ...textEvents,\n ...toolCallEvents,\n LLMDone.make({ stopReason: toolCallEvents.length > 0 ? 'tool_use' : 'stop' })\n ]\n\n if (response.usage !== undefined) {\n events.push(LLMUsage.make({ usage: toAgentUsage(response.usage) }))\n }\n\n return events\n })\n\nconst decodeOpenAiCodexResponse = (json: unknown) =>\n Schema.decodeUnknownEffect(OpenAiCodexResponse)(json).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid OpenAI Codex response: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst parseOpenAiCodexJsonResponse = (\n raw: string\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const json = yield* decodeJsonString(raw, 'Could not parse OpenAI Codex response JSON')\n const parsed = yield* decodeOpenAiCodexResponse(json)\n\n return yield* toLlmEvents(parsed, { allowEmptyStop: false })\n })\n\ntype OpenAiCodexBodyFormat = 'undecided' | 'sse' | 'json'\n\ntype OpenAiCodexSseState = {\n readonly hasTextDelta: boolean\n readonly hasReasoningDelta: boolean\n readonly hasToolCall: boolean\n readonly hasDone: boolean\n}\n\ntype OpenAiCodexSseStep = {\n readonly state: OpenAiCodexSseState\n readonly events: ReadonlyArray<LLMEvent>\n}\n\ntype OpenAiCodexBodyState = {\n readonly format: OpenAiCodexBodyFormat\n readonly buffer: string\n readonly sse: OpenAiCodexSseState\n}\n\nconst initialSseState: OpenAiCodexSseState = {\n hasTextDelta: false,\n hasReasoningDelta: false,\n hasToolCall: false,\n hasDone: false\n}\n\nconst initialBodyState: OpenAiCodexBodyState = {\n format: 'undecided',\n buffer: '',\n sse: initialSseState\n}\n\nconst normalizeNewlines = (text: string) => text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\nconst classifyCodexBody = (buffer: string): OpenAiCodexBodyFormat => {\n const trimmed = buffer.trimStart()\n\n if (trimmed.length === 0) {\n return 'undecided'\n }\n\n if (trimmed.startsWith('event:') || trimmed.startsWith('data:')) {\n return 'sse'\n }\n\n if ('event:'.startsWith(trimmed) || 'data:'.startsWith(trimmed)) {\n return 'undecided'\n }\n\n return 'json'\n}\n\nconst splitCompleteSseBlocks = (buffer: string) => {\n const blocks = buffer.split('\\n\\n')\n const tail = blocks.at(-1) ?? ''\n\n return { completeBlocks: blocks.slice(0, -1), tail }\n}\n\nconst dataFromSseBlock = (block: string) => {\n const lines = Arr.map(\n Arr.filter(block.split('\\n'), line => line.startsWith('data:')),\n line => line.slice(5).trimStart()\n )\n\n const data = lines.join('\\n').trim()\n\n if (data.length === 0 || data === '[DONE]') {\n return undefined\n }\n\n return data\n}\n\nconst parseOpenAiCodexSseJson = (data: string) =>\n decodeJsonString(data, 'Could not parse OpenAI Codex stream event JSON')\n\nconst decodeOpenAiCodexOutputItem = (value: unknown) =>\n Schema.decodeUnknownEffect(OpenAiCodexOutputItem)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid OpenAI Codex output item: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst invalidFunctionCallSseItemError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Invalid OpenAI Codex function call stream item',\n retryable: false\n })\n\nconst eventsFromOutputItem = (\n item: OpenAiCodexOutputItem\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> => {\n switch (item.type) {\n case 'message': {\n const text = textFromOutputItems([item])\n\n return Effect.succeed(text.length > 0 ? [LLMTextDelta.make({ text })] : [])\n }\n case 'reasoning': {\n const reasoning = reasoningFromOutputItems([item])\n\n return Effect.succeed(\n reasoning.length > 0 ? [LLMReasoningDelta.make({ text: reasoning })] : []\n )\n }\n case 'function_call':\n return parseToolArguments(item.arguments).pipe(\n Effect.map(params => [\n LLMToolCall.make({\n call: ToolCall.make({\n id: item.call_id,\n name: item.name,\n params\n })\n })\n ])\n )\n }\n}\n\nconst eventsFromOutputItemDone = (\n event: Record<string, unknown>\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n if (event.type !== 'response.output_item.done') {\n return []\n }\n\n const item = event.item\n\n if (item === undefined) {\n return yield* Effect.fail(invalidFunctionCallSseItemError())\n }\n\n return yield* decodeOpenAiCodexOutputItem(item).pipe(Effect.flatMap(eventsFromOutputItem))\n })\n\nconst finalResponseToEvents = (\n response: unknown,\n state: OpenAiCodexSseState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const parsedFinal = yield* decodeOpenAiCodexResponse(response)\n const finalEvents = yield* toLlmEvents(parsedFinal, {\n allowEmptyStop: state.hasTextDelta || state.hasToolCall\n })\n\n const shouldDedupe = state.hasTextDelta || state.hasReasoningDelta || state.hasToolCall\n const dedupedEvents = shouldDedupe\n ? finalEvents.filter(event => {\n if (state.hasTextDelta && event._tag === 'TextDelta') {\n return false\n }\n\n if (state.hasReasoningDelta && event._tag === 'ReasoningDelta') {\n return false\n }\n\n if (state.hasToolCall && event._tag === 'ToolCall') {\n return false\n }\n\n return true\n })\n : finalEvents\n\n if (!state.hasToolCall) {\n return dedupedEvents\n }\n\n return dedupedEvents.map(event =>\n event._tag === 'Done' ? LLMDone.make({ stopReason: 'tool_use' }) : event\n )\n })\n\nconst processSseData = (\n state: OpenAiCodexSseState,\n data: string\n): Effect.Effect<OpenAiCodexSseStep, LLMError> =>\n Effect.gen(function* () {\n const parsed = yield* parseOpenAiCodexSseJson(data)\n\n if (!isRecord(parsed)) {\n return { state, events: [] }\n }\n\n if (\n (parsed.type === 'response.output_text.delta' ||\n parsed.type === 'response.content_part.delta') &&\n typeof parsed.delta === 'string'\n ) {\n return {\n state: { ...state, hasTextDelta: true },\n events: [LLMTextDelta.make({ text: parsed.delta })]\n }\n }\n\n if (\n (parsed.type === 'response.reasoning_summary_text.delta' ||\n parsed.type === 'response.reasoning_text.delta') &&\n typeof parsed.delta === 'string'\n ) {\n return {\n state: { ...state, hasReasoningDelta: true },\n events: [LLMReasoningDelta.make({ text: parsed.delta })]\n }\n }\n\n const outputItemDoneEvents = yield* eventsFromOutputItemDone(parsed)\n if (outputItemDoneEvents.length > 0) {\n const events = outputItemDoneEvents.filter(event => {\n if (state.hasTextDelta && event._tag === 'TextDelta') {\n return false\n }\n\n if (state.hasReasoningDelta && event._tag === 'ReasoningDelta') {\n return false\n }\n\n if (state.hasToolCall && event._tag === 'ToolCall') {\n return false\n }\n\n return true\n })\n\n return {\n state: {\n hasTextDelta: state.hasTextDelta || events.some(event => event._tag === 'TextDelta'),\n hasReasoningDelta:\n state.hasReasoningDelta || events.some(event => event._tag === 'ReasoningDelta'),\n hasToolCall: state.hasToolCall || events.some(event => event._tag === 'ToolCall'),\n hasDone: state.hasDone\n },\n events\n }\n }\n\n if (parsed.type === 'response.completed') {\n const events = yield* finalResponseToEvents(parsed.response, state)\n const emittedText = events.some(event => event._tag === 'TextDelta')\n const emittedReasoning = events.some(event => event._tag === 'ReasoningDelta')\n const emittedToolCall = events.some(event => event._tag === 'ToolCall')\n\n return {\n state: {\n hasTextDelta: state.hasTextDelta || emittedText,\n hasReasoningDelta: state.hasReasoningDelta || emittedReasoning,\n hasToolCall: state.hasToolCall || emittedToolCall,\n hasDone: true\n },\n events\n }\n }\n\n if (parsed.type === 'response.failed') {\n const error = recordField(recordField(parsed, 'response'), 'error')\n const message = stringField(error, 'message') ?? 'OpenAI Codex response failed'\n const providerCode = stringField(error, 'code') ?? stringField(error, 'type')\n\n return yield* Effect.fail(\n providerSignalError({\n message,\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n if (parsed.type === 'error' && typeof parsed.message === 'string') {\n const providerCode = stringField(parsed, 'code') ?? stringField(parsed, 'type')\n\n return yield* Effect.fail(\n providerSignalError({\n message: parsed.message,\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n return { state, events: [] }\n })\n\nconst processSseBlock = (\n state: OpenAiCodexSseState,\n block: string\n): Effect.Effect<OpenAiCodexSseStep, LLMError> => {\n const data = dataFromSseBlock(block)\n\n if (data === undefined) {\n return Effect.succeed({ state, events: [] })\n }\n\n return processSseData(state, data)\n}\n\nconst processSseBlocks = (\n state: OpenAiCodexSseState,\n blocks: ReadonlyArray<string>\n): Effect.Effect<OpenAiCodexSseStep, LLMError> =>\n Effect.gen(function* () {\n const events: Array<LLMEvent> = []\n let currentState = state\n\n for (const block of blocks) {\n const step = yield* processSseBlock(currentState, block)\n currentState = step.state\n events.push(...step.events)\n }\n\n return { state: currentState, events }\n })\n\nconst processBodyChunk = (\n state: OpenAiCodexBodyState,\n chunk: string\n): Effect.Effect<OpenAiCodexSseStep & { readonly bodyState: OpenAiCodexBodyState }, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(`${state.buffer}${chunk}`)\n const format = state.format === 'undecided' ? classifyCodexBody(buffer) : state.format\n\n if (format !== 'sse') {\n return {\n state: state.sse,\n bodyState: { ...state, format, buffer },\n events: []\n }\n }\n\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(state.sse, split.completeBlocks)\n\n return {\n state: step.state,\n bodyState: { format, buffer: split.tail, sse: step.state },\n events: step.events\n }\n })\n\nconst finalizeBodyState = (\n state: OpenAiCodexBodyState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(state.buffer)\n const format = state.format === 'undecided' ? classifyCodexBody(buffer) : state.format\n\n if (format === 'json') {\n return yield* parseOpenAiCodexJsonResponse(buffer)\n }\n\n const events: Array<LLMEvent> = []\n let sseState = state.sse\n\n if (format === 'sse') {\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(sseState, split.completeBlocks)\n sseState = step.state\n events.push(...step.events)\n\n if (split.tail.trim().length > 0) {\n const tailStep = yield* processSseBlock(sseState, split.tail)\n sseState = tailStep.state\n events.push(...tailStep.events)\n }\n }\n\n if (!sseState.hasDone) {\n events.push(LLMDone.make({ stopReason: sseState.hasToolCall ? 'tool_use' : 'stop' }))\n }\n\n return events\n })\n\nconst toHttpClientLlmError =\n (message: string, retryable: boolean, kind: ProviderFailureKind = 'network') =>\n (error: HttpClientError.HttpClientError) =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${error.message}`,\n retryable,\n provider: providerErrorInfo({\n provider: openAiCodexProvider,\n kind: retryable ? kind : 'unknown'\n })\n })\n\nexport const streamOpenAiCodexResponse = (\n response: HttpClientResponse.HttpClientResponse\n): Stream.Stream<LLMEvent, LLMError> =>\n Stream.unwrap(\n Ref.make(initialBodyState).pipe(\n Effect.map(bodyStateRef => {\n const chunks = response.stream.pipe(\n Stream.mapError(\n toHttpClientLlmError('Could not read OpenAI Codex stream', true, 'stream')\n ),\n Stream.decodeText,\n Stream.mapEffect(chunk =>\n Effect.gen(function* () {\n const state = yield* Ref.get(bodyStateRef)\n const step = yield* processBodyChunk(state, chunk)\n yield* Ref.set(bodyStateRef, step.bodyState)\n return step.events\n })\n ),\n Stream.flatMap(events => Stream.fromIterable(events))\n )\n\n const finalEvents = Stream.fromEffect(\n Ref.get(bodyStateRef).pipe(Effect.flatMap(finalizeBodyState))\n ).pipe(Stream.flatMap(events => Stream.fromIterable(events)))\n\n return chunks.pipe(Stream.concat(finalEvents))\n })\n )\n )\n\nconst sendOpenAiCodexRequest = (\n config: OpenAiCodexProviderConfig,\n request: LLMRequest,\n client: HttpClient.HttpClient\n): Effect.Effect<HttpClientResponse.HttpClientResponse, LLMError> =>\n Effect.gen(function* () {\n const body = yield* toOpenAiCodexRequestBody(request, config)\n // Replayed transcripts can carry lone surrogates; harden the lowered\n // body so one bad historical string cannot poison every model call.\n const serializedBody = yield* encodeJsonString(\n replaceLoneSurrogatesDeep(body),\n 'Could not serialize OpenAI Codex request'\n )\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...openAiCodexAuthorizationHeaders(config.token),\n 'content-type': 'application/json',\n ...config.extraHeaders\n }\n\n const httpRequest = HttpClientRequest.post(config.responsesUrl ?? openAiCodexResponsesUrl).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(serializedBody, 'application/json')\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientLlmError('OpenAI Codex request failed', true)))\n\n if (response.status < 200 || response.status >= 300) {\n const errorText = yield* response.text.pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not read OpenAI Codex error body: ${error.message}`,\n retryable: false\n })\n )\n )\n\n const provider = classifyProviderFailure({\n provider: openAiCodexProvider,\n status: response.status,\n headers: response.headers,\n body: errorText\n })\n\n return yield* Effect.fail(\n new LLMError({\n cause: providerFailureCause(provider.kind),\n message: `OpenAI Codex returned ${response.status}`,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n )\n }\n\n return response\n }).pipe(Effect.withSpan('OpenAiCodexProvider.stream'))\n\nexport const makeOpenAiCodexProviderLayer = (config: OpenAiCodexProviderConfig) =>\n Layer.effect(LLMProvider)(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n\n return LLMProvider.of({\n stream: request =>\n Stream.fromEffect(sendOpenAiCodexRequest(config, request, client)).pipe(\n Stream.flatMap(streamOpenAiCodexResponse)\n )\n })\n })\n )\n"],"mappings":";;;;;;;;;AAqIA,IAAM,kCAAN,cAA8C,OAAO,MACnD,iCACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,cAAc,CAAC;CACtC,MAAM,OAAO;AACf,CAAC,EAAE,CAAC;AAEJ,IAAM,2BAAN,cAAuC,OAAO,MAC5C,0BACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,gBAAgB,CAAC;CACxC,MAAM,OAAO;AACf,CAAC,EAAE,CAAC;AAEJ,IAAM,wBAAN,cAAoC,OAAO,MAA6B,uBAAuB,EAAE;CAC/F,MAAM,OAAO,SAAS,CAAC,aAAa,CAA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zF,kBAAkB,WAAW,OAAO,GACpC,kBAAkB,SAAS,gBAAgB,kBAAkB,CAC/D;CACA,MAAM,WAAW,OAAO,OACrB,QAAQ,WAAW,EACnB,KAAK,OAAO,SAAS,qBAAqB,+BAA+B,IAAI,CAAC,CAAC;CAElF,IAAI,SAAS,SAAS,OAAO,SAAS,UAAU,KAAK;EACnD,MAAM,YAAY,OAAO,SAAS,KAAK,KACrC,OAAO,UACL,UACE,IAAI,SAAS;GACX,OAAO;GACP,SAAS,2CAA2C,MAAM;GAC1D,WAAW;EACb,CAAC,CACL,CACF;EAEA,MAAM,WAAW,wBAAwB;GACvC,UAAU;GACV,QAAQ,SAAS;GACjB,SAAS,SAAS;GAClB,MAAM;EACR,CAAC;EAED,OAAO,OAAO,OAAO,KACnB,IAAI,SAAS;GACX,OAAO,qBAAqB,SAAS,IAAI;GACzC,SAAS,yBAAyB,SAAS;GAC3C,WAAW,yBAAyB,SAAS,IAAI;GACjD;EACF,CAAC,CACH;CACF;CAEA,OAAO;AACT,CAAC,EAAE,KAAK,OAAO,SAAS,4BAA4B,CAAC;AAEvD,MAAa,gCAAgC,WAC3C,MAAM,OAAO,WAAW,EACtB,OAAO,IAAI,aAAa;CACtB,MAAM,SAAS,OAAO,WAAW;CAEjC,OAAO,YAAY,GAAG,EACpB,SAAQ,YACN,OAAO,WAAW,uBAAuB,QAAQ,SAAS,MAAM,CAAC,EAAE,KACjE,OAAO,QAAQ,yBAAyB,CAC1C,EACJ,CAAC;AACH,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"codex-provider.mjs","names":["Arr","LLMReasoningDelta","LLMTextDelta"],"sources":["../../../src/providers/openai/codex-provider.ts"],"sourcesContent":["import { Array as Arr, Effect, Layer, Option, Ref, Stream } from 'effect'\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentInputUsage,\n AgentOutputUsage,\n AgentUsage,\n ToolCall,\n attachmentSourceDataUrl,\n attachmentSourceUrl,\n assistantContent,\n assistantHostToolCalls,\n contentParts,\n messageContextText,\n replaceLoneSurrogatesDeep,\n prependMessageContextToContent,\n type AgentMessage,\n type AgentReasoningEffort,\n type Content,\n type ContentPart,\n type ProviderFailureKind,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport {\n LLMError,\n LLMDone,\n LLMProvider,\n LLMReasoningDelta,\n LLMTextDelta,\n LLMToolCall,\n LLMUsage,\n type LLMEvent,\n type LLMRequest\n} from '@yolk-sdk/agent/loop'\nimport { openAiCodexAuthorizationHeaders, openAiCodexResponsesUrl } from './codex.ts'\nimport type { OAuthAccessToken } from '@yolk-sdk/agent/oauth'\nimport {\n classifyProviderFailure,\n providerErrorInfo,\n providerFailureCause,\n providerFailureRetryable\n} from '../provider-error.ts'\nimport { validateProviderTranscript } from '../transcript.ts'\n\nexport type OpenAiCodexReasoningSummary = 'auto' | 'concise' | 'detailed'\n\nexport type OpenAiCodexProviderConfig = {\n readonly token: OAuthAccessToken\n readonly maxOutputTokens: number\n readonly responsesUrl?: string\n readonly extraHeaders?: Readonly<Record<string, string>>\n readonly defaultReasoningEffort?: AgentReasoningEffort\n readonly reasoningSummary?: OpenAiCodexReasoningSummary\n}\n\ntype OpenAiCodexMessageInput = {\n readonly role: 'user' | 'assistant'\n readonly content: string | ReadonlyArray<OpenAiCodexInputContentPart>\n}\n\ntype OpenAiCodexInputTextPart = {\n readonly type: 'input_text'\n readonly text: string\n}\n\ntype OpenAiCodexInputImagePart = {\n readonly type: 'input_image'\n readonly image_url: string\n}\n\ntype OpenAiCodexInputFilePart =\n | {\n readonly type: 'input_file'\n readonly filename: string\n readonly file_data: string\n }\n | {\n readonly type: 'input_file'\n readonly file_url: string\n }\n\ntype OpenAiCodexInputContentPart =\n | OpenAiCodexInputTextPart\n | OpenAiCodexInputImagePart\n | OpenAiCodexInputFilePart\n\ntype OpenAiCodexFunctionOutput = string | ReadonlyArray<OpenAiCodexInputContentPart>\n\ntype OpenAiCodexFunctionCallInput = {\n readonly type: 'function_call'\n readonly call_id: string\n readonly name: string\n readonly arguments: string\n}\n\ntype OpenAiCodexFunctionOutputInput = {\n readonly type: 'function_call_output'\n readonly call_id: string\n readonly output: OpenAiCodexFunctionOutput\n}\n\ntype OpenAiCodexInputItem =\n | OpenAiCodexMessageInput\n | OpenAiCodexFunctionCallInput\n | OpenAiCodexFunctionOutputInput\n\ntype OpenAiCodexTool = {\n readonly type: 'function'\n readonly name: string\n readonly description: string\n readonly parameters: unknown\n}\n\ntype OpenAiCodexRequestBody = {\n readonly model: string\n readonly instructions: string\n readonly input: ReadonlyArray<OpenAiCodexInputItem>\n readonly store: false\n readonly stream: true\n readonly reasoning: {\n readonly effort: AgentReasoningEffort\n readonly summary: OpenAiCodexReasoningSummary\n }\n readonly tools?: ReadonlyArray<OpenAiCodexTool>\n readonly parallel_tool_calls?: true\n}\n\nclass OpenAiCodexReasoningSummaryText extends Schema.Class<OpenAiCodexReasoningSummaryText>(\n 'OpenAiCodexReasoningSummaryText'\n)({\n type: Schema.Literals(['summary_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexReasoningText extends Schema.Class<OpenAiCodexReasoningText>(\n 'OpenAiCodexReasoningText'\n)({\n type: Schema.Literals(['reasoning_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexOutputText extends Schema.Class<OpenAiCodexOutputText>('OpenAiCodexOutputText')({\n type: Schema.Literals(['output_text']),\n text: Schema.String\n}) {}\n\nclass OpenAiCodexMessageOutput extends Schema.Class<OpenAiCodexMessageOutput>(\n 'OpenAiCodexMessageOutput'\n)({\n type: Schema.Literals(['message']),\n content: Schema.Array(OpenAiCodexOutputText)\n}) {}\n\nclass OpenAiCodexFunctionCallOutput extends Schema.Class<OpenAiCodexFunctionCallOutput>(\n 'OpenAiCodexFunctionCallOutput'\n)({\n type: Schema.Literals(['function_call']),\n call_id: Schema.String,\n name: Schema.String,\n arguments: Schema.String\n}) {}\n\nclass OpenAiCodexReasoningOutput extends Schema.Class<OpenAiCodexReasoningOutput>(\n 'OpenAiCodexReasoningOutput'\n)({\n type: Schema.Literals(['reasoning']),\n summary: Schema.optional(Schema.Array(OpenAiCodexReasoningSummaryText)),\n content: Schema.optional(Schema.Array(OpenAiCodexReasoningText))\n}) {}\n\nclass OpenAiCodexInputTokensDetails extends Schema.Class<OpenAiCodexInputTokensDetails>(\n 'OpenAiCodexInputTokensDetails'\n)({\n cached_tokens: Schema.optional(Schema.Number)\n}) {}\n\nclass OpenAiCodexOutputTokensDetails extends Schema.Class<OpenAiCodexOutputTokensDetails>(\n 'OpenAiCodexOutputTokensDetails'\n)({\n reasoning_tokens: Schema.optional(Schema.Number)\n}) {}\n\nclass OpenAiCodexUsageResponse extends Schema.Class<OpenAiCodexUsageResponse>(\n 'OpenAiCodexUsageResponse'\n)({\n input_tokens: Schema.Number,\n output_tokens: Schema.Number,\n input_tokens_details: Schema.optional(OpenAiCodexInputTokensDetails),\n output_tokens_details: Schema.optional(OpenAiCodexOutputTokensDetails)\n}) {}\n\nconst OpenAiCodexOutputItem = Schema.Union([\n OpenAiCodexMessageOutput,\n OpenAiCodexFunctionCallOutput,\n OpenAiCodexReasoningOutput\n])\ntype OpenAiCodexOutputItem = typeof OpenAiCodexOutputItem.Type\n\nclass OpenAiCodexResponse extends Schema.Class<OpenAiCodexResponse>('OpenAiCodexResponse')({\n output_text: Schema.optional(Schema.String),\n output: Schema.Array(OpenAiCodexOutputItem),\n usage: Schema.optional(OpenAiCodexUsageResponse)\n}) {}\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst unsupportedContentError = (contentType: string) =>\n new LLMError({\n cause: 'provider_error',\n message: `${contentType} content is not supported by the OpenAI Codex OAuth provider yet`,\n retryable: false\n })\n\nconst contentPartToText = (part: ContentPart, owner: string): Effect.Effect<string, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part.text)\n case 'Image':\n return Effect.fail(unsupportedContentError(`${owner} image`))\n case 'Document':\n return Effect.fail(unsupportedContentError(`${owner} document`))\n case 'Audio':\n return Effect.fail(unsupportedContentError(`${owner} audio`))\n }\n}\n\nconst contentToText = (content: Content, owner: string): Effect.Effect<string, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => contentPartToText(part, owner)).pipe(\n Effect.map(textParts => textParts.join('\\n'))\n )\n\nconst contentPartToCodexInputPart = (\n part: ContentPart\n): Effect.Effect<\n OpenAiCodexInputTextPart | OpenAiCodexInputImagePart | OpenAiCodexInputFilePart,\n LLMError\n> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed({ type: 'input_text', text: part.text })\n case 'Image':\n return Option.match(attachmentSourceUrl(part.source, part.mimeType), {\n onNone: () => Effect.fail(unsupportedContentError('Unresolved image source')),\n onSome: url =>\n Effect.succeed({\n type: 'input_image',\n image_url: url\n })\n })\n case 'Document':\n switch (part.source._tag) {\n case 'InlineBase64':\n return Option.match(attachmentSourceDataUrl(part.source, part.mimeType), {\n onNone: () => Effect.fail(unsupportedContentError('Invalid document source')),\n onSome: url =>\n Effect.succeed({\n type: 'input_file',\n filename: part.filename,\n file_data: url\n })\n })\n case 'Url':\n return Effect.succeed({ type: 'input_file', file_url: part.source.url })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved document source'))\n }\n case 'Audio':\n return Effect.fail(unsupportedContentError('Audio'))\n }\n}\n\nconst contentToUserInput = (\n content: Content\n): Effect.Effect<OpenAiCodexMessageInput['content'], LLMError> => {\n if (typeof content === 'string') {\n return Effect.succeed(content)\n }\n\n const parts = contentParts(content)\n const onlyPart = parts[0]\n\n if (onlyPart !== undefined && parts.length === 1 && onlyPart._tag === 'Text') {\n return Effect.succeed(onlyPart.text)\n }\n\n return Effect.forEach(parts, contentPartToCodexInputPart)\n}\n\nconst contentToCodexFunctionOutput = (\n content: Content\n): Effect.Effect<OpenAiCodexFunctionOutput, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, contentPartToCodexInputPart)\n\nconst codexToolResultOutput = (\n content: Content,\n isError: boolean | undefined\n): Effect.Effect<OpenAiCodexFunctionOutput, LLMError> =>\n contentToCodexFunctionOutput(content).pipe(\n Effect.map(output => {\n if (isError !== true) return output\n\n const errorPart: OpenAiCodexInputTextPart = {\n type: 'input_text',\n text: 'Tool execution failed.'\n }\n\n return typeof output === 'string' ? `${errorPart.text}\\n\\n${output}` : [errorPart, ...output]\n })\n )\n\nconst serializeToolArguments = (params: unknown) =>\n encodeJsonString(params, 'Could not serialize OpenAI Codex tool arguments')\n\nconst toolCallToCodexInput = (\n call: ToolCall\n): Effect.Effect<OpenAiCodexFunctionCallInput, LLMError> =>\n Effect.gen(function* () {\n return {\n type: 'function_call',\n call_id: call.id,\n name: call.name,\n arguments: yield* serializeToolArguments(call.params)\n }\n })\n\nconst messageToCodexInput = (\n message: AgentMessage\n): Effect.Effect<ReadonlyArray<OpenAiCodexInputItem>, LLMError> =>\n Effect.gen(function* () {\n switch (message._tag) {\n case 'User':\n return [\n {\n role: 'user',\n content: yield* contentToUserInput(\n prependMessageContextToContent(message.content, messageContextText(message))\n )\n }\n ]\n case 'Assistant': {\n const content = yield* contentToText(\n prependMessageContextToContent(assistantContent(message), messageContextText(message)),\n 'Assistant'\n )\n const toolCallInputs = yield* Effect.forEach(\n assistantHostToolCalls(message),\n toolCallToCodexInput\n )\n\n if (content.length > 0) {\n const assistantMessage: OpenAiCodexInputItem = { role: 'assistant', content }\n\n return [assistantMessage, ...toolCallInputs]\n }\n\n return toolCallInputs\n }\n case 'ToolResult':\n return [\n {\n type: 'function_call_output',\n call_id: message.toolCallId,\n output: yield* codexToolResultOutput(\n prependMessageContextToContent(message.content, messageContextText(message)),\n message.isError\n )\n }\n ]\n }\n })\n\nconst toOpenAiCodexTool = (tool: ToolDef): OpenAiCodexTool => ({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters\n})\n\nexport const toOpenAiCodexRequestBody = (\n request: LLMRequest,\n config: {\n readonly maxOutputTokens: number\n readonly defaultReasoningEffort?: AgentReasoningEffort\n readonly reasoningSummary?: OpenAiCodexReasoningSummary\n }\n): Effect.Effect<OpenAiCodexRequestBody, LLMError> =>\n Effect.gen(function* () {\n yield* validateProviderTranscript(request.messages)\n const input = Arr.flatten(yield* Effect.forEach(request.messages, messageToCodexInput))\n\n const body: Omit<OpenAiCodexRequestBody, 'tools'> = {\n model: request.model,\n instructions: request.systemPrompt,\n input,\n store: false,\n stream: true,\n reasoning: {\n effort: request.reasoningEffort ?? config.defaultReasoningEffort ?? 'low',\n summary: config.reasoningSummary ?? 'auto'\n }\n }\n\n if (request.tools.length === 0) {\n return body\n }\n\n return {\n ...body,\n tools: request.tools.map(toOpenAiCodexTool),\n parallel_tool_calls: true\n }\n })\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\nconst stringField = (value: unknown, key: string) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n const field = Object.getOwnPropertyDescriptor(value, key)?.value\n\n return typeof field === 'string' ? field : undefined\n}\n\nconst recordField = (value: unknown, key: string) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n const field = Object.getOwnPropertyDescriptor(value, key)?.value\n\n return isRecord(field) ? field : undefined\n}\n\nconst openAiCodexProvider = 'openai_codex'\n\nconst providerSignalError = (input: {\n readonly message: string\n readonly providerCode?: string\n readonly fallbackKind?: ProviderFailureKind\n}) => {\n const provider = classifyProviderFailure({\n provider: openAiCodexProvider,\n message: input.message,\n ...(input.providerCode === undefined ? {} : { providerCode: input.providerCode }),\n ...(input.fallbackKind === undefined ? {} : { fallbackKind: input.fallbackKind })\n })\n\n return new LLMError({\n cause: providerFailureCause(provider.kind),\n message: `OpenAI Codex stream error: ${input.message}`,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n}\n\nconst parseToolArguments = (raw: string) =>\n decodeJsonString(raw, 'Invalid OpenAI Codex tool arguments JSON')\n\nconst textFromOutputItem = (item: OpenAiCodexOutputItem) => {\n switch (item.type) {\n case 'message':\n return Arr.map(item.content, content => content.text)\n case 'function_call':\n case 'reasoning':\n return []\n }\n}\n\nconst textFromOutputItems = (items: ReadonlyArray<OpenAiCodexOutputItem>) => {\n const textParts = Arr.flatten(Arr.map(items, textFromOutputItem))\n\n return textParts.join('')\n}\n\nconst reasoningFromOutputItem = (item: OpenAiCodexOutputItem) => {\n switch (item.type) {\n case 'reasoning':\n return [\n ...(item.summary ?? []).map(summary => summary.text),\n ...(item.content ?? []).map(content => content.text)\n ]\n case 'message':\n case 'function_call':\n return []\n }\n}\n\nconst reasoningFromOutputItems = (items: ReadonlyArray<OpenAiCodexOutputItem>) => {\n const reasoningParts = Arr.flatten(Arr.map(items, reasoningFromOutputItem))\n\n return reasoningParts.join('')\n}\n\nconst toAgentUsage = (usage: OpenAiCodexUsageResponse) =>\n AgentUsage.make({\n input: AgentInputUsage.make({\n total: usage.input_tokens,\n uncached: usage.input_tokens - (usage.input_tokens_details?.cached_tokens ?? 0),\n cacheRead: usage.input_tokens_details?.cached_tokens\n }),\n output: AgentOutputUsage.make({\n total: usage.output_tokens,\n reasoning: usage.output_tokens_details?.reasoning_tokens,\n text: usage.output_tokens - (usage.output_tokens_details?.reasoning_tokens ?? 0)\n })\n })\n\ntype ToLlmEventsOptions = {\n readonly allowEmptyStop: boolean\n}\n\nconst toLlmEvents = (\n response: OpenAiCodexResponse,\n options: ToLlmEventsOptions\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const text = response.output_text ?? textFromOutputItems(response.output)\n const reasoning = reasoningFromOutputItems(response.output)\n const reasoningEvents =\n reasoning.length > 0 ? [LLMReasoningDelta.make({ text: reasoning })] : []\n const textEvents = text.length > 0 ? [LLMTextDelta.make({ text })] : []\n const toolCallEvents = Arr.getSomes(\n yield* Effect.forEach(response.output, item => {\n switch (item.type) {\n case 'message':\n case 'reasoning':\n return Effect.succeed(Option.none())\n case 'function_call':\n return parseToolArguments(item.arguments).pipe(\n Effect.map(params =>\n Option.some(\n LLMToolCall.make({\n call: ToolCall.make({\n id: item.call_id,\n name: item.name,\n params\n })\n })\n )\n )\n )\n }\n })\n )\n\n if (textEvents.length === 0 && toolCallEvents.length === 0 && !options.allowEmptyStop) {\n return yield* Effect.fail(\n new LLMError({\n cause: 'invalid_response',\n message: 'OpenAI Codex response did not include text or tool calls',\n retryable: false\n })\n )\n }\n\n const events: Array<LLMEvent> = [\n ...reasoningEvents,\n ...textEvents,\n ...toolCallEvents,\n LLMDone.make({ stopReason: toolCallEvents.length > 0 ? 'tool_use' : 'stop' })\n ]\n\n if (response.usage !== undefined) {\n events.push(LLMUsage.make({ usage: toAgentUsage(response.usage) }))\n }\n\n return events\n })\n\nconst decodeOpenAiCodexResponse = (json: unknown) =>\n Schema.decodeUnknownEffect(OpenAiCodexResponse)(json).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid OpenAI Codex response: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst parseOpenAiCodexJsonResponse = (\n raw: string\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const json = yield* decodeJsonString(raw, 'Could not parse OpenAI Codex response JSON')\n const parsed = yield* decodeOpenAiCodexResponse(json)\n\n return yield* toLlmEvents(parsed, { allowEmptyStop: false })\n })\n\ntype OpenAiCodexBodyFormat = 'undecided' | 'sse' | 'json'\n\ntype OpenAiCodexSseState = {\n readonly hasTextDelta: boolean\n readonly hasReasoningDelta: boolean\n readonly hasToolCall: boolean\n readonly hasDone: boolean\n}\n\ntype OpenAiCodexSseStep = {\n readonly state: OpenAiCodexSseState\n readonly events: ReadonlyArray<LLMEvent>\n}\n\ntype OpenAiCodexBodyState = {\n readonly format: OpenAiCodexBodyFormat\n readonly buffer: string\n readonly sse: OpenAiCodexSseState\n}\n\nconst initialSseState: OpenAiCodexSseState = {\n hasTextDelta: false,\n hasReasoningDelta: false,\n hasToolCall: false,\n hasDone: false\n}\n\nconst initialBodyState: OpenAiCodexBodyState = {\n format: 'undecided',\n buffer: '',\n sse: initialSseState\n}\n\nconst normalizeNewlines = (text: string) => text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\nconst classifyCodexBody = (buffer: string): OpenAiCodexBodyFormat => {\n const trimmed = buffer.trimStart()\n\n if (trimmed.length === 0) {\n return 'undecided'\n }\n\n if (trimmed.startsWith('event:') || trimmed.startsWith('data:')) {\n return 'sse'\n }\n\n if ('event:'.startsWith(trimmed) || 'data:'.startsWith(trimmed)) {\n return 'undecided'\n }\n\n return 'json'\n}\n\nconst splitCompleteSseBlocks = (buffer: string) => {\n const blocks = buffer.split('\\n\\n')\n const tail = blocks.at(-1) ?? ''\n\n return { completeBlocks: blocks.slice(0, -1), tail }\n}\n\nconst dataFromSseBlock = (block: string) => {\n const lines = Arr.map(\n Arr.filter(block.split('\\n'), line => line.startsWith('data:')),\n line => line.slice(5).trimStart()\n )\n\n const data = lines.join('\\n').trim()\n\n if (data.length === 0 || data === '[DONE]') {\n return undefined\n }\n\n return data\n}\n\nconst parseOpenAiCodexSseJson = (data: string) =>\n decodeJsonString(data, 'Could not parse OpenAI Codex stream event JSON')\n\nconst decodeOpenAiCodexOutputItem = (value: unknown) =>\n Schema.decodeUnknownEffect(OpenAiCodexOutputItem)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid OpenAI Codex output item: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst invalidFunctionCallSseItemError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Invalid OpenAI Codex function call stream item',\n retryable: false\n })\n\nconst eventsFromOutputItem = (\n item: OpenAiCodexOutputItem\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> => {\n switch (item.type) {\n case 'message': {\n const text = textFromOutputItems([item])\n\n return Effect.succeed(text.length > 0 ? [LLMTextDelta.make({ text })] : [])\n }\n case 'reasoning': {\n const reasoning = reasoningFromOutputItems([item])\n\n return Effect.succeed(\n reasoning.length > 0 ? [LLMReasoningDelta.make({ text: reasoning })] : []\n )\n }\n case 'function_call':\n return parseToolArguments(item.arguments).pipe(\n Effect.map(params => [\n LLMToolCall.make({\n call: ToolCall.make({\n id: item.call_id,\n name: item.name,\n params\n })\n })\n ])\n )\n }\n}\n\nconst eventsFromOutputItemDone = (\n event: Record<string, unknown>\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n if (event.type !== 'response.output_item.done') {\n return []\n }\n\n const item = event.item\n\n if (item === undefined) {\n return yield* Effect.fail(invalidFunctionCallSseItemError())\n }\n\n return yield* decodeOpenAiCodexOutputItem(item).pipe(Effect.flatMap(eventsFromOutputItem))\n })\n\nconst finalResponseToEvents = (\n response: unknown,\n state: OpenAiCodexSseState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const parsedFinal = yield* decodeOpenAiCodexResponse(response)\n const finalEvents = yield* toLlmEvents(parsedFinal, {\n allowEmptyStop: state.hasTextDelta || state.hasToolCall\n })\n\n const shouldDedupe = state.hasTextDelta || state.hasReasoningDelta || state.hasToolCall\n const dedupedEvents = shouldDedupe\n ? finalEvents.filter(event => {\n if (state.hasTextDelta && event._tag === 'TextDelta') {\n return false\n }\n\n if (state.hasReasoningDelta && event._tag === 'ReasoningDelta') {\n return false\n }\n\n if (state.hasToolCall && event._tag === 'ToolCall') {\n return false\n }\n\n return true\n })\n : finalEvents\n\n if (!state.hasToolCall) {\n return dedupedEvents\n }\n\n return dedupedEvents.map(event =>\n event._tag === 'Done' ? LLMDone.make({ stopReason: 'tool_use' }) : event\n )\n })\n\nconst processSseData = (\n state: OpenAiCodexSseState,\n data: string\n): Effect.Effect<OpenAiCodexSseStep, LLMError> =>\n Effect.gen(function* () {\n const parsed = yield* parseOpenAiCodexSseJson(data)\n\n if (!isRecord(parsed)) {\n return { state, events: [] }\n }\n\n if (\n (parsed.type === 'response.output_text.delta' ||\n parsed.type === 'response.content_part.delta') &&\n typeof parsed.delta === 'string'\n ) {\n return {\n state: { ...state, hasTextDelta: true },\n events: [LLMTextDelta.make({ text: parsed.delta })]\n }\n }\n\n if (\n (parsed.type === 'response.reasoning_summary_text.delta' ||\n parsed.type === 'response.reasoning_text.delta') &&\n typeof parsed.delta === 'string'\n ) {\n return {\n state: { ...state, hasReasoningDelta: true },\n events: [LLMReasoningDelta.make({ text: parsed.delta })]\n }\n }\n\n const outputItemDoneEvents = yield* eventsFromOutputItemDone(parsed)\n if (outputItemDoneEvents.length > 0) {\n const events = outputItemDoneEvents.filter(event => {\n if (state.hasTextDelta && event._tag === 'TextDelta') {\n return false\n }\n\n if (state.hasReasoningDelta && event._tag === 'ReasoningDelta') {\n return false\n }\n\n if (state.hasToolCall && event._tag === 'ToolCall') {\n return false\n }\n\n return true\n })\n\n return {\n state: {\n hasTextDelta: state.hasTextDelta || events.some(event => event._tag === 'TextDelta'),\n hasReasoningDelta:\n state.hasReasoningDelta || events.some(event => event._tag === 'ReasoningDelta'),\n hasToolCall: state.hasToolCall || events.some(event => event._tag === 'ToolCall'),\n hasDone: state.hasDone\n },\n events\n }\n }\n\n if (parsed.type === 'response.completed') {\n const events = yield* finalResponseToEvents(parsed.response, state)\n const emittedText = events.some(event => event._tag === 'TextDelta')\n const emittedReasoning = events.some(event => event._tag === 'ReasoningDelta')\n const emittedToolCall = events.some(event => event._tag === 'ToolCall')\n\n return {\n state: {\n hasTextDelta: state.hasTextDelta || emittedText,\n hasReasoningDelta: state.hasReasoningDelta || emittedReasoning,\n hasToolCall: state.hasToolCall || emittedToolCall,\n hasDone: true\n },\n events\n }\n }\n\n if (parsed.type === 'response.failed') {\n const error = recordField(recordField(parsed, 'response'), 'error')\n const message = stringField(error, 'message') ?? 'OpenAI Codex response failed'\n const providerCode = stringField(error, 'code') ?? stringField(error, 'type')\n\n return yield* Effect.fail(\n providerSignalError({\n message,\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n if (parsed.type === 'error' && typeof parsed.message === 'string') {\n const providerCode = stringField(parsed, 'code') ?? stringField(parsed, 'type')\n\n return yield* Effect.fail(\n providerSignalError({\n message: parsed.message,\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n return { state, events: [] }\n })\n\nconst processSseBlock = (\n state: OpenAiCodexSseState,\n block: string\n): Effect.Effect<OpenAiCodexSseStep, LLMError> => {\n const data = dataFromSseBlock(block)\n\n if (data === undefined) {\n return Effect.succeed({ state, events: [] })\n }\n\n return processSseData(state, data)\n}\n\nconst processSseBlocks = (\n state: OpenAiCodexSseState,\n blocks: ReadonlyArray<string>\n): Effect.Effect<OpenAiCodexSseStep, LLMError> =>\n Effect.gen(function* () {\n const events: Array<LLMEvent> = []\n let currentState = state\n\n for (const block of blocks) {\n const step = yield* processSseBlock(currentState, block)\n currentState = step.state\n events.push(...step.events)\n }\n\n return { state: currentState, events }\n })\n\nconst processBodyChunk = (\n state: OpenAiCodexBodyState,\n chunk: string\n): Effect.Effect<OpenAiCodexSseStep & { readonly bodyState: OpenAiCodexBodyState }, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(`${state.buffer}${chunk}`)\n const format = state.format === 'undecided' ? classifyCodexBody(buffer) : state.format\n\n if (format !== 'sse') {\n return {\n state: state.sse,\n bodyState: { ...state, format, buffer },\n events: []\n }\n }\n\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(state.sse, split.completeBlocks)\n\n return {\n state: step.state,\n bodyState: { format, buffer: split.tail, sse: step.state },\n events: step.events\n }\n })\n\nconst finalizeBodyState = (\n state: OpenAiCodexBodyState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(state.buffer)\n const format = state.format === 'undecided' ? classifyCodexBody(buffer) : state.format\n\n if (format === 'json') {\n return yield* parseOpenAiCodexJsonResponse(buffer)\n }\n\n const events: Array<LLMEvent> = []\n let sseState = state.sse\n\n if (format === 'sse') {\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(sseState, split.completeBlocks)\n sseState = step.state\n events.push(...step.events)\n\n if (split.tail.trim().length > 0) {\n const tailStep = yield* processSseBlock(sseState, split.tail)\n sseState = tailStep.state\n events.push(...tailStep.events)\n }\n }\n\n if (!sseState.hasDone) {\n events.push(LLMDone.make({ stopReason: sseState.hasToolCall ? 'tool_use' : 'stop' }))\n }\n\n return events\n })\n\nconst toHttpClientLlmError =\n (message: string, retryable: boolean, kind: ProviderFailureKind = 'network') =>\n (error: HttpClientError.HttpClientError) =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${error.message}`,\n retryable,\n provider: providerErrorInfo({\n provider: openAiCodexProvider,\n kind: retryable ? kind : 'unknown'\n })\n })\n\nexport const streamOpenAiCodexResponse = (\n response: HttpClientResponse.HttpClientResponse\n): Stream.Stream<LLMEvent, LLMError> =>\n Stream.unwrap(\n Ref.make(initialBodyState).pipe(\n Effect.map(bodyStateRef => {\n const chunks = response.stream.pipe(\n Stream.mapError(\n toHttpClientLlmError('Could not read OpenAI Codex stream', true, 'stream')\n ),\n Stream.decodeText,\n Stream.mapEffect(chunk =>\n Effect.gen(function* () {\n const state = yield* Ref.get(bodyStateRef)\n const step = yield* processBodyChunk(state, chunk)\n yield* Ref.set(bodyStateRef, step.bodyState)\n return step.events\n })\n ),\n Stream.flatMap(events => Stream.fromIterable(events))\n )\n\n const finalEvents = Stream.fromEffect(\n Ref.get(bodyStateRef).pipe(Effect.flatMap(finalizeBodyState))\n ).pipe(Stream.flatMap(events => Stream.fromIterable(events)))\n\n return chunks.pipe(Stream.concat(finalEvents))\n })\n )\n )\n\nconst sendOpenAiCodexRequest = (\n config: OpenAiCodexProviderConfig,\n request: LLMRequest,\n client: HttpClient.HttpClient\n): Effect.Effect<HttpClientResponse.HttpClientResponse, LLMError> =>\n Effect.gen(function* () {\n const body = yield* toOpenAiCodexRequestBody(request, config)\n // Replayed transcripts can carry lone surrogates; harden the lowered\n // body so one bad historical string cannot poison every model call.\n const serializedBody = yield* encodeJsonString(\n replaceLoneSurrogatesDeep(body),\n 'Could not serialize OpenAI Codex request'\n )\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...openAiCodexAuthorizationHeaders(config.token),\n 'content-type': 'application/json',\n ...config.extraHeaders\n }\n\n const httpRequest = HttpClientRequest.post(config.responsesUrl ?? openAiCodexResponsesUrl).pipe(\n HttpClientRequest.setHeaders(headers),\n HttpClientRequest.bodyText(serializedBody, 'application/json')\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientLlmError('OpenAI Codex request failed', true)))\n\n if (response.status < 200 || response.status >= 300) {\n const errorText = yield* response.text.pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not read OpenAI Codex error body: ${error.message}`,\n retryable: false\n })\n )\n )\n\n const provider = classifyProviderFailure({\n provider: openAiCodexProvider,\n status: response.status,\n headers: response.headers,\n body: errorText\n })\n\n return yield* Effect.fail(\n new LLMError({\n cause: providerFailureCause(provider.kind),\n message: `OpenAI Codex returned ${response.status}`,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n )\n }\n\n return response\n }).pipe(Effect.withSpan('OpenAiCodexProvider.stream'))\n\nexport const makeOpenAiCodexProviderLayer = (config: OpenAiCodexProviderConfig) =>\n Layer.effect(LLMProvider)(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n\n return LLMProvider.of({\n stream: request =>\n Stream.fromEffect(sendOpenAiCodexRequest(config, request, client)).pipe(\n Stream.flatMap(streamOpenAiCodexResponse)\n )\n })\n })\n )\n"],"mappings":";;;;;;;;;AAoIA,IAAM,kCAAN,cAA8C,OAAO,MACnD,iCACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,cAAc,CAAC;CACtC,MAAM,OAAO;AACf,CAAC,EAAE,CAAC;AAEJ,IAAM,2BAAN,cAAuC,OAAO,MAC5C,0BACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,gBAAgB,CAAC;CACxC,MAAM,OAAO;AACf,CAAC,EAAE,CAAC;AAEJ,IAAM,wBAAN,cAAoC,OAAO,MAA6B,uBAAuB,EAAE;CAC/F,MAAM,OAAO,SAAS,CAAC,aAAa,CAAC;CACrC,MAAM,OAAO;AACf,CAAC,EAAE,CAAC;AAEJ,IAAM,2BAAN,cAAuC,OAAO,MAC5C,0BACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,SAAS,CAAC;CACjC,SAAS,OAAO,MAAM,qBAAqB;AAC7C,CAAC,EAAE,CAAC;AAEJ,IAAM,gCAAN,cAA4C,OAAO,MACjD,+BACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,eAAe,CAAC;CACvC,SAAS,OAAO;CAChB,MAAM,OAAO;CACb,WAAW,OAAO;AACpB,CAAC,EAAE,CAAC;AAEJ,IAAM,6BAAN,cAAyC,OAAO,MAC9C,4BACF,EAAE;CACA,MAAM,OAAO,SAAS,CAAC,WAAW,CAAC;CACnC,SAAS,OAAO,SAAS,OAAO,MAAM,+BAA+B,CAAC;CACtE,SAAS,OAAO,SAAS,OAAO,MAAM,wBAAwB,CAAC;AACjE,CAAC,EAAE,CAAC;AAEJ,IAAM,gCAAN,cAA4C,OAAO,MACjD,+BACF,EAAE,EACA,eAAe,OAAO,SAAS,OAA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AAa,gCAAgC,WAC3C,MAAM,OAAO,WAAW,EACtB,OAAO,IAAI,aAAa;CACtB,MAAM,SAAS,OAAO,WAAW;CAEjC,OAAO,YAAY,GAAG,EACpB,SAAQ,YACN,OAAO,WAAW,uBAAuB,QAAQ,SAAS,MAAM,CAAC,EAAE,KACjE,OAAO,QAAQ,yBAAyB,CAC1C,EACJ,CAAC;AACH,CAAC,CACH"}
|
|
@@ -25,8 +25,8 @@ declare const mergeSkillsets: (sources: ReadonlyArray<SkillsetSource>) => Effect
|
|
|
25
25
|
readonly name: string;
|
|
26
26
|
readonly hints: readonly string[];
|
|
27
27
|
readonly template: string;
|
|
28
|
-
readonly description?: string | undefined;
|
|
29
28
|
readonly source?: string | undefined;
|
|
29
|
+
readonly description?: string | undefined;
|
|
30
30
|
readonly arguments?: readonly {
|
|
31
31
|
readonly required: boolean;
|
|
32
32
|
readonly name: string;
|
package/dist/tools/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { EmptyToolParams, ModelVisibleToolError, ModelVisibleToolErrorInput, ModelVisibleToolErrorReason, ModelVisibleToolErrorStructuredContent, ModelVisibleToolErrorStructuredContentSchema, ResolvedToolSet, SchemaToolExecutionInput, ToolAccess, ToolExecutionInput, ToolMetadata, ToolModule, ToolRegistration, ToolRegistryError, makeTool, makeToolExecutorLayer, modelVisibleToolError, modelVisibleToolErrorResult, modelVisibleToolErrorStructuredContent, resolveTools } from "./registry.mjs";
|
|
2
2
|
import { QuestionExecutionInput, QuestionToolOptions, makeQuestionToolDef, makeQuestionToolModule, makeQuestionToolRegistration, questionToolName } from "./question.mjs";
|
|
3
|
-
import { TaskExecutionInput, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName } from "./task.mjs";
|
|
4
|
-
export { EmptyToolParams, ModelVisibleToolError, type ModelVisibleToolErrorInput, ModelVisibleToolErrorReason, type ModelVisibleToolErrorStructuredContent, ModelVisibleToolErrorStructuredContentSchema, 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, modelVisibleToolError, modelVisibleToolErrorResult, modelVisibleToolErrorStructuredContent, questionToolName, resolveTools, subagentResultText, taskSubagentRunId, taskToolName };
|
|
3
|
+
import { TaskExecutionInput, TaskModelDefinition, TaskReasoningEffortDefinition, TaskRuntimeSelectionOptions, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName } from "./task.mjs";
|
|
4
|
+
export { EmptyToolParams, ModelVisibleToolError, type ModelVisibleToolErrorInput, ModelVisibleToolErrorReason, type ModelVisibleToolErrorStructuredContent, ModelVisibleToolErrorStructuredContentSchema, type QuestionExecutionInput, type QuestionToolOptions, type ResolvedToolSet, type SchemaToolExecutionInput, type TaskExecutionInput, type TaskModelDefinition, type TaskReasoningEffortDefinition, type TaskRuntimeSelectionOptions, 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, modelVisibleToolError, modelVisibleToolErrorResult, modelVisibleToolErrorStructuredContent, questionToolName, resolveTools, subagentResultText, taskSubagentRunId, taskToolName };
|
package/dist/tools/task.d.mts
CHANGED
|
@@ -1,21 +1,33 @@
|
|
|
1
1
|
import { ToolModule, ToolRegistration, ToolRegistryError } from "./registry.mjs";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
|
-
import { AgentEvent, ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
4
|
-
import * as Schema from "effect/Schema";
|
|
3
|
+
import { AgentEvent, AgentReasoningEffort, ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
5
4
|
import { ToolError } from "@yolk-sdk/agent/loop";
|
|
6
5
|
|
|
7
6
|
//#region src/tools/task.d.ts
|
|
8
7
|
declare const taskToolName = "task";
|
|
9
|
-
|
|
10
|
-
readonly description:
|
|
11
|
-
readonly prompt:
|
|
12
|
-
readonly subagent_type:
|
|
13
|
-
|
|
14
|
-
|
|
8
|
+
type TaskToolParams = {
|
|
9
|
+
readonly description: string;
|
|
10
|
+
readonly prompt: string;
|
|
11
|
+
readonly subagent_type: string;
|
|
12
|
+
readonly model?: string;
|
|
13
|
+
readonly reasoning_effort?: AgentReasoningEffort;
|
|
14
|
+
};
|
|
15
15
|
type TaskSubagentDefinition = {
|
|
16
16
|
readonly name: string;
|
|
17
17
|
readonly description: string;
|
|
18
18
|
};
|
|
19
|
+
type TaskModelDefinition = {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly description: string;
|
|
22
|
+
};
|
|
23
|
+
type TaskReasoningEffortDefinition = {
|
|
24
|
+
readonly value: AgentReasoningEffort;
|
|
25
|
+
readonly description: string;
|
|
26
|
+
};
|
|
27
|
+
type TaskRuntimeSelectionOptions = {
|
|
28
|
+
readonly models?: ReadonlyArray<TaskModelDefinition>;
|
|
29
|
+
readonly reasoningEfforts?: ReadonlyArray<TaskReasoningEffortDefinition>;
|
|
30
|
+
};
|
|
19
31
|
type TaskSubagentContext = {
|
|
20
32
|
readonly subagent?: boolean;
|
|
21
33
|
};
|
|
@@ -24,7 +36,7 @@ type TaskExecutionInput<Context> = {
|
|
|
24
36
|
readonly context: Context;
|
|
25
37
|
readonly params: TaskToolParams;
|
|
26
38
|
};
|
|
27
|
-
type TaskToolOptions<Context> = {
|
|
39
|
+
type TaskToolOptions<Context> = TaskRuntimeSelectionOptions & {
|
|
28
40
|
readonly subagents: ReadonlyArray<TaskSubagentDefinition>;
|
|
29
41
|
readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>;
|
|
30
42
|
readonly execute: (input: TaskExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>;
|
|
@@ -38,10 +50,11 @@ type TaskToolResultInput = {
|
|
|
38
50
|
readonly startedAtMs: number;
|
|
39
51
|
readonly endedAtMs: number;
|
|
40
52
|
readonly model: string;
|
|
53
|
+
readonly reasoningEffort?: AgentReasoningEffort;
|
|
41
54
|
readonly isError?: boolean;
|
|
42
55
|
};
|
|
43
56
|
declare const makeTaskToolRegistration: <Context>(options: TaskToolOptions<Context>) => ToolRegistration<Context>;
|
|
44
|
-
declare const makeTaskToolDef: (subagents: ReadonlyArray<TaskSubagentDefinition
|
|
57
|
+
declare const makeTaskToolDef: (subagents: ReadonlyArray<TaskSubagentDefinition>, runtimeSelections?: TaskRuntimeSelectionOptions) => import("@yolk-sdk/agent/protocol").ToolDef;
|
|
45
58
|
declare const makeTaskToolModule: <Context>(options: TaskToolOptions<Context>) => ToolModule<Context>;
|
|
46
59
|
declare const makeNonRecursiveTaskToolModule: <Context extends TaskSubagentContext>(options: TaskToolOptions<Context>) => ToolModule<Context>;
|
|
47
60
|
declare const formatTaskResult: (output: string) => string;
|
|
@@ -49,5 +62,5 @@ declare const taskSubagentRunId: (parentToolCallId: string) => string;
|
|
|
49
62
|
declare const subagentResultText: (events: ReadonlyArray<AgentEvent>) => string;
|
|
50
63
|
declare const makeTaskToolResult: (input: TaskToolResultInput) => ToolResult;
|
|
51
64
|
//#endregion
|
|
52
|
-
export { TaskExecutionInput, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName };
|
|
65
|
+
export { TaskExecutionInput, TaskModelDefinition, TaskReasoningEffortDefinition, TaskRuntimeSelectionOptions, TaskSubagentContext, TaskSubagentDefinition, TaskToolOptions, TaskToolParams, TaskToolResultInput, formatTaskResult, makeNonRecursiveTaskToolModule, makeTaskToolDef, makeTaskToolModule, makeTaskToolRegistration, makeTaskToolResult, subagentResultText, taskSubagentRunId, taskToolName };
|
|
53
66
|
//# 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":";;;;;;cAsBa,YAAA;AAAA,KAiBD,cAAA;EAAA,SACD,WAAA;EAAA,SACA,MAAA;EAAA,SACA,aAAA;EAAA,SACA,KAAA;EAAA,SACA,gBAAA,GAAmB,oBAAoB;AAAA;AAAA,KAGtC,sBAAA;EAAA,SACD,IAAA;EAAA,SACA,WAAW;AAAA;AAAA,KAGV,mBAAA;EAAA,SACD,EAAA;EAAA,SACA,WAAW;AAAA;AAAA,KAGV,6BAAA;EAAA,SACD,KAAA,EAAO,oBAAoB;EAAA,SAC3B,WAAA;AAAA;AAAA,KAGC,2BAAA;EAAA,SACD,MAAA,GAAS,aAAA,CAAc,mBAAA;EAAA,SACvB,gBAAA,GAAmB,aAAA,CAAc,6BAAA;AAAA;AAAA,KAGhC,mBAAA;EAAA,SACD,QAAQ;AAAA;AAAA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yolk-sdk/agent/loop";
|
|
6
6
|
//#region src/tools/task.ts
|
|
7
7
|
const taskToolName = "task";
|
|
8
|
-
const
|
|
8
|
+
const TaskToolBaseFields = {
|
|
9
9
|
description: Schema.String.pipe(Schema.annotate({ description: "A short 3-5 word description of the task." })),
|
|
10
10
|
prompt: Schema.String.pipe(Schema.annotate({ description: "The complete task instructions for the subagent, including all context it needs." })),
|
|
11
11
|
subagent_type: Schema.String.pipe(Schema.annotate({ description: "The specialized subagent type to use for this task." }))
|
|
12
|
-
}
|
|
12
|
+
};
|
|
13
13
|
const taskToolError = (message, cause) => new ToolError({
|
|
14
14
|
tool: taskToolName,
|
|
15
15
|
message,
|
|
@@ -20,10 +20,38 @@ const taskModelVisibleError = (message) => modelVisibleToolError({
|
|
|
20
20
|
message,
|
|
21
21
|
reason: "validation"
|
|
22
22
|
});
|
|
23
|
+
const enumRecord = (values) => Object.fromEntries(values.map((value) => [value, value]));
|
|
24
|
+
const optionalRuntimeSelection = (input) => Schema.optionalKey(Schema.Enum(enumRecord(input.values)).pipe(Schema.annotate({ description: input.description })));
|
|
25
|
+
const configuredTaskToolParams = (options) => {
|
|
26
|
+
const model = options.models === void 0 || options.models.length === 0 ? void 0 : optionalRuntimeSelection({
|
|
27
|
+
values: options.models.map((item) => item.id),
|
|
28
|
+
description: "Model for this subagent. Omit to inherit the host runtime model."
|
|
29
|
+
});
|
|
30
|
+
const reasoningEffort = options.reasoningEfforts === void 0 || options.reasoningEfforts.length === 0 ? void 0 : optionalRuntimeSelection({
|
|
31
|
+
values: options.reasoningEfforts.map((item) => item.value),
|
|
32
|
+
description: "Reasoning effort for this subagent. Omit to inherit the host runtime effort."
|
|
33
|
+
});
|
|
34
|
+
if (model !== void 0 && reasoningEffort !== void 0) return Schema.Struct({
|
|
35
|
+
...TaskToolBaseFields,
|
|
36
|
+
model,
|
|
37
|
+
reasoning_effort: reasoningEffort
|
|
38
|
+
});
|
|
39
|
+
if (model !== void 0) return Schema.Struct({
|
|
40
|
+
...TaskToolBaseFields,
|
|
41
|
+
model
|
|
42
|
+
});
|
|
43
|
+
if (reasoningEffort !== void 0) return Schema.Struct({
|
|
44
|
+
...TaskToolBaseFields,
|
|
45
|
+
reasoning_effort: reasoningEffort
|
|
46
|
+
});
|
|
47
|
+
return Schema.Struct(TaskToolBaseFields);
|
|
48
|
+
};
|
|
23
49
|
const trimmedTaskParams = (params) => ({
|
|
24
50
|
description: params.description.trim(),
|
|
25
51
|
prompt: params.prompt.trim(),
|
|
26
|
-
subagent_type: params.subagent_type.trim()
|
|
52
|
+
subagent_type: params.subagent_type.trim(),
|
|
53
|
+
...params.model === void 0 ? {} : { model: params.model },
|
|
54
|
+
...params.reasoning_effort === void 0 ? {} : { reasoning_effort: params.reasoning_effort }
|
|
27
55
|
});
|
|
28
56
|
const validateTaskParams = (params) => {
|
|
29
57
|
const trimmed = trimmedTaskParams(params);
|
|
@@ -38,19 +66,31 @@ const requireKnownSubagent = (subagents, name) => {
|
|
|
38
66
|
return subagent === void 0 ? Effect.fail(taskModelVisibleError(`Unknown subagent type: ${name}`)) : Effect.succeed(subagent);
|
|
39
67
|
};
|
|
40
68
|
const subagentDescription = (subagent) => `- ${subagent.name}: ${subagent.description}`;
|
|
41
|
-
const
|
|
69
|
+
const modelDescription = (model) => `- ${model.id}: ${model.description}`;
|
|
70
|
+
const reasoningEffortDescription = (effort) => `- ${effort.value}: ${effort.description}`;
|
|
71
|
+
const taskToolDescription = (options) => [
|
|
42
72
|
"Launch a new agent to handle complex, multistep tasks autonomously.",
|
|
43
73
|
"Use this when delegating focused work to a specialized subagent would save context or allow parallel exploration.",
|
|
44
74
|
"To run subagents in parallel, call this task tool multiple times in the same assistant response.",
|
|
45
75
|
"Yolk runs same-turn task calls concurrently automatically.",
|
|
46
76
|
"A fresh subagent only sees the prompt you provide, so include all required context.",
|
|
47
77
|
"Subagents can use their normal tools but cannot launch further task subagents in v1.",
|
|
48
|
-
subagents.length === 0 ? "No subagent types are currently available." : `Available subagent types:\n${subagents.map(subagentDescription).join("\n")}
|
|
49
|
-
|
|
78
|
+
options.subagents.length === 0 ? "No subagent types are currently available." : `Available subagent types:\n${options.subagents.map(subagentDescription).join("\n")}`,
|
|
79
|
+
options.models === void 0 || options.models.length === 0 ? void 0 : [
|
|
80
|
+
"Available subagent models:",
|
|
81
|
+
options.models.map(modelDescription).join("\n"),
|
|
82
|
+
"Omit model to inherit the host runtime model."
|
|
83
|
+
].join("\n"),
|
|
84
|
+
options.reasoningEfforts === void 0 || options.reasoningEfforts.length === 0 ? void 0 : [
|
|
85
|
+
"Available subagent reasoning efforts:",
|
|
86
|
+
options.reasoningEfforts.map(reasoningEffortDescription).join("\n"),
|
|
87
|
+
"Omit reasoning_effort to inherit the host runtime effort."
|
|
88
|
+
].join("\n")
|
|
89
|
+
].filter((section) => section !== void 0).join("\n\n");
|
|
50
90
|
const makeTaskToolRegistration = (options) => makeTool({
|
|
51
91
|
name: taskToolName,
|
|
52
|
-
description: taskToolDescription(options
|
|
53
|
-
parameters:
|
|
92
|
+
description: taskToolDescription(options),
|
|
93
|
+
parameters: configuredTaskToolParams(options),
|
|
54
94
|
access: "read",
|
|
55
95
|
isEnabled: options.isEnabled,
|
|
56
96
|
invalidParamsMessage: (error) => `Invalid task arguments: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -65,8 +105,9 @@ const makeTaskToolRegistration = (options) => makeTool({
|
|
|
65
105
|
});
|
|
66
106
|
})
|
|
67
107
|
});
|
|
68
|
-
const makeTaskToolDef = (subagents) => makeTaskToolRegistration({
|
|
108
|
+
const makeTaskToolDef = (subagents, runtimeSelections = {}) => makeTaskToolRegistration({
|
|
69
109
|
subagents,
|
|
110
|
+
...runtimeSelections,
|
|
70
111
|
execute: ({ call }) => Effect.succeed(ToolResult.make({
|
|
71
112
|
toolCallId: call.id,
|
|
72
113
|
content: ""
|
|
@@ -106,7 +147,8 @@ const makeTaskToolResult = (input) => ToolResult.make({
|
|
|
106
147
|
ended_at_ms: input.endedAtMs,
|
|
107
148
|
duration_ms: Math.max(0, input.endedAtMs - input.startedAtMs),
|
|
108
149
|
status: input.isError === true ? "error" : "completed",
|
|
109
|
-
model: input.model
|
|
150
|
+
model: input.model,
|
|
151
|
+
...input.reasoningEffort === void 0 ? {} : { reasoning_effort: input.reasoningEffort }
|
|
110
152
|
}
|
|
111
153
|
});
|
|
112
154
|
//#endregion
|
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 {\n assistantContent,\n contentText,\n makeSubagentRunId,\n ToolResult,\n type AgentEvent,\n type AgentMessage,\n type ToolCall\n} from '@yolk-sdk/agent/protocol'\nimport {\n makeTool,\n modelVisibleToolError,\n type ModelVisibleToolError,\n type ToolModule,\n type ToolRegistration,\n type ToolRegistryError\n} from './registry.ts'\n\nexport const taskToolName = 'task'\n\nconst TaskToolParams = Schema.Struct({\n description: Schema.String.pipe(\n Schema.annotate({ description: 'A short 3-5 word description of the task.' })\n ),\n prompt: Schema.String.pipe(\n Schema.annotate({\n description:\n '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 taskModelVisibleError = (message: string) =>\n modelVisibleToolError({\n tool: taskToolName,\n message,\n reason: 'validation'\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 = (\n params: TaskToolParams\n): Effect.Effect<\n {\n readonly description: string\n readonly prompt: string\n readonly subagent_type: string\n },\n ModelVisibleToolError\n> => {\n const trimmed = trimmedTaskParams(params)\n\n if (trimmed.description.length === 0) {\n return Effect.fail(taskModelVisibleError('description must not be empty'))\n }\n\n if (trimmed.prompt.length === 0) {\n return Effect.fail(taskModelVisibleError('prompt must not be empty'))\n }\n\n if (trimmed.subagent_type.length === 0) {\n return Effect.fail(taskModelVisibleError('subagent_type must not be empty'))\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): Effect.Effect<TaskSubagentDefinition, ModelVisibleToolError> => {\n const subagent = findSubagent(subagents, name)\n\n return subagent === undefined\n ? Effect.fail(taskModelVisibleError(`Unknown subagent type: ${name}`))\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> =>\n makeTool({\n name: taskToolName,\n description: taskToolDescription(options.subagents),\n parameters: TaskToolParams,\n access: 'read',\n isEnabled: options.isEnabled,\n invalidParamsMessage: error =>\n `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(\n taskToolError(`Tool is not configured: ${call.name}`, 'not_found')\n )\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>(\n options: TaskToolOptions<Context>\n): ToolModule<Context> => ({\n id: 'task',\n tools: [makeTaskToolRegistration(options)]\n})\n\nexport const makeNonRecursiveTaskToolModule = <Context extends TaskSubagentContext>(\n options: TaskToolOptions<Context>\n): ToolModule<Context> =>\n makeTaskToolModule({\n ...options,\n isEnabled: context =>\n 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) =>\n ['<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) =>\n 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":";;;;;;AAqBA,MAAa,eAAe;AAE5B,MAAM,iBAAiB,OAAO,OAAO;CACnC,aAAa,OAAO,OAAO,KACzB,OAAO,SAAS,EAAE,aAAa,4CAA4C,CAAC,CAC9E;CACA,QAAQ,OAAO,OAAO,KACpB,OAAO,SAAS,EACd,aACE,mFACJ,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,yBAAyB,YAC7B,sBAAsB;CACpB,MAAM;CACN;CACA,QAAQ;AACV,CAAC;AAEH,MAAM,qBAAqB,YAA4B;CACrD,aAAa,OAAO,YAAY,KAAK;CACrC,QAAQ,OAAO,OAAO,KAAK;CAC3B,eAAe,OAAO,cAAc,KAAK;AAC3C;AAEA,MAAM,sBACJ,WAQG;CACH,MAAM,UAAU,kBAAkB,MAAM;CAExC,IAAI,QAAQ,YAAY,WAAW,GACjC,OAAO,OAAO,KAAK,sBAAsB,+BA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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 AgentReasoningEffort,\n type ToolCall\n} from '@yolk-sdk/agent/protocol'\nimport {\n makeTool,\n modelVisibleToolError,\n type ModelVisibleToolError,\n type ToolModule,\n type ToolRegistration,\n type ToolRegistryError\n} from './registry.ts'\n\nexport const taskToolName = 'task'\n\nconst TaskToolBaseFields = {\n description: Schema.String.pipe(\n Schema.annotate({ description: 'A short 3-5 word description of the task.' })\n ),\n prompt: Schema.String.pipe(\n Schema.annotate({\n description:\n '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 = {\n readonly description: string\n readonly prompt: string\n readonly subagent_type: string\n readonly model?: string\n readonly reasoning_effort?: AgentReasoningEffort\n}\n\nexport type TaskSubagentDefinition = {\n readonly name: string\n readonly description: string\n}\n\nexport type TaskModelDefinition = {\n readonly id: string\n readonly description: string\n}\n\nexport type TaskReasoningEffortDefinition = {\n readonly value: AgentReasoningEffort\n readonly description: string\n}\n\nexport type TaskRuntimeSelectionOptions = {\n readonly models?: ReadonlyArray<TaskModelDefinition>\n readonly reasoningEfforts?: ReadonlyArray<TaskReasoningEffortDefinition>\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> = TaskRuntimeSelectionOptions & {\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 reasoningEffort?: AgentReasoningEffort\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 taskModelVisibleError = (message: string) =>\n modelVisibleToolError({\n tool: taskToolName,\n message,\n reason: 'validation'\n })\n\nconst enumRecord = <Value extends string>(\n values: ReadonlyArray<Value>\n): Readonly<Record<string, Value>> => Object.fromEntries(values.map(value => [value, value]))\n\nconst optionalRuntimeSelection = <Value extends string>(input: {\n readonly values: ReadonlyArray<Value>\n readonly description: string\n}) =>\n Schema.optionalKey(\n Schema.Enum(enumRecord(input.values)).pipe(Schema.annotate({ description: input.description }))\n )\n\nconst configuredTaskToolParams = (options: TaskRuntimeSelectionOptions) => {\n const model =\n options.models === undefined || options.models.length === 0\n ? undefined\n : optionalRuntimeSelection({\n values: options.models.map(item => item.id),\n description: 'Model for this subagent. Omit to inherit the host runtime model.'\n })\n const reasoningEffort =\n options.reasoningEfforts === undefined || options.reasoningEfforts.length === 0\n ? undefined\n : optionalRuntimeSelection({\n values: options.reasoningEfforts.map(item => item.value),\n description:\n 'Reasoning effort for this subagent. Omit to inherit the host runtime effort.'\n })\n\n if (model !== undefined && reasoningEffort !== undefined) {\n return Schema.Struct({\n ...TaskToolBaseFields,\n model,\n reasoning_effort: reasoningEffort\n })\n }\n\n if (model !== undefined) {\n return Schema.Struct({ ...TaskToolBaseFields, model })\n }\n\n if (reasoningEffort !== undefined) {\n return Schema.Struct({ ...TaskToolBaseFields, reasoning_effort: reasoningEffort })\n }\n\n return Schema.Struct(TaskToolBaseFields)\n}\n\nconst trimmedTaskParams = (params: TaskToolParams): TaskToolParams => ({\n description: params.description.trim(),\n prompt: params.prompt.trim(),\n subagent_type: params.subagent_type.trim(),\n ...(params.model === undefined ? {} : { model: params.model }),\n ...(params.reasoning_effort === undefined ? {} : { reasoning_effort: params.reasoning_effort })\n})\n\nconst validateTaskParams = (\n params: TaskToolParams\n): Effect.Effect<\n {\n readonly description: string\n readonly prompt: string\n readonly subagent_type: string\n },\n ModelVisibleToolError\n> => {\n const trimmed = trimmedTaskParams(params)\n\n if (trimmed.description.length === 0) {\n return Effect.fail(taskModelVisibleError('description must not be empty'))\n }\n\n if (trimmed.prompt.length === 0) {\n return Effect.fail(taskModelVisibleError('prompt must not be empty'))\n }\n\n if (trimmed.subagent_type.length === 0) {\n return Effect.fail(taskModelVisibleError('subagent_type must not be empty'))\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): Effect.Effect<TaskSubagentDefinition, ModelVisibleToolError> => {\n const subagent = findSubagent(subagents, name)\n\n return subagent === undefined\n ? Effect.fail(taskModelVisibleError(`Unknown subagent type: ${name}`))\n : Effect.succeed(subagent)\n}\n\nconst subagentDescription = (subagent: TaskSubagentDefinition) =>\n `- ${subagent.name}: ${subagent.description}`\n\nconst modelDescription = (model: TaskModelDefinition) => `- ${model.id}: ${model.description}`\n\nconst reasoningEffortDescription = (effort: TaskReasoningEffortDefinition) =>\n `- ${effort.value}: ${effort.description}`\n\nconst taskToolDescription = (\n options: TaskRuntimeSelectionOptions & {\n readonly subagents: ReadonlyArray<TaskSubagentDefinition>\n }\n) =>\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 options.subagents.length === 0\n ? 'No subagent types are currently available.'\n : `Available subagent types:\\n${options.subagents.map(subagentDescription).join('\\n')}`,\n options.models === undefined || options.models.length === 0\n ? undefined\n : [\n 'Available subagent models:',\n options.models.map(modelDescription).join('\\n'),\n 'Omit model to inherit the host runtime model.'\n ].join('\\n'),\n options.reasoningEfforts === undefined || options.reasoningEfforts.length === 0\n ? undefined\n : [\n 'Available subagent reasoning efforts:',\n options.reasoningEfforts.map(reasoningEffortDescription).join('\\n'),\n 'Omit reasoning_effort to inherit the host runtime effort.'\n ].join('\\n')\n ]\n .filter(section => section !== undefined)\n .join('\\n\\n')\n\nexport const makeTaskToolRegistration = <Context>(\n options: TaskToolOptions<Context>\n): ToolRegistration<Context> =>\n makeTool({\n name: taskToolName,\n description: taskToolDescription(options),\n parameters: configuredTaskToolParams(options),\n access: 'read',\n isEnabled: options.isEnabled,\n invalidParamsMessage: error =>\n `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(\n taskToolError(`Tool is not configured: ${call.name}`, 'not_found')\n )\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 = (\n subagents: ReadonlyArray<TaskSubagentDefinition>,\n runtimeSelections: TaskRuntimeSelectionOptions = {}\n) =>\n makeTaskToolRegistration({\n subagents,\n ...runtimeSelections,\n execute: ({ call }) => Effect.succeed(ToolResult.make({ toolCallId: call.id, content: '' }))\n }).def\n\nexport const makeTaskToolModule = <Context>(\n options: TaskToolOptions<Context>\n): ToolModule<Context> => ({\n id: 'task',\n tools: [makeTaskToolRegistration(options)]\n})\n\nexport const makeNonRecursiveTaskToolModule = <Context extends TaskSubagentContext>(\n options: TaskToolOptions<Context>\n): ToolModule<Context> =>\n makeTaskToolModule({\n ...options,\n isEnabled: context =>\n 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) =>\n ['<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) =>\n 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 ...(input.reasoningEffort === undefined ? {} : { reasoning_effort: input.reasoningEffort })\n }\n })\n"],"mappings":";;;;;;AAsBA,MAAa,eAAe;AAE5B,MAAM,qBAAqB;CACzB,aAAa,OAAO,OAAO,KACzB,OAAO,SAAS,EAAE,aAAa,4CAA4C,CAAC,CAC9E;CACA,QAAQ,OAAO,OAAO,KACpB,OAAO,SAAS,EACd,aACE,mFACJ,CAAC,CACH;CACA,eAAe,OAAO,OAAO,KAC3B,OAAO,SAAS,EAAE,aAAa,sDAAsD,CAAC,CACxF;AACF;AA2DA,MAAM,iBAAiB,SAAiB,UACtC,IAAI,UAAU;CACZ,MAAM;CACN;CACA;AACF,CAAC;AAEH,MAAM,yBAAyB,YAC7B,sBAAsB;CACpB,MAAM;CACN;CACA,QAAQ;AACV,CAAC;AAEH,MAAM,c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AC;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,UACjC,WAAW,KAAK;CACd,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;EACb,GAAI,MAAM,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB,MAAM,gBAAgB;CAC3F;AACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk-sdk/agent",
|
|
3
|
-
"version": "0.1.0-canary.
|
|
3
|
+
"version": "0.1.0-canary.53",
|
|
4
4
|
"description": "Protocol, loop, runtime, client, compaction, tools, React, providers, OAuth, skillset, and voice primitives for building Yolk agents.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -120,7 +120,6 @@ type OpenAiCodexRequestBody = {
|
|
|
120
120
|
readonly model: string
|
|
121
121
|
readonly instructions: string
|
|
122
122
|
readonly input: ReadonlyArray<OpenAiCodexInputItem>
|
|
123
|
-
readonly max_output_tokens: number
|
|
124
123
|
readonly store: false
|
|
125
124
|
readonly stream: true
|
|
126
125
|
readonly reasoning: {
|
|
@@ -427,7 +426,6 @@ export const toOpenAiCodexRequestBody = (
|
|
|
427
426
|
model: request.model,
|
|
428
427
|
instructions: request.systemPrompt,
|
|
429
428
|
input,
|
|
430
|
-
max_output_tokens: config.maxOutputTokens,
|
|
431
429
|
store: false,
|
|
432
430
|
stream: true,
|
|
433
431
|
reasoning: {
|
package/src/tools/README.md
CHANGED
|
@@ -51,7 +51,11 @@ aborts, and implementation bugs outside typed tool execution.
|
|
|
51
51
|
|
|
52
52
|
`task` is the standard tool for delegating focused work to a subagent. The SDK owns the
|
|
53
53
|
tool schema, validation, event metadata shape, and result formatting. Host apps still own
|
|
54
|
-
execution: model
|
|
54
|
+
execution: available model/reasoning choices, provider layers, prompts, auth, concrete tools,
|
|
55
|
+
storage, and policy. When choices are configured, the tool exposes optional `model` and
|
|
56
|
+
`reasoning_effort` fields; omission lets the host inherit its current runtime settings. Model ids
|
|
57
|
+
are opaque host values. Reasoning effort values are `minimal`, `low`, `medium`, `high`, and
|
|
58
|
+
`xhigh`.
|
|
55
59
|
|
|
56
60
|
Use `makeNonRecursiveTaskToolModule` for the top-level agent so nested subagents do not receive
|
|
57
61
|
`task` again:
|
|
@@ -77,10 +81,20 @@ const taskToolModule = makeNonRecursiveTaskToolModule<ToolContext>({
|
|
|
77
81
|
{ name: 'general', description: 'Handle complex multi-step work.' },
|
|
78
82
|
{ name: 'explore', description: 'Explore code and docs.' }
|
|
79
83
|
],
|
|
84
|
+
models: [
|
|
85
|
+
{ id: 'gpt-5.5', description: 'Strong general-purpose model.' },
|
|
86
|
+
{ id: 'fast-model', description: 'Fast model for focused exploration.' }
|
|
87
|
+
],
|
|
88
|
+
reasoningEfforts: [
|
|
89
|
+
{ value: 'medium', description: 'Balanced default for normal exploration.' },
|
|
90
|
+
{ value: 'high', description: 'Use for difficult reasoning.' }
|
|
91
|
+
],
|
|
80
92
|
execute: ({ call, context, params }) =>
|
|
81
93
|
Effect.gen(function* () {
|
|
82
94
|
const startedAtMs = yield* Clock.currentTimeMillis
|
|
83
95
|
const subagentRunId = makeSubagentRunId(call.id)
|
|
96
|
+
const model = params.model ?? 'gpt-5.5'
|
|
97
|
+
const reasoningEffort = params.reasoning_effort ?? 'medium'
|
|
84
98
|
const subagentToolSet = yield* resolveSubagentToolSet({
|
|
85
99
|
...context,
|
|
86
100
|
subagent: true
|
|
@@ -89,7 +103,8 @@ const taskToolModule = makeNonRecursiveTaskToolModule<ToolContext>({
|
|
|
89
103
|
messages: [UserMessage.make({ content: params.prompt })],
|
|
90
104
|
systemPrompt: subagentSystemPrompt(params.subagent_type),
|
|
91
105
|
tools: subagentToolSet.tools,
|
|
92
|
-
model
|
|
106
|
+
model,
|
|
107
|
+
reasoningEffort
|
|
93
108
|
}).pipe(Stream.runCollect, Effect.provide(makeToolExecutorLayer(subagentToolSet)))
|
|
94
109
|
const endedAtMs = yield* Clock.currentTimeMillis
|
|
95
110
|
|
|
@@ -101,12 +116,17 @@ const taskToolModule = makeNonRecursiveTaskToolModule<ToolContext>({
|
|
|
101
116
|
subagentRunId,
|
|
102
117
|
startedAtMs,
|
|
103
118
|
endedAtMs,
|
|
104
|
-
model
|
|
119
|
+
model,
|
|
120
|
+
reasoningEffort
|
|
105
121
|
})
|
|
106
122
|
})
|
|
107
123
|
})
|
|
108
124
|
```
|
|
109
125
|
|
|
126
|
+
Host apps should advertise only runtime choices they can execute. If support depends on the
|
|
127
|
+
selected model, validate the model/reasoning combination before constructing the child provider
|
|
128
|
+
layer and return a model-visible error for unsupported combinations.
|
|
129
|
+
|
|
110
130
|
Host apps should usually resolve a smaller subagent toolset:
|
|
111
131
|
|
|
112
132
|
- include read/search tools that help delegated work
|
package/src/tools/index.ts
CHANGED
|
@@ -42,6 +42,9 @@ export type {
|
|
|
42
42
|
export type { QuestionExecutionInput, QuestionToolOptions } from './question.ts'
|
|
43
43
|
export type {
|
|
44
44
|
TaskExecutionInput,
|
|
45
|
+
TaskModelDefinition,
|
|
46
|
+
TaskReasoningEffortDefinition,
|
|
47
|
+
TaskRuntimeSelectionOptions,
|
|
45
48
|
TaskSubagentContext,
|
|
46
49
|
TaskSubagentDefinition,
|
|
47
50
|
TaskToolOptions,
|
package/src/tools/task.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
ToolResult,
|
|
9
9
|
type AgentEvent,
|
|
10
10
|
type AgentMessage,
|
|
11
|
+
type AgentReasoningEffort,
|
|
11
12
|
type ToolCall
|
|
12
13
|
} from '@yolk-sdk/agent/protocol'
|
|
13
14
|
import {
|
|
@@ -21,7 +22,7 @@ import {
|
|
|
21
22
|
|
|
22
23
|
export const taskToolName = 'task'
|
|
23
24
|
|
|
24
|
-
const
|
|
25
|
+
const TaskToolBaseFields = {
|
|
25
26
|
description: Schema.String.pipe(
|
|
26
27
|
Schema.annotate({ description: 'A short 3-5 word description of the task.' })
|
|
27
28
|
),
|
|
@@ -34,15 +35,36 @@ const TaskToolParams = Schema.Struct({
|
|
|
34
35
|
subagent_type: Schema.String.pipe(
|
|
35
36
|
Schema.annotate({ description: 'The specialized subagent type to use for this task.' })
|
|
36
37
|
)
|
|
37
|
-
}
|
|
38
|
+
}
|
|
38
39
|
|
|
39
|
-
export type TaskToolParams =
|
|
40
|
+
export type TaskToolParams = {
|
|
41
|
+
readonly description: string
|
|
42
|
+
readonly prompt: string
|
|
43
|
+
readonly subagent_type: string
|
|
44
|
+
readonly model?: string
|
|
45
|
+
readonly reasoning_effort?: AgentReasoningEffort
|
|
46
|
+
}
|
|
40
47
|
|
|
41
48
|
export type TaskSubagentDefinition = {
|
|
42
49
|
readonly name: string
|
|
43
50
|
readonly description: string
|
|
44
51
|
}
|
|
45
52
|
|
|
53
|
+
export type TaskModelDefinition = {
|
|
54
|
+
readonly id: string
|
|
55
|
+
readonly description: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type TaskReasoningEffortDefinition = {
|
|
59
|
+
readonly value: AgentReasoningEffort
|
|
60
|
+
readonly description: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type TaskRuntimeSelectionOptions = {
|
|
64
|
+
readonly models?: ReadonlyArray<TaskModelDefinition>
|
|
65
|
+
readonly reasoningEfforts?: ReadonlyArray<TaskReasoningEffortDefinition>
|
|
66
|
+
}
|
|
67
|
+
|
|
46
68
|
export type TaskSubagentContext = {
|
|
47
69
|
readonly subagent?: boolean
|
|
48
70
|
}
|
|
@@ -53,7 +75,7 @@ export type TaskExecutionInput<Context> = {
|
|
|
53
75
|
readonly params: TaskToolParams
|
|
54
76
|
}
|
|
55
77
|
|
|
56
|
-
export type TaskToolOptions<Context> = {
|
|
78
|
+
export type TaskToolOptions<Context> = TaskRuntimeSelectionOptions & {
|
|
57
79
|
readonly subagents: ReadonlyArray<TaskSubagentDefinition>
|
|
58
80
|
readonly isEnabled?: (context: Context) => Effect.Effect<boolean, ToolRegistryError>
|
|
59
81
|
readonly execute: (input: TaskExecutionInput<Context>) => Effect.Effect<ToolResult, ToolError>
|
|
@@ -68,6 +90,7 @@ export type TaskToolResultInput = {
|
|
|
68
90
|
readonly startedAtMs: number
|
|
69
91
|
readonly endedAtMs: number
|
|
70
92
|
readonly model: string
|
|
93
|
+
readonly reasoningEffort?: AgentReasoningEffort
|
|
71
94
|
readonly isError?: boolean
|
|
72
95
|
}
|
|
73
96
|
|
|
@@ -85,10 +108,60 @@ const taskModelVisibleError = (message: string) =>
|
|
|
85
108
|
reason: 'validation'
|
|
86
109
|
})
|
|
87
110
|
|
|
88
|
-
const
|
|
111
|
+
const enumRecord = <Value extends string>(
|
|
112
|
+
values: ReadonlyArray<Value>
|
|
113
|
+
): Readonly<Record<string, Value>> => Object.fromEntries(values.map(value => [value, value]))
|
|
114
|
+
|
|
115
|
+
const optionalRuntimeSelection = <Value extends string>(input: {
|
|
116
|
+
readonly values: ReadonlyArray<Value>
|
|
117
|
+
readonly description: string
|
|
118
|
+
}) =>
|
|
119
|
+
Schema.optionalKey(
|
|
120
|
+
Schema.Enum(enumRecord(input.values)).pipe(Schema.annotate({ description: input.description }))
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
const configuredTaskToolParams = (options: TaskRuntimeSelectionOptions) => {
|
|
124
|
+
const model =
|
|
125
|
+
options.models === undefined || options.models.length === 0
|
|
126
|
+
? undefined
|
|
127
|
+
: optionalRuntimeSelection({
|
|
128
|
+
values: options.models.map(item => item.id),
|
|
129
|
+
description: 'Model for this subagent. Omit to inherit the host runtime model.'
|
|
130
|
+
})
|
|
131
|
+
const reasoningEffort =
|
|
132
|
+
options.reasoningEfforts === undefined || options.reasoningEfforts.length === 0
|
|
133
|
+
? undefined
|
|
134
|
+
: optionalRuntimeSelection({
|
|
135
|
+
values: options.reasoningEfforts.map(item => item.value),
|
|
136
|
+
description:
|
|
137
|
+
'Reasoning effort for this subagent. Omit to inherit the host runtime effort.'
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
if (model !== undefined && reasoningEffort !== undefined) {
|
|
141
|
+
return Schema.Struct({
|
|
142
|
+
...TaskToolBaseFields,
|
|
143
|
+
model,
|
|
144
|
+
reasoning_effort: reasoningEffort
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (model !== undefined) {
|
|
149
|
+
return Schema.Struct({ ...TaskToolBaseFields, model })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (reasoningEffort !== undefined) {
|
|
153
|
+
return Schema.Struct({ ...TaskToolBaseFields, reasoning_effort: reasoningEffort })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return Schema.Struct(TaskToolBaseFields)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const trimmedTaskParams = (params: TaskToolParams): TaskToolParams => ({
|
|
89
160
|
description: params.description.trim(),
|
|
90
161
|
prompt: params.prompt.trim(),
|
|
91
|
-
subagent_type: params.subagent_type.trim()
|
|
162
|
+
subagent_type: params.subagent_type.trim(),
|
|
163
|
+
...(params.model === undefined ? {} : { model: params.model }),
|
|
164
|
+
...(params.reasoning_effort === undefined ? {} : { reasoning_effort: params.reasoning_effort })
|
|
92
165
|
})
|
|
93
166
|
|
|
94
167
|
const validateTaskParams = (
|
|
@@ -135,7 +208,16 @@ const requireKnownSubagent = (
|
|
|
135
208
|
const subagentDescription = (subagent: TaskSubagentDefinition) =>
|
|
136
209
|
`- ${subagent.name}: ${subagent.description}`
|
|
137
210
|
|
|
138
|
-
const
|
|
211
|
+
const modelDescription = (model: TaskModelDefinition) => `- ${model.id}: ${model.description}`
|
|
212
|
+
|
|
213
|
+
const reasoningEffortDescription = (effort: TaskReasoningEffortDefinition) =>
|
|
214
|
+
`- ${effort.value}: ${effort.description}`
|
|
215
|
+
|
|
216
|
+
const taskToolDescription = (
|
|
217
|
+
options: TaskRuntimeSelectionOptions & {
|
|
218
|
+
readonly subagents: ReadonlyArray<TaskSubagentDefinition>
|
|
219
|
+
}
|
|
220
|
+
) =>
|
|
139
221
|
[
|
|
140
222
|
'Launch a new agent to handle complex, multistep tasks autonomously.',
|
|
141
223
|
'Use this when delegating focused work to a specialized subagent would save context or allow parallel exploration.',
|
|
@@ -143,18 +225,34 @@ const taskToolDescription = (subagents: ReadonlyArray<TaskSubagentDefinition>) =
|
|
|
143
225
|
'Yolk runs same-turn task calls concurrently automatically.',
|
|
144
226
|
'A fresh subagent only sees the prompt you provide, so include all required context.',
|
|
145
227
|
'Subagents can use their normal tools but cannot launch further task subagents in v1.',
|
|
146
|
-
subagents.length === 0
|
|
228
|
+
options.subagents.length === 0
|
|
147
229
|
? 'No subagent types are currently available.'
|
|
148
|
-
: `Available subagent types:\n${subagents.map(subagentDescription).join('\n')}
|
|
149
|
-
|
|
230
|
+
: `Available subagent types:\n${options.subagents.map(subagentDescription).join('\n')}`,
|
|
231
|
+
options.models === undefined || options.models.length === 0
|
|
232
|
+
? undefined
|
|
233
|
+
: [
|
|
234
|
+
'Available subagent models:',
|
|
235
|
+
options.models.map(modelDescription).join('\n'),
|
|
236
|
+
'Omit model to inherit the host runtime model.'
|
|
237
|
+
].join('\n'),
|
|
238
|
+
options.reasoningEfforts === undefined || options.reasoningEfforts.length === 0
|
|
239
|
+
? undefined
|
|
240
|
+
: [
|
|
241
|
+
'Available subagent reasoning efforts:',
|
|
242
|
+
options.reasoningEfforts.map(reasoningEffortDescription).join('\n'),
|
|
243
|
+
'Omit reasoning_effort to inherit the host runtime effort.'
|
|
244
|
+
].join('\n')
|
|
245
|
+
]
|
|
246
|
+
.filter(section => section !== undefined)
|
|
247
|
+
.join('\n\n')
|
|
150
248
|
|
|
151
249
|
export const makeTaskToolRegistration = <Context>(
|
|
152
250
|
options: TaskToolOptions<Context>
|
|
153
251
|
): ToolRegistration<Context> =>
|
|
154
252
|
makeTool({
|
|
155
253
|
name: taskToolName,
|
|
156
|
-
description: taskToolDescription(options
|
|
157
|
-
parameters:
|
|
254
|
+
description: taskToolDescription(options),
|
|
255
|
+
parameters: configuredTaskToolParams(options),
|
|
158
256
|
access: 'read',
|
|
159
257
|
isEnabled: options.isEnabled,
|
|
160
258
|
invalidParamsMessage: error =>
|
|
@@ -174,9 +272,13 @@ export const makeTaskToolRegistration = <Context>(
|
|
|
174
272
|
})
|
|
175
273
|
})
|
|
176
274
|
|
|
177
|
-
export const makeTaskToolDef = (
|
|
275
|
+
export const makeTaskToolDef = (
|
|
276
|
+
subagents: ReadonlyArray<TaskSubagentDefinition>,
|
|
277
|
+
runtimeSelections: TaskRuntimeSelectionOptions = {}
|
|
278
|
+
) =>
|
|
178
279
|
makeTaskToolRegistration({
|
|
179
280
|
subagents,
|
|
281
|
+
...runtimeSelections,
|
|
180
282
|
execute: ({ call }) => Effect.succeed(ToolResult.make({ toolCallId: call.id, content: '' }))
|
|
181
283
|
}).def
|
|
182
284
|
|
|
@@ -231,6 +333,7 @@ export const makeTaskToolResult = (input: TaskToolResultInput) =>
|
|
|
231
333
|
ended_at_ms: input.endedAtMs,
|
|
232
334
|
duration_ms: Math.max(0, input.endedAtMs - input.startedAtMs),
|
|
233
335
|
status: input.isError === true ? 'error' : 'completed',
|
|
234
|
-
model: input.model
|
|
336
|
+
model: input.model,
|
|
337
|
+
...(input.reasoningEffort === undefined ? {} : { reasoning_effort: input.reasoningEffort })
|
|
235
338
|
}
|
|
236
339
|
})
|