@shuind/dsh-codex-harness 0.3.1 → 0.3.3
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/CHANGELOG.md +29 -0
- package/README.md +21 -43
- package/docs/preset-library.md +2 -2
- package/docs/tool-policy.md +1 -1
- package/lib/client.js +1738 -327
- package/lib/compact-command.js +7 -1
- package/lib/compaction.js +7 -1
- package/lib/hybrid-executor.js +23 -12
- package/lib/index.js +1266 -36
- package/lib/preferences.js +21 -2
- package/lib/tool-policy.js +11 -2
- package/lib/typert.js +42 -1
- package/lib/types/client/desktop.d.ts +20 -42
- package/lib/types/client/desktop.js +191 -126
- package/lib/types/client/index.d.ts +104 -28
- package/lib/types/client/index.js +97 -15
- package/lib/types/client/policy-drafts.d.ts +18 -0
- package/lib/types/client/policy-drafts.js +27 -0
- package/lib/types/client/policy-locale.d.ts +80 -20
- package/lib/types/client/policy-locale.js +197 -80
- package/lib/types/client/preset-manager.d.ts +25 -2
- package/lib/types/client/preset-manager.js +89 -5
- package/lib/types/client/preset-requests.d.ts +44 -1
- package/lib/types/client/preset-requests.js +150 -0
- package/lib/types/client/tool-policy.d.ts +7 -2
- package/lib/types/client/tool-policy.js +48 -6
- package/lib/types/contracts/preset-editor-schema.d.ts +35 -0
- package/lib/types/contracts/preset-editor-schema.js +39 -0
- package/lib/types/contracts/settings.d.ts +12 -0
- package/lib/types/contracts/settings.js +10 -1
- package/lib/types/contracts/ui-contracts.d.ts +52 -0
- package/lib/types/contracts/ui-contracts.js +58 -0
- package/lib/types/contracts/update.d.ts +73 -0
- package/lib/types/contracts/update.js +291 -0
- package/lib/types/entries/index.js +20 -2
- package/lib/types/entries/preferences.d.ts +2 -0
- package/lib/types/entries/preferences.js +9 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +1 -1
- package/lib/types/hybrid/hybrid-sdk.js +27 -13
- package/lib/types/presets/preset-editor.d.ts +13 -1
- package/lib/types/presets/preset-editor.js +24 -1
- package/lib/types/presets/pro-mode-store.d.ts +13 -0
- package/lib/types/presets/pro-mode-store.js +69 -0
- package/lib/types/responses/background-sse-codec.d.ts +23 -0
- package/lib/types/responses/background-sse-codec.js +230 -0
- package/lib/types/responses/background-stream.d.ts +28 -0
- package/lib/types/responses/background-stream.js +351 -0
- package/lib/types/responses/compact-checkpoint.js +3 -10
- package/lib/types/responses/fetch-transport.js +24 -9
- package/lib/types/responses/remote-compact.js +39 -11
- package/lib/types/responses/wire-rewrite.d.ts +4 -0
- package/lib/types/responses/wire-rewrite.js +30 -4
- package/lib/types/tools/codex-subagent.d.ts +14 -0
- package/lib/types/tools/codex-subagent.js +269 -0
- package/lib/types/update/checker.d.ts +14 -0
- package/lib/types/update/checker.js +166 -0
- package/locale/en.json +1 -1
- package/locale/hybrid-executor/en.json +1 -1
- package/locale/hybrid-executor/zh.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -2
- package/src/client/desktop.tsx +370 -153
- package/src/client/index.tsx +122 -22
- package/src/client/policy-drafts.ts +45 -0
- package/src/client/policy-locale.ts +197 -80
- package/src/client/preset-manager.tsx +125 -4
- package/src/client/preset-requests.ts +185 -1
- package/src/client/tool-policy.tsx +63 -9
- package/src/contracts/preset-editor-schema.ts +44 -0
- package/src/contracts/settings.ts +20 -1
- package/src/contracts/ui-contracts.ts +91 -0
- package/src/contracts/update.ts +307 -0
- package/src/entries/index.ts +25 -2
- package/src/entries/preferences.ts +9 -0
- package/src/hybrid/hybrid-sdk.ts +28 -12
- package/src/presets/preset-editor.ts +31 -3
- package/src/presets/pro-mode-store.ts +80 -0
- package/src/responses/background-sse-codec.ts +237 -0
- package/src/responses/background-stream.ts +371 -0
- package/src/responses/compact-checkpoint.ts +2 -8
- package/src/responses/fetch-transport.ts +28 -9
- package/src/responses/remote-compact.ts +41 -11
- package/src/responses/wire-rewrite.ts +34 -3
- package/src/tools/codex-subagent.ts +290 -0
- package/src/update/checker.ts +193 -0
- package/tsdown.config.ts +4 -0
|
@@ -4,6 +4,11 @@ import type { StreamChunk } from '@deepseek-ai/dsh-llm'
|
|
|
4
4
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
5
5
|
import { zstdCompressSync, zstdDecompressSync } from 'node:zlib'
|
|
6
6
|
import { isGptModel } from '../contracts/settings.ts'
|
|
7
|
+
import {
|
|
8
|
+
applyBackgroundStreamBody,
|
|
9
|
+
isOfficialOpenAiResponsesUrl,
|
|
10
|
+
wrapResilientBackgroundSseResponse,
|
|
11
|
+
} from './background-stream.ts'
|
|
7
12
|
import { captureCodexErrors } from './sse-diagnostics.ts'
|
|
8
13
|
import {
|
|
9
14
|
applyRequestWireOptions,
|
|
@@ -27,6 +32,7 @@ interface CapabilityEntry {
|
|
|
27
32
|
const CAPABILITY_CACHE_TTL_MS = 10 * 60_000
|
|
28
33
|
const CAPABILITY_CACHE_MAX_ENTRIES = 64
|
|
29
34
|
export const CONTEXT_LIMIT_ERROR = /context_length_exceeded|maximum context length|context window|too many tokens/i
|
|
35
|
+
const REASONING_MODE_ERROR = /reasoning\.mode|reasoning_mode|['"`]mode['"`].*\bpro\b/i
|
|
30
36
|
const WEB_SEARCH_ERROR = /web_search|external_web_access/i
|
|
31
37
|
const CUSTOM_PATCH_ERROR = /apply_patch|custom_tool|custom\s+tool|grammar|lark/i
|
|
32
38
|
|
|
@@ -108,7 +114,7 @@ function shouldFallbackResponse(response: Response, errorText: string): boolean
|
|
|
108
114
|
&& response.status !== 422) {
|
|
109
115
|
return false
|
|
110
116
|
}
|
|
111
|
-
return !CONTEXT_LIMIT_ERROR.test(errorText)
|
|
117
|
+
return !CONTEXT_LIMIT_ERROR.test(errorText) && !REASONING_MODE_ERROR.test(errorText)
|
|
112
118
|
}
|
|
113
119
|
|
|
114
120
|
function isAbortError(error: unknown, signal: AbortSignal): boolean {
|
|
@@ -173,9 +179,22 @@ function installGlobalHostedWebSearchPatch(): () => void {
|
|
|
173
179
|
if (isNativeCompactionTriggerBody(body)) return requestAndCapture(input, init)
|
|
174
180
|
|
|
175
181
|
const requestBody = applyRequestWireOptions(body, options)
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
182
|
+
const useBackgroundStream = options.reasoningMode === 'pro'
|
|
183
|
+
&& options.backgroundStream === true
|
|
184
|
+
&& isOfficialOpenAiResponsesUrl(request.url)
|
|
185
|
+
&& requestBody.stream === true
|
|
186
|
+
&& requestBody.background !== false
|
|
187
|
+
const transportBody = useBackgroundStream ? applyBackgroundStreamBody(requestBody) : requestBody
|
|
188
|
+
const sendResponsesRequest = async (target: RequestInfo | URL, requestInit?: RequestInit): Promise<Response> => {
|
|
189
|
+
const response = await original(target, requestInit)
|
|
190
|
+
const wrapped = useBackgroundStream
|
|
191
|
+
? wrapResilientBackgroundSseResponse(response, request, original)
|
|
192
|
+
: response
|
|
193
|
+
return captureCodexErrors(wrapped)
|
|
194
|
+
}
|
|
195
|
+
const baseBody = isGptModel(transportBody.model) && hasRemoteCompaction(transportBody, options.trustedCheckpoints)
|
|
196
|
+
? replaceRemoteCompactions(transportBody, options.trustedCheckpoints)
|
|
197
|
+
: transportBody
|
|
179
198
|
const key = capabilityKey(request.url, baseBody.model)
|
|
180
199
|
const activeOptions = effectiveWireOptions(key, options)
|
|
181
200
|
|
|
@@ -189,18 +208,18 @@ function installGlobalHostedWebSearchPatch(): () => void {
|
|
|
189
208
|
|
|
190
209
|
if (!usesHostedWebSearch && !usesCustomApplyPatch) {
|
|
191
210
|
return baseBody === body
|
|
192
|
-
?
|
|
193
|
-
:
|
|
211
|
+
? sendResponsesRequest(input, init)
|
|
212
|
+
: sendResponsesRequest(jsonRequest(request, baseBody))
|
|
194
213
|
}
|
|
195
214
|
|
|
196
215
|
const hostedBody = rewriteCodexResponsesBody(baseBody, activeOptions)
|
|
197
216
|
const hostedRequest = jsonRequest(request, hostedBody)
|
|
198
217
|
const fallbackRequest = baseBody === body ? request.clone() : jsonRequest(request, baseBody)
|
|
199
|
-
const sendPlainFallback = (): Promise<Response> =>
|
|
218
|
+
const sendPlainFallback = (): Promise<Response> => sendResponsesRequest(fallbackRequest)
|
|
200
219
|
|
|
201
220
|
let response: Response
|
|
202
221
|
try {
|
|
203
|
-
response = await
|
|
222
|
+
response = await sendResponsesRequest(hostedRequest)
|
|
204
223
|
} catch (error) {
|
|
205
224
|
if (isAbortError(error, request.signal)) throw error
|
|
206
225
|
// Transport failures fall back once without poisoning the capability cache.
|
|
@@ -222,7 +241,7 @@ function installGlobalHostedWebSearchPatch(): () => void {
|
|
|
222
241
|
mentionsWebSearch ? { hostedWebSearch: false } : { customApplyPatch: false },
|
|
223
242
|
)
|
|
224
243
|
try {
|
|
225
|
-
const reducedResponse = await
|
|
244
|
+
const reducedResponse = await sendResponsesRequest(
|
|
226
245
|
jsonRequest(request, rewriteCodexResponsesBody(baseBody, reducedOptions)),
|
|
227
246
|
)
|
|
228
247
|
if (reducedResponse.ok) return reducedResponse
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import type { Context } from '@deepseek-ai/cordis'
|
|
4
4
|
import { credentialRef } from '@deepseek-ai/dsh-credentials'
|
|
5
|
-
import
|
|
5
|
+
import { offloadedImageText, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm'
|
|
6
|
+
import type { GenerateOptions, ImageBlock, Message, StreamChunk, TokenUsage, ToolSchema } from '@deepseek-ai/dsh-llm'
|
|
6
7
|
import { isGptModel, readHostSettings } from '../contracts/settings.ts'
|
|
7
8
|
import {
|
|
8
9
|
collectTrustedCompactionMarkers,
|
|
@@ -98,9 +99,37 @@ async function apiHeaders(
|
|
|
98
99
|
return headers
|
|
99
100
|
}
|
|
100
101
|
|
|
101
|
-
|
|
102
|
+
const VALID_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
|
|
103
|
+
|
|
104
|
+
function hasValidImageRef(attachment: unknown): attachment is ImageBlock['attachment'] {
|
|
105
|
+
if (typeof attachment !== 'object' || attachment === null) return false
|
|
106
|
+
const record = attachment as Record<string, unknown>
|
|
107
|
+
return typeof record.attachmentId === 'string' && record.attachmentId.length > 0
|
|
108
|
+
&& typeof record.mediaType === 'string' && VALID_IMAGE_MEDIA_TYPES.has(record.mediaType)
|
|
109
|
+
&& typeof record.width === 'number' && typeof record.height === 'number'
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function formatOffloadedImage(ctx: Context, block: ImageBlock): string {
|
|
113
|
+
const attachments = ctx.get('attachments' as never) as { imageHostPath?: (ref: ImageBlock['attachment']) => string | undefined } | undefined
|
|
114
|
+
const fs = ctx.get('fs' as never) as { processPathFromHostPath?: (hostPath: string) => string | undefined } | undefined
|
|
115
|
+
const access = typeof attachments?.imageHostPath === 'function' && typeof fs?.processPathFromHostPath === 'function'
|
|
116
|
+
? resolveImageAttachmentAccess(attachments as never, hostPath => fs.processPathFromHostPath!(hostPath), block.attachment)
|
|
117
|
+
: undefined
|
|
118
|
+
return offloadedImageText(block.attachment, access)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function textOf(ctx: Context, message: Pick<Message, 'content'>): string {
|
|
102
122
|
return message.content
|
|
103
|
-
.map(block =>
|
|
123
|
+
.map(block => {
|
|
124
|
+
if (block.type === 'text') return block.text
|
|
125
|
+
if (block.type === 'image') {
|
|
126
|
+
if (block.offloaded !== true || !hasValidImageRef(block.attachment)) {
|
|
127
|
+
throw new Error('Codex remote compaction requires the DSH adapter for image attachments')
|
|
128
|
+
}
|
|
129
|
+
return formatOffloadedImage(ctx, block)
|
|
130
|
+
}
|
|
131
|
+
return ''
|
|
132
|
+
})
|
|
104
133
|
.join('')
|
|
105
134
|
}
|
|
106
135
|
|
|
@@ -112,18 +141,18 @@ function stripCompactionPrompt(messages: readonly RequestMessage[]): readonly Re
|
|
|
112
141
|
return messages
|
|
113
142
|
}
|
|
114
143
|
|
|
115
|
-
function extractInstructions(options: GenerateOptions, messages: readonly RequestMessage[]): string | undefined {
|
|
144
|
+
function extractInstructions(ctx: Context, options: GenerateOptions, messages: readonly RequestMessage[]): string | undefined {
|
|
116
145
|
if (options.system !== undefined) return options.system
|
|
117
146
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
118
147
|
const message = messages[index]!
|
|
119
148
|
if (message.role !== 'system') continue
|
|
120
|
-
const text = textOf(message)
|
|
149
|
+
const text = textOf(ctx, message)
|
|
121
150
|
return text.length > 0 ? text : undefined
|
|
122
151
|
}
|
|
123
152
|
return undefined
|
|
124
153
|
}
|
|
125
154
|
|
|
126
|
-
function responsesInput(messages: readonly RequestMessage[]): JsonObject[] {
|
|
155
|
+
function responsesInput(ctx: Context, messages: readonly RequestMessage[]): JsonObject[] {
|
|
127
156
|
const result: JsonObject[] = []
|
|
128
157
|
for (const message of messages) {
|
|
129
158
|
// This compact transport cannot serialize attachment file references losslessly.
|
|
@@ -131,7 +160,7 @@ function responsesInput(messages: readonly RequestMessage[]): JsonObject[] {
|
|
|
131
160
|
throw new Error('Codex remote compaction requires the DSH adapter for attachments')
|
|
132
161
|
}
|
|
133
162
|
if (message.role === 'system') continue
|
|
134
|
-
const text = textOf(message)
|
|
163
|
+
const text = textOf(ctx, message)
|
|
135
164
|
if (message.role === 'tool') {
|
|
136
165
|
result.push({ type: 'function_call_output', call_id: message.toolCallId.split('|')[0]!, output: text })
|
|
137
166
|
continue
|
|
@@ -175,17 +204,18 @@ function responsesTools(tools: readonly ToolSchema[] | undefined): JsonObject[]
|
|
|
175
204
|
}
|
|
176
205
|
|
|
177
206
|
function compactBody(
|
|
207
|
+
ctx: Context,
|
|
178
208
|
options: GenerateOptions,
|
|
179
209
|
wireOptions: CodexRequestWireOptions,
|
|
180
210
|
isV2Responses: boolean,
|
|
181
211
|
): { body: JsonObject; preCompactInput: JsonObject[] } {
|
|
182
212
|
const messages = stripCompactionPrompt(options.messages)
|
|
183
|
-
const instructions = extractInstructions(options, messages)
|
|
213
|
+
const instructions = extractInstructions(ctx, options, messages)
|
|
184
214
|
const tools = responsesTools(options.tools)
|
|
185
215
|
const serviceTier = wireOptions.serviceTier ?? serviceTierOf(options)
|
|
186
216
|
const body: JsonObject = {
|
|
187
217
|
model: options.model,
|
|
188
|
-
input: responsesInput(messages),
|
|
218
|
+
input: responsesInput(ctx, messages),
|
|
189
219
|
...instructions !== undefined ? { instructions } : isV2Responses ? { instructions: '' } : {},
|
|
190
220
|
...tools === undefined ? {} : { tools },
|
|
191
221
|
...typeof options.sessionId === 'string' && options.sessionId.length > 0
|
|
@@ -325,7 +355,7 @@ async function remoteCompact(
|
|
|
325
355
|
...wireOptions,
|
|
326
356
|
trustedCheckpoints: wireOptions.trustedCheckpoints ?? collectTrustedCompactionMarkers(options.messages),
|
|
327
357
|
}
|
|
328
|
-
const initial = compactBody(options, compactWireOptions, isV2Responses)
|
|
358
|
+
const initial = compactBody(ctx, options, compactWireOptions, isV2Responses)
|
|
329
359
|
let preCompactInput = initial.preCompactInput
|
|
330
360
|
let response = await sendWithRetry(endpoint, headers, initial.body, options.signal)
|
|
331
361
|
|
|
@@ -334,7 +364,7 @@ async function remoteCompact(
|
|
|
334
364
|
&& canRewriteCompactTools(options, wireOptions)) {
|
|
335
365
|
const errorText = await response.clone().text().catch(() => '')
|
|
336
366
|
if (!CONTEXT_LIMIT_ERROR.test(errorText)) {
|
|
337
|
-
const reduced = compactBody(options, {
|
|
367
|
+
const reduced = compactBody(ctx, options, {
|
|
338
368
|
...compactWireOptions,
|
|
339
369
|
hostedWebSearch: false,
|
|
340
370
|
customApplyPatch: false,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Pure Responses wire transformations for hosted search, custom `apply_patch`, and compaction items. */
|
|
2
2
|
|
|
3
3
|
import type { GenerateOptions } from '@deepseek-ai/dsh-llm'
|
|
4
|
-
import { isGptModel } from '../contracts/settings.ts'
|
|
4
|
+
import { isGptModel, supportsApiProMode } from '../contracts/settings.ts'
|
|
5
5
|
import { APPLY_PATCH_DESCRIPTION, APPLY_PATCH_GRAMMAR } from '../tools/patch.ts'
|
|
6
6
|
import {
|
|
7
7
|
REMOTE_COMPACTION_OPEN,
|
|
@@ -17,6 +17,10 @@ export type { JsonObject }
|
|
|
17
17
|
export interface CodexRequestWireOptions {
|
|
18
18
|
/** Provider-facing request option preserved by older DSH LLM adapters. */
|
|
19
19
|
serviceTier?: string
|
|
20
|
+
/** Optional Responses reasoning mode override (e.g. 'pro' for GPT-5.6/6+). */
|
|
21
|
+
reasoningMode?: 'standard' | 'pro'
|
|
22
|
+
/** Enable background+stream resilient execution on the official OpenAI Responses API. */
|
|
23
|
+
backgroundStream?: boolean
|
|
20
24
|
/** Whether local web_search should become the hosted Responses tool. */
|
|
21
25
|
hostedWebSearch?: boolean
|
|
22
26
|
/** Whether apply_patch should use the Responses custom grammar tool. */
|
|
@@ -255,7 +259,34 @@ export function hasRemoteCompaction(
|
|
|
255
259
|
return body.input.some(item => trustedMarkerInInputItem(item, trustedCheckpoints) !== undefined)
|
|
256
260
|
}
|
|
257
261
|
|
|
262
|
+
function withEncryptedReasoningInclude(include: unknown): unknown[] {
|
|
263
|
+
if (!Array.isArray(include)) return ['reasoning.encrypted_content']
|
|
264
|
+
return include.includes('reasoning.encrypted_content')
|
|
265
|
+
? include
|
|
266
|
+
: [...include, 'reasoning.encrypted_content']
|
|
267
|
+
}
|
|
268
|
+
|
|
258
269
|
export function applyRequestWireOptions(body: JsonObject, options: CodexRequestWireOptions): JsonObject {
|
|
259
|
-
|
|
260
|
-
|
|
270
|
+
let next = body
|
|
271
|
+
if (options.serviceTier !== undefined && isGptModel(next.model) && next.service_tier === undefined) {
|
|
272
|
+
next = { ...next, service_tier: options.serviceTier }
|
|
273
|
+
}
|
|
274
|
+
if (options.reasoningMode === 'pro' && supportsApiProMode(next.model)) {
|
|
275
|
+
const existing = typeof next.reasoning === 'object' && next.reasoning !== null && !Array.isArray(next.reasoning)
|
|
276
|
+
? next.reasoning as JsonObject
|
|
277
|
+
: undefined
|
|
278
|
+
if (existing?.mode === undefined) {
|
|
279
|
+
const reasoning: JsonObject = {
|
|
280
|
+
...existing,
|
|
281
|
+
mode: 'pro',
|
|
282
|
+
...(existing?.summary === undefined ? { summary: 'auto' } : {}),
|
|
283
|
+
}
|
|
284
|
+
next = {
|
|
285
|
+
...next,
|
|
286
|
+
reasoning,
|
|
287
|
+
include: withEncryptedReasoningInclude(next.include),
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return next
|
|
261
292
|
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/** Opt-in global `codex_subagent` tool backed by Codex Connect (`openai-codex`) + DSH `spawn`. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import { ReasoningEffortId } from '@deepseek-ai/dsh-llm'
|
|
5
|
+
import type {} from '@deepseek-ai/dsh-llm'
|
|
6
|
+
import type { SubagentProvider } from '@deepseek-ai/dsh-subagent'
|
|
7
|
+
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
8
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
9
|
+
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
|
10
|
+
import { CODEX_SETTINGS_NAMESPACE } from '../contracts/settings.ts'
|
|
11
|
+
import type { CodexSettings } from '../contracts/settings.ts'
|
|
12
|
+
import {
|
|
13
|
+
CODEX_SUBAGENT_DEFAULT_PRESET,
|
|
14
|
+
CODEX_SUBAGENT_PRESET_INHERIT,
|
|
15
|
+
CODEX_SUBAGENT_TOOL_NAME,
|
|
16
|
+
OPENAI_CODEX_PROVIDER,
|
|
17
|
+
} from '../contracts/ui-contracts.ts'
|
|
18
|
+
import type { CodexSubagentModelCatalog, CodexSubagentModelOption } from '../contracts/ui-contracts.ts'
|
|
19
|
+
|
|
20
|
+
export {
|
|
21
|
+
CODEX_SUBAGENT_DEFAULT_PRESET,
|
|
22
|
+
CODEX_SUBAGENT_PRESET_INHERIT,
|
|
23
|
+
CODEX_SUBAGENT_TOOL_NAME,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const SPAWN_PROVIDER = 'spawn'
|
|
27
|
+
|
|
28
|
+
function delegationDepthOf(agent: { options?: { subagentDepth?: number }; session?: { header?: { delegationDepth?: number } } }): number {
|
|
29
|
+
const runtime = agent.options?.subagentDepth ?? 0
|
|
30
|
+
const persisted = agent.session?.header?.delegationDepth ?? 0
|
|
31
|
+
return Math.max(persisted, runtime)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface AgentPresetsResolver {
|
|
35
|
+
resolve?(id: string): Promise<{ readonly id: string; readonly broken?: string }>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface SubscribablePreferences {
|
|
39
|
+
subscribe?(listener: () => void): () => void
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function hasOpenAICodexProvider(ctx: Context): boolean {
|
|
43
|
+
const llm = ctx.get('llm')
|
|
44
|
+
if (llm === undefined || typeof llm.listProviders !== 'function') return false
|
|
45
|
+
try {
|
|
46
|
+
return llm.listProviders().some(provider => provider.id === OPENAI_CODEX_PROVIDER)
|
|
47
|
+
} catch {
|
|
48
|
+
return false
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Query live `openai-codex` models and advertised reasoning efforts from the Host LLM registry. */
|
|
53
|
+
export async function readCodexSubagentModels(ctx: Context): Promise<CodexSubagentModelCatalog> {
|
|
54
|
+
const llm = ctx.get('llm')
|
|
55
|
+
if (llm === undefined || !hasOpenAICodexProvider(ctx) || typeof llm.listModels !== 'function') {
|
|
56
|
+
return { available: false, models: [] }
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const listed = await llm.listModels(OPENAI_CODEX_PROVIDER)
|
|
60
|
+
const models: CodexSubagentModelOption[] = await Promise.all(listed.map(async model => {
|
|
61
|
+
let efforts: string[] = []
|
|
62
|
+
let defaultEffort: string | undefined
|
|
63
|
+
if (typeof llm.resolveModelInfo === 'function') {
|
|
64
|
+
try {
|
|
65
|
+
const resolved = await llm.resolveModelInfo(OPENAI_CODEX_PROVIDER, model.id)
|
|
66
|
+
efforts = (resolved.reasoning?.efforts ?? []).map(effort => effort.id)
|
|
67
|
+
defaultEffort = resolved.reasoning?.defaultEffort
|
|
68
|
+
} catch {}
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
id: model.id,
|
|
72
|
+
name: model.name || model.id,
|
|
73
|
+
efforts,
|
|
74
|
+
...(defaultEffort !== undefined ? { defaultEffort } : {}),
|
|
75
|
+
}
|
|
76
|
+
}))
|
|
77
|
+
return { available: true, models }
|
|
78
|
+
} catch {
|
|
79
|
+
return { available: true, models: [] }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function resolveChildPreset(
|
|
84
|
+
ctx: Context,
|
|
85
|
+
spawnProvider: SubagentProvider,
|
|
86
|
+
configured: string | undefined,
|
|
87
|
+
): Promise<string | undefined> {
|
|
88
|
+
const trimmed = configured?.trim()
|
|
89
|
+
if (trimmed === CODEX_SUBAGENT_PRESET_INHERIT) return undefined
|
|
90
|
+
const target = trimmed && trimmed.length > 0 ? trimmed : CODEX_SUBAGENT_DEFAULT_PRESET
|
|
91
|
+
if (!spawnProvider.capabilities.agentPreset || spawnProvider.inheritsParentContext) return undefined
|
|
92
|
+
const presets = ctx.get('agentPresets') as AgentPresetsResolver | undefined
|
|
93
|
+
if (presets === undefined || typeof presets.resolve !== 'function') return undefined
|
|
94
|
+
try {
|
|
95
|
+
const resolved = await presets.resolve(target)
|
|
96
|
+
return resolved.broken === undefined ? resolved.id : undefined
|
|
97
|
+
} catch {
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function buildCodexSubagentTool(
|
|
103
|
+
ctx: Context,
|
|
104
|
+
currentSettings: () => CodexSettings,
|
|
105
|
+
): ToolDefinition {
|
|
106
|
+
return defineTool({
|
|
107
|
+
name: CODEX_SUBAGENT_TOOL_NAME,
|
|
108
|
+
description: 'Delegate a self-contained task to an isolated subagent powered by the configured Codex subscription model (openai-codex), running in its own context without consuming this conversation\'s context or main-model API quota. Starts the subagent immediately and returns its name; when it finishes, the runtime delivers its completion notice automatically. Use `send_message` to steer it while running or continue it afterward.',
|
|
109
|
+
parameters: {
|
|
110
|
+
cwd: {
|
|
111
|
+
type: 'string',
|
|
112
|
+
description: 'Initial child working directory. Relative paths use your current directory; omitted inherits it.',
|
|
113
|
+
},
|
|
114
|
+
description: {
|
|
115
|
+
type: 'string',
|
|
116
|
+
required: true,
|
|
117
|
+
description: 'A short (3-5 word) description of the delegated task, for display. Use the language of the user\'s current request.',
|
|
118
|
+
},
|
|
119
|
+
name: {
|
|
120
|
+
type: 'string',
|
|
121
|
+
description: 'Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent.',
|
|
122
|
+
},
|
|
123
|
+
prompt: {
|
|
124
|
+
type: 'string',
|
|
125
|
+
required: true,
|
|
126
|
+
description: 'The complete, self-contained task for the subagent. It does not share this conversation\'s context, so include everything it needs.',
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
output: {
|
|
130
|
+
schema: {
|
|
131
|
+
type: 'object',
|
|
132
|
+
additionalProperties: false,
|
|
133
|
+
properties: {
|
|
134
|
+
kind: { type: 'string', required: true, const: 'activation' },
|
|
135
|
+
name: { type: 'string', required: true },
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
render: (_args, value) => [{
|
|
139
|
+
type: 'text',
|
|
140
|
+
text: `started subagent ${value.name}`,
|
|
141
|
+
}],
|
|
142
|
+
presentationMeta: (_args, value) => ({
|
|
143
|
+
kind: value.kind,
|
|
144
|
+
name: value.name,
|
|
145
|
+
}),
|
|
146
|
+
},
|
|
147
|
+
isConcurrencySafe: () => true,
|
|
148
|
+
async execute(args, exec) {
|
|
149
|
+
const parent = exec.agent
|
|
150
|
+
if (parent === undefined) {
|
|
151
|
+
throw new Error('codex_subagent requires a calling agent (exec.agent was undefined)')
|
|
152
|
+
}
|
|
153
|
+
const subagents = ctx.get('subagents')
|
|
154
|
+
const spawnProvider = subagents?.getProvider(SPAWN_PROVIDER)
|
|
155
|
+
if (subagents === undefined || spawnProvider === undefined) {
|
|
156
|
+
throw new Error('codex_subagent requires the native `spawn` subagent provider')
|
|
157
|
+
}
|
|
158
|
+
const llm = ctx.get('llm')
|
|
159
|
+
if (llm === undefined || !hasOpenAICodexProvider(ctx)) {
|
|
160
|
+
throw new Error('codex_subagent requires Codex Connect (openai-codex) to be enabled')
|
|
161
|
+
}
|
|
162
|
+
const settings = currentSettings()
|
|
163
|
+
let model = settings.codexSubagentModel?.trim() || ''
|
|
164
|
+
if (model.length === 0) {
|
|
165
|
+
const available = await llm.listModels(OPENAI_CODEX_PROVIDER)
|
|
166
|
+
exec.signal.throwIfAborted()
|
|
167
|
+
model = available[0]?.id ?? ''
|
|
168
|
+
if (model.length === 0) {
|
|
169
|
+
throw new Error('codex_subagent has no enabled openai-codex models available')
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const effortText = settings.codexSubagentEffort?.trim() || ''
|
|
173
|
+
const reasoningEffort = effortText.length > 0 ? ReasoningEffortId(effortText) : undefined
|
|
174
|
+
await llm.resolveCallConfig({
|
|
175
|
+
provider: OPENAI_CODEX_PROVIDER,
|
|
176
|
+
model,
|
|
177
|
+
...(reasoningEffort === undefined ? {} : { reasoningEffort }),
|
|
178
|
+
}, exec.signal)
|
|
179
|
+
exec.signal.throwIfAborted()
|
|
180
|
+
if (subagents.getProvider(SPAWN_PROVIDER) !== spawnProvider) {
|
|
181
|
+
throw new Error('subagent provider "spawn" changed while resolving codex_subagent; retry the delegation')
|
|
182
|
+
}
|
|
183
|
+
const agentPreset = await resolveChildPreset(ctx, spawnProvider, settings.codexSubagentPreset)
|
|
184
|
+
exec.signal.throwIfAborted()
|
|
185
|
+
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
186
|
+
const activation = await subagents.startActivation({
|
|
187
|
+
provider: SPAWN_PROVIDER,
|
|
188
|
+
label: args.description,
|
|
189
|
+
...(args.name === undefined ? {} : { name: args.name }),
|
|
190
|
+
...(args.cwd === undefined ? {} : { cwd: args.cwd }),
|
|
191
|
+
prompt: [{ type: 'text', text: args.prompt }],
|
|
192
|
+
parent,
|
|
193
|
+
...(agentPreset === undefined ? {} : { agentPreset }),
|
|
194
|
+
agentOptions: {
|
|
195
|
+
provider: OPENAI_CODEX_PROVIDER,
|
|
196
|
+
model,
|
|
197
|
+
...(reasoningEffort === undefined ? {} : { reasoningEffort }),
|
|
198
|
+
},
|
|
199
|
+
...(maxDepth === undefined ? {} : { maxDepth }),
|
|
200
|
+
signal: exec.signal,
|
|
201
|
+
delivery: 'parent',
|
|
202
|
+
})
|
|
203
|
+
return { kind: 'activation' as const, name: activation.name }
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Mount a reactive global registration controller for `codex_subagent`.
|
|
210
|
+
* Registers immediately when enabled + `spawn` + `openai-codex` are ready, and unregisters on disable.
|
|
211
|
+
*/
|
|
212
|
+
export function installCodexSubagent(ctx: Context, currentSettings: () => CodexSettings): void {
|
|
213
|
+
if (typeof (ctx as unknown as { inject?: unknown }).inject !== 'function') return
|
|
214
|
+
ctx.inject(['subagents', 'tools'], subagentCtx => {
|
|
215
|
+
let mounted: { definition: ToolDefinition; dispose: () => void } | undefined
|
|
216
|
+
let stopped = false
|
|
217
|
+
|
|
218
|
+
const unmount = (): void => {
|
|
219
|
+
if (mounted === undefined) return
|
|
220
|
+
const current = mounted
|
|
221
|
+
mounted = undefined
|
|
222
|
+
try { current.dispose() } catch {}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const reconcile = (): void => {
|
|
226
|
+
if (stopped) return
|
|
227
|
+
const settings = currentSettings()
|
|
228
|
+
const ready = settings.codexSubagentEnabled === true
|
|
229
|
+
&& subagentCtx.subagents.getProvider(SPAWN_PROVIDER) !== undefined
|
|
230
|
+
&& hasOpenAICodexProvider(subagentCtx)
|
|
231
|
+
if (!ready) {
|
|
232
|
+
unmount()
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
if (mounted !== undefined) return
|
|
236
|
+
try {
|
|
237
|
+
const definition = buildCodexSubagentTool(subagentCtx, currentSettings)
|
|
238
|
+
const dispose = subagentCtx.tools.register(definition)
|
|
239
|
+
mounted = { definition, dispose }
|
|
240
|
+
} catch (error) {
|
|
241
|
+
subagentCtx.logger.warn(`codex: could not register global ${CODEX_SUBAGENT_TOOL_NAME} tool`)
|
|
242
|
+
subagentCtx.logger.warn(error)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
subagentCtx.on('subagent/provider-added', provider => {
|
|
247
|
+
if (provider.name === SPAWN_PROVIDER) reconcile()
|
|
248
|
+
})
|
|
249
|
+
subagentCtx.on('subagent/provider-removed', providerName => {
|
|
250
|
+
if (providerName === SPAWN_PROVIDER) reconcile()
|
|
251
|
+
})
|
|
252
|
+
;(subagentCtx as unknown as { on?: (event: string, listener: (...args: any[]) => void) => void }).on?.('llm/adapters-updated', () => {
|
|
253
|
+
reconcile()
|
|
254
|
+
})
|
|
255
|
+
subagentCtx.on('settings/document-updated', ns => {
|
|
256
|
+
if (ns === CODEX_SETTINGS_NAMESPACE) reconcile()
|
|
257
|
+
})
|
|
258
|
+
subagentCtx.inject(['codexPreferences'], prefCtx => {
|
|
259
|
+
const preferences = prefCtx.get('codexPreferences') as SubscribablePreferences | undefined
|
|
260
|
+
if (typeof preferences?.subscribe !== 'function') return
|
|
261
|
+
const unsubscribe = preferences.subscribe(() => reconcile())
|
|
262
|
+
prefCtx.effect(() => unsubscribe, 'codex: codex_subagent preferences listener')
|
|
263
|
+
reconcile()
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
const systemPrompt = subagentCtx.get('systemPrompt')
|
|
267
|
+
if (systemPrompt !== undefined) {
|
|
268
|
+
systemPrompt.context({
|
|
269
|
+
name: `tool:${CODEX_SUBAGENT_TOOL_NAME}:depth`,
|
|
270
|
+
order: systemPrompt.getContextOrder('SUBAGENT_DELEGATION'),
|
|
271
|
+
text: context => {
|
|
272
|
+
if (context.agent === undefined || mounted === undefined) return ''
|
|
273
|
+
if (subagentCtx.tools.get(CODEX_SUBAGENT_TOOL_NAME, context.scope) !== mounted.definition) return ''
|
|
274
|
+
const maxDepth = subagentCtx.subagents.resolveMaxDepth(undefined)
|
|
275
|
+
if (maxDepth === undefined) return ''
|
|
276
|
+
const depth = delegationDepthOf(context.agent)
|
|
277
|
+
if (depth < maxDepth) return ''
|
|
278
|
+
return `Delegation depth for \`${CODEX_SUBAGENT_TOOL_NAME}\`: current ${depth}, maximum ${maxDepth}, remaining levels 0. Do not call \`${CODEX_SUBAGENT_TOOL_NAME}\` at this depth; carry out the work directly.`
|
|
279
|
+
},
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
subagentCtx.effect(() => () => {
|
|
284
|
+
stopped = true
|
|
285
|
+
unmount()
|
|
286
|
+
}, 'codex: global codex_subagent lifecycle')
|
|
287
|
+
|
|
288
|
+
reconcile()
|
|
289
|
+
})
|
|
290
|
+
}
|