@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1
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 +121 -0
- package/README.md +48 -38
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +150 -6
- package/docs/preset-library.md +39 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +144 -0
- package/lib/client.js +1639 -111
- package/lib/compaction.js +17 -2
- package/lib/index.js +799 -188
- package/lib/installer.js +50 -6
- package/lib/preferences.js +111 -0
- package/lib/tool-policy.js +2235 -0
- package/lib/typert.js +57 -10
- package/lib/types/activity.d.ts +1 -1
- package/lib/types/activity.js +50 -14
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/desktop.d.ts +43 -0
- package/lib/types/client/desktop.js +121 -0
- package/lib/types/client/entry.d.ts +10 -0
- package/lib/types/client/entry.js +12 -0
- package/lib/types/client/index.d.ts +109 -19
- package/lib/types/client/index.js +21 -40
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/preset-copy.d.ts +1 -0
- package/lib/types/client/preset-copy.js +2 -0
- package/lib/types/client/preset-manager.d.ts +12 -2
- package/lib/types/client/preset-manager.js +70 -25
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/session.d.ts +6 -0
- package/lib/types/client/session.js +9 -0
- package/lib/types/client/tool-policy.d.ts +120 -0
- package/lib/types/client/tool-policy.js +394 -0
- package/lib/types/compaction.d.ts +3 -3
- package/lib/types/compaction.js +6 -2
- package/lib/types/desktop-preset.d.ts +20 -0
- package/lib/types/desktop-preset.js +39 -0
- package/lib/types/exec.d.ts +4 -0
- package/lib/types/exec.js +192 -66
- package/lib/types/host-settings.d.ts +4 -0
- package/lib/types/host-settings.js +13 -0
- package/lib/types/index.d.ts +20 -2
- package/lib/types/index.js +181 -68
- package/lib/types/installer.js +11 -2
- package/lib/types/preferences.d.ts +11 -0
- package/lib/types/preferences.js +16 -0
- package/lib/types/preset-editor-remote.d.ts +2 -0
- package/lib/types/preset-editor-remote.js +6 -2
- package/lib/types/preset-editor.d.ts +12 -7
- package/lib/types/preset-editor.js +43 -13
- package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
- package/lib/types/preset-prompt-catalog-schema.js +11 -0
- package/lib/types/preset-prompt-catalog.d.ts +21 -0
- package/lib/types/preset-prompt-catalog.js +192 -0
- package/lib/types/preset-prompt-contract.d.ts +22 -0
- package/lib/types/preset-prompt-contract.js +3 -0
- package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
- package/lib/types/preset-tool-catalog-schema.js +28 -0
- package/lib/types/preset-tool-catalog.d.ts +5 -0
- package/lib/types/preset-tool-catalog.js +51 -0
- package/lib/types/prompt-sections.d.ts +1 -1
- package/lib/types/prompt-sections.js +9 -3
- package/lib/types/prompt.js +4 -2
- package/lib/types/remote.js +23 -8
- package/lib/types/settings.d.ts +3 -3
- package/lib/types/settings.js +3 -3
- package/lib/types/tool-capabilities.d.ts +32 -0
- package/lib/types/tool-capabilities.js +42 -0
- package/lib/types/tool-policy-contract.d.ts +60 -0
- package/lib/types/tool-policy-contract.js +26 -0
- package/lib/types/tool-policy.d.ts +171 -0
- package/lib/types/tool-policy.js +367 -0
- package/lib/types/typert.host.d.ts +2 -2
- package/lib/types/typert.host.js +12 -2
- package/locale/en.json +6 -0
- package/locale/tool-policy/en.json +6 -0
- package/locale/tool-policy/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +375 -299
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/activity-types.ts +7 -0
- package/src/activity.ts +158 -0
- package/src/client/activity.ts +82 -0
- package/src/client/desktop.tsx +162 -0
- package/src/client/entry.tsx +16 -0
- package/src/client/index.tsx +972 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/preset-copy.ts +83 -0
- package/src/client/preset-manager.tsx +281 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/session.ts +11 -0
- package/src/client/tool-policy.tsx +380 -0
- package/src/compact-command.ts +112 -0
- package/src/compaction.ts +190 -0
- package/src/context.ts +15 -0
- package/src/desktop-preset.ts +55 -0
- package/src/exec.ts +570 -0
- package/src/host-settings.ts +17 -0
- package/src/index.ts +1097 -0
- package/src/installer.ts +172 -0
- package/src/invariant.ts +34 -0
- package/src/patch.ts +258 -0
- package/src/preferences.ts +17 -0
- package/src/preset-contract.ts +85 -0
- package/src/preset-editor-remote.ts +41 -0
- package/src/preset-editor.ts +502 -0
- package/src/preset-prompt-catalog-schema.ts +10 -0
- package/src/preset-prompt-catalog.ts +191 -0
- package/src/preset-prompt-contract.ts +21 -0
- package/src/preset-tool-catalog-schema.ts +28 -0
- package/src/preset-tool-catalog.ts +51 -0
- package/src/prompt-sections.ts +33 -0
- package/src/prompt.ts +62 -0
- package/src/remote.ts +748 -0
- package/src/settings.ts +79 -0
- package/src/tool-capabilities.ts +76 -0
- package/src/tool-policy-contract.ts +76 -0
- package/src/tool-policy.ts +388 -0
- package/src/typert.host.ts +119 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
package/src/index.ts
ADDED
|
@@ -0,0 +1,1097 @@
|
|
|
1
|
+
/** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
5
|
+
import z from '@deepseek-ai/schemastery'
|
|
6
|
+
import type {} from '@deepseek-ai/dsh-settings'
|
|
7
|
+
import type {} from '@deepseek-ai/dsh-llm'
|
|
8
|
+
import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
|
|
9
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
10
|
+
import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
|
|
11
|
+
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
12
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
13
|
+
import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools'
|
|
14
|
+
import type { FsInfo, FsTarget, FsWriteIntent } from '@deepseek-ai/dsh-fs'
|
|
15
|
+
import type {} from '@deepseek-ai/dsh-fs'
|
|
16
|
+
import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox'
|
|
17
|
+
import { ESCALATION_TARGETS, sandboxPermissionsDescription } from '@deepseek-ai/dsh-sandbox'
|
|
18
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
19
|
+
import type { TodoItem } from '@deepseek-ai/dsh-tool-todo'
|
|
20
|
+
import type {} from '@deepseek-ai/dsh-shell'
|
|
21
|
+
import type {} from '@deepseek-ai/dsh-shell-env'
|
|
22
|
+
import type {} from '@deepseek-ai/dsh-terminal'
|
|
23
|
+
import { APPLY_PATCH_DESCRIPTION, applyPatchHunks, parsePatch } from './patch.ts'
|
|
24
|
+
import type { PatchFile } from './patch.ts'
|
|
25
|
+
import { renderExecResult, runExecCommand, runWriteStdin, supportsLegacyShellOptions } from './exec.ts'
|
|
26
|
+
import type { ExecCommandArgs, ExecResult, WriteStdinArgs } from './exec.ts'
|
|
27
|
+
import {
|
|
28
|
+
hostedWebSearchStream,
|
|
29
|
+
installHostedWebSearch,
|
|
30
|
+
remoteCompactStream,
|
|
31
|
+
repairLegacyPiAiContextOverflow,
|
|
32
|
+
} from './remote.ts'
|
|
33
|
+
import { registerCodexActivityProjection } from './activity.ts'
|
|
34
|
+
import {
|
|
35
|
+
DEFAULT_CODEX_PERSONA,
|
|
36
|
+
DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
37
|
+
DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
38
|
+
DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
39
|
+
resolveCodexSystemPrompt,
|
|
40
|
+
} from './prompt.ts'
|
|
41
|
+
import {
|
|
42
|
+
CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA,
|
|
43
|
+
} from './settings.ts'
|
|
44
|
+
import type { CodexSettings } from './settings.ts'
|
|
45
|
+
import { codexCompactionMode } from './compaction.ts'
|
|
46
|
+
import { CodexPresetEditor } from './preset-editor.ts'
|
|
47
|
+
import { applyPromptSections, Config as PromptSectionsConfig } from './prompt-sections.ts'
|
|
48
|
+
import { readHostSettings } from './host-settings.ts'
|
|
49
|
+
import { codexToolEnabled, markCodexTool, hasPresetPromptOverride } from './tool-capabilities.ts'
|
|
50
|
+
import type { CodexCapability, CodexToolMetadata } from './tool-policy-contract.ts'
|
|
51
|
+
|
|
52
|
+
export {
|
|
53
|
+
DEFAULT_CODEX_PERSONA,
|
|
54
|
+
DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
55
|
+
DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
56
|
+
DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
57
|
+
} from './prompt.ts'
|
|
58
|
+
export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA } from './settings.ts'
|
|
59
|
+
export type { CodexSettings } from './settings.ts'
|
|
60
|
+
|
|
61
|
+
export const name = 'codex'
|
|
62
|
+
export const inject = ['tools', 'systemPrompt', 'shell', 'fs', 'llm', 'credentials', 'settings']
|
|
63
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024
|
|
64
|
+
|
|
65
|
+
/** Add the preset editor when DSH's optional user-preset service is available. */
|
|
66
|
+
function installPresetEditor(ctx: Context): void {
|
|
67
|
+
// `agentPresets` is supplied by dsh-agent-presets and may be installed after
|
|
68
|
+
// this plugin. Waiting through inject keeps the Codex core usable on hosts
|
|
69
|
+
// without that optional service while still mounting the Remote as soon as
|
|
70
|
+
// the Web preset catalog becomes available.
|
|
71
|
+
ctx.inject(['agentPresets'], presetCtx => {
|
|
72
|
+
void (async () => {
|
|
73
|
+
try {
|
|
74
|
+
await presetCtx.plugin(CodexPresetEditor)
|
|
75
|
+
} catch (error) {
|
|
76
|
+
ctx.logger.warn('codex: preset editor is unavailable on this host')
|
|
77
|
+
ctx.logger.warn(error)
|
|
78
|
+
}
|
|
79
|
+
})()
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Configuration for the Codex shell result bridge. */
|
|
84
|
+
export interface Config {
|
|
85
|
+
/** Install request/transport/activity enhancements for every agent scope. */
|
|
86
|
+
globalEnhancements?: boolean
|
|
87
|
+
/** Install the Codex operating prompt and four core tools in this scope. */
|
|
88
|
+
codexCore?: boolean
|
|
89
|
+
/** Default wait before a pipe-backed command yields a session id. */
|
|
90
|
+
defaultYieldTimeMs?: number
|
|
91
|
+
/** Default wait for an empty `write_stdin` poll. */
|
|
92
|
+
pollYieldTimeMs?: number
|
|
93
|
+
/** Default wait for a non-empty `write_stdin` send. */
|
|
94
|
+
writeYieldTimeMs?: number
|
|
95
|
+
/** Maximum output retained in one canonical result, in UTF-8 bytes. */
|
|
96
|
+
maxOutputBytes?: number
|
|
97
|
+
/** Send GPT Responses requests with the native hosted web_search tool first. */
|
|
98
|
+
hostedWebSearch?: boolean
|
|
99
|
+
/** Use the provider's /responses/compact endpoint before local compaction. */
|
|
100
|
+
remoteCompact?: boolean
|
|
101
|
+
/** Complete plugin-owned Codex operating prompt. */
|
|
102
|
+
systemPrompt?: string
|
|
103
|
+
/** Explicit per-preset operating prompt; overrides the shared prompt only. */
|
|
104
|
+
presetPrompt?: string
|
|
105
|
+
presetSections?: import('./prompt-sections.ts').Config
|
|
106
|
+
/** Per-preset Codex capability overrides. Omitted values follow shared settings. */
|
|
107
|
+
promptEnabled?: boolean
|
|
108
|
+
terminalToolsEnabled?: boolean
|
|
109
|
+
patchToolEnabled?: boolean
|
|
110
|
+
planToolEnabled?: boolean
|
|
111
|
+
hostedWebSearchEnabled?: boolean
|
|
112
|
+
remoteCompactionEnabled?: boolean
|
|
113
|
+
/** Deployment Persona template. */
|
|
114
|
+
persona?: string
|
|
115
|
+
/** DSH Core source-checkout guidance template. */
|
|
116
|
+
harnessSourcePrompt?: string
|
|
117
|
+
/** DSH Core Web GUI guidance template. */
|
|
118
|
+
webSurfacePrompt?: string
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Runtime configuration schema for the Codex tool bridge. */
|
|
122
|
+
export const Config: z<Config> = z.object({
|
|
123
|
+
globalEnhancements: z.boolean().default(true),
|
|
124
|
+
codexCore: z.boolean().default(true),
|
|
125
|
+
defaultYieldTimeMs: z.number().step(1).min(0).default(10_000),
|
|
126
|
+
pollYieldTimeMs: z.number().step(1).min(0).default(5_000),
|
|
127
|
+
writeYieldTimeMs: z.number().step(1).min(0).default(250),
|
|
128
|
+
maxOutputBytes: z.number().step(1).min(1).default(DEFAULT_MAX_OUTPUT_BYTES),
|
|
129
|
+
hostedWebSearch: z.boolean().default(true),
|
|
130
|
+
remoteCompact: z.boolean().default(true),
|
|
131
|
+
systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
|
|
132
|
+
presetPrompt: z.string(),
|
|
133
|
+
presetSections: PromptSectionsConfig,
|
|
134
|
+
promptEnabled: z.boolean(),
|
|
135
|
+
terminalToolsEnabled: z.boolean(),
|
|
136
|
+
patchToolEnabled: z.boolean(),
|
|
137
|
+
planToolEnabled: z.boolean(),
|
|
138
|
+
hostedWebSearchEnabled: z.boolean(),
|
|
139
|
+
remoteCompactionEnabled: z.boolean(),
|
|
140
|
+
persona: z.string().default(DEFAULT_CODEX_PERSONA),
|
|
141
|
+
harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
142
|
+
webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
const LLM_PI_AI_SETTINGS = 'llm-pi-ai' as const
|
|
146
|
+
|
|
147
|
+
/** Codex request envelope with the plugin's provider-facing service-tier field. */
|
|
148
|
+
export interface CodexRequestConfig extends LlmCallConfig {
|
|
149
|
+
/** Codex request context capacity override, retained for older DSH hosts. */
|
|
150
|
+
contextWindow?: number
|
|
151
|
+
/** Provider-facing service tier, for example Responses `priority`. */
|
|
152
|
+
serviceTier?: string
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const GPT_REASONING_EFFORTS = {
|
|
156
|
+
low: 'low',
|
|
157
|
+
medium: 'medium',
|
|
158
|
+
high: 'high',
|
|
159
|
+
xhigh: 'xhigh',
|
|
160
|
+
max: 'max',
|
|
161
|
+
} as const
|
|
162
|
+
|
|
163
|
+
type CodexReasoningEfforts = false | Record<string, string | null>
|
|
164
|
+
|
|
165
|
+
function codexReasoningEfforts(configured: CodexReasoningEfforts | undefined): CodexReasoningEfforts {
|
|
166
|
+
if (configured === false) return false
|
|
167
|
+
const filtered = configured === undefined
|
|
168
|
+
? {}
|
|
169
|
+
: Object.fromEntries(Object.entries(configured).filter(([level]) => level !== 'off' && level !== 'minimal'))
|
|
170
|
+
return Object.keys(filtered).length === 0 ? GPT_REASONING_EFFORTS : filtered
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export interface CodexModelProfile {
|
|
174
|
+
id: string
|
|
175
|
+
input?: string[]
|
|
176
|
+
reasoningEfforts?: false | Record<string, string | null>
|
|
177
|
+
[key: string]: unknown
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
interface CodexModelOverride {
|
|
181
|
+
input?: string[]
|
|
182
|
+
reasoningEfforts?: false | Record<string, string | null>
|
|
183
|
+
[key: string]: unknown
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface CodexProviderProfile {
|
|
187
|
+
models?: CodexModelProfile[]
|
|
188
|
+
modelOverrides?: Record<string, CodexModelOverride>
|
|
189
|
+
[key: string]: unknown
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** GPT model ids are the only models whose relay capabilities Codex fills in. */
|
|
193
|
+
function isGptModel(id: string): boolean {
|
|
194
|
+
return /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(id)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Add Codex defaults without overwriting explicit user capabilities. */
|
|
198
|
+
export function enrichCodexModel(model: CodexModelProfile): CodexModelProfile {
|
|
199
|
+
if (!isGptModel(model.id)) return model
|
|
200
|
+
const input = model.input === undefined || model.input.length === 0
|
|
201
|
+
? ['text', 'image']
|
|
202
|
+
: model.input
|
|
203
|
+
const efforts = codexReasoningEfforts(model.reasoningEfforts)
|
|
204
|
+
if (input === model.input && efforts === model.reasoningEfforts) return model
|
|
205
|
+
return { ...model, input, reasoningEfforts: efforts }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The settings schema keys modelOverrides by id, so its values must not carry an id field. */
|
|
209
|
+
function enrichCodexOverride(id: string, model: CodexModelOverride): CodexModelOverride {
|
|
210
|
+
if (!isGptModel(id)) return model
|
|
211
|
+
const enriched = enrichCodexModel({ ...model, id })
|
|
212
|
+
const { id: _id, ...withoutId } = enriched
|
|
213
|
+
const inputMissing = model.input === undefined || model.input.length === 0
|
|
214
|
+
const nextEfforts = codexReasoningEfforts(model.reasoningEfforts)
|
|
215
|
+
const reasoningChanged = JSON.stringify(nextEfforts) !== JSON.stringify(model.reasoningEfforts)
|
|
216
|
+
if (!inputMissing && !reasoningChanged) return model
|
|
217
|
+
return { ...withoutId, reasoningEfforts: nextEfforts }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
interface LlmPiAiSettings {
|
|
221
|
+
providers?: Record<string, CodexProviderProfile>
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Persist only missing GPT capabilities into the user's existing pi-ai model config. */
|
|
225
|
+
async function enrichConfiguredGptModels(ctx: Context): Promise<void> {
|
|
226
|
+
const settings = ctx.get('settings') as { get(ns: unknown): unknown; update(ns: unknown, patch: object): Promise<void> } | undefined
|
|
227
|
+
if (settings === undefined) return
|
|
228
|
+
const current = readHostSettings<LlmPiAiSettings>(ctx, LLM_PI_AI_SETTINGS)
|
|
229
|
+
if (current?.providers === undefined) return
|
|
230
|
+
const providers: Record<string, Record<string, unknown>> = {}
|
|
231
|
+
let changed = false
|
|
232
|
+
for (const [provider, profile] of Object.entries(current.providers)) {
|
|
233
|
+
const models = profile.models
|
|
234
|
+
const overrides = profile.modelOverrides
|
|
235
|
+
const nextModels = Array.isArray(models) ? models.map(enrichCodexModel) : undefined
|
|
236
|
+
const nextOverrides = overrides === undefined
|
|
237
|
+
? undefined
|
|
238
|
+
: Object.fromEntries(Object.entries(overrides).map(([id, model]) => [id, enrichCodexOverride(id, model)]))
|
|
239
|
+
const modelsChanged = nextModels !== undefined && nextModels.some((model, index) => model !== models?.[index])
|
|
240
|
+
const overridesChanged = nextOverrides !== undefined
|
|
241
|
+
&& overrides !== undefined
|
|
242
|
+
&& Object.entries(nextOverrides).some(([id, model]) => model !== overrides[id])
|
|
243
|
+
if (modelsChanged || overridesChanged) {
|
|
244
|
+
changed = true
|
|
245
|
+
providers[provider] = {
|
|
246
|
+
...modelsChanged ? { models: nextModels } : {},
|
|
247
|
+
...overridesChanged ? { modelOverrides: nextOverrides } : {},
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (changed) await settings.update(LLM_PI_AI_SETTINGS, { providers })
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Keep newly edited GPT model entries enriched while Codex mode is mounted. */
|
|
255
|
+
function watchConfiguredGptModels(ctx: Context): void {
|
|
256
|
+
let tail = Promise.resolve()
|
|
257
|
+
const schedule = (): void => {
|
|
258
|
+
tail = tail.then(() => enrichConfiguredGptModels(ctx)).catch(error => {
|
|
259
|
+
ctx.logger.warn('codex: could not enrich configured GPT model capabilities')
|
|
260
|
+
ctx.logger.warn(error)
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
ctx.on('settings/document-updated', (ns) => {
|
|
264
|
+
if (ns === LLM_PI_AI_SETTINGS) schedule()
|
|
265
|
+
})
|
|
266
|
+
schedule()
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Install the optional settings source used by requests and prompt assembly. */
|
|
270
|
+
function installCodexSettings(
|
|
271
|
+
ctx: Context,
|
|
272
|
+
systemPrompt: string,
|
|
273
|
+
persona: string,
|
|
274
|
+
harnessSourcePrompt: string,
|
|
275
|
+
webSurfacePrompt: string,
|
|
276
|
+
): { current: () => CodexSettings } {
|
|
277
|
+
const entry: CodexSettings = {
|
|
278
|
+
...CODEX_SETTINGS_ENTRY,
|
|
279
|
+
systemPrompt,
|
|
280
|
+
persona,
|
|
281
|
+
harnessSourcePrompt,
|
|
282
|
+
webSurfacePrompt,
|
|
283
|
+
}
|
|
284
|
+
const withDefaults = (value: CodexSettings | undefined): CodexSettings => ({
|
|
285
|
+
...entry,
|
|
286
|
+
...value,
|
|
287
|
+
})
|
|
288
|
+
let source: () => CodexSettings = () => entry
|
|
289
|
+
let attached = false
|
|
290
|
+
const attachSettings = (candidate: unknown): boolean => {
|
|
291
|
+
if (attached || candidate === undefined || candidate === null) return attached
|
|
292
|
+
const settings = candidate as {
|
|
293
|
+
get?: (namespace: unknown) => unknown
|
|
294
|
+
installSection?: (
|
|
295
|
+
owner: Context,
|
|
296
|
+
namespace: unknown,
|
|
297
|
+
schema: unknown,
|
|
298
|
+
base: CodexSettings,
|
|
299
|
+
hooks: { setSource: (current: () => CodexSettings) => void; onChange: () => void },
|
|
300
|
+
) => void
|
|
301
|
+
register?: (
|
|
302
|
+
namespace: unknown,
|
|
303
|
+
schema: unknown,
|
|
304
|
+
options: { base: CodexSettings },
|
|
305
|
+
) => { get: () => unknown }
|
|
306
|
+
}
|
|
307
|
+
if (typeof settings.get === 'function') {
|
|
308
|
+
const get = settings.get.bind(settings)
|
|
309
|
+
if (get(CODEX_SETTINGS_NAMESPACE) !== undefined) {
|
|
310
|
+
source = () => get(CODEX_SETTINGS_NAMESPACE) as CodexSettings
|
|
311
|
+
attached = true
|
|
312
|
+
return true
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (typeof settings.installSection === 'function') {
|
|
316
|
+
settings.installSection.call(settings, ctx, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, entry, {
|
|
317
|
+
setSource: (current) => { source = current },
|
|
318
|
+
onChange: () => {},
|
|
319
|
+
})
|
|
320
|
+
attached = true
|
|
321
|
+
return true
|
|
322
|
+
}
|
|
323
|
+
if (typeof settings.register === 'function') {
|
|
324
|
+
const scope = settings.register.call(settings, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, { base: entry })
|
|
325
|
+
source = () => scope.get() as CodexSettings
|
|
326
|
+
attached = true
|
|
327
|
+
return true
|
|
328
|
+
}
|
|
329
|
+
return false
|
|
330
|
+
}
|
|
331
|
+
if (!attachSettings(ctx.get('settings'))) {
|
|
332
|
+
ctx.inject(['settings'], (settingsCtx) => {
|
|
333
|
+
attachSettings((settingsCtx as Context & { settings: unknown }).settings)
|
|
334
|
+
})
|
|
335
|
+
}
|
|
336
|
+
return { current: () => withDefaults(readHostSettings<CodexSettings>(ctx, CODEX_SETTINGS_NAMESPACE) ?? source()) }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// PromptPresentation replaced PromptAssembly at the presentation waterfall in DSH 0.2.2.
|
|
340
|
+
// Pick the common fields so older hosts can keep passing their complete assembly.
|
|
341
|
+
type CodexPromptPresentation = Pick<PromptAssembly, 'sections' | 'contexts' | 'variables'>
|
|
342
|
+
|
|
343
|
+
type SessionEvent = { type: string, seq: number }
|
|
344
|
+
|
|
345
|
+
/** Read the event snapshot across the pre- and post-0.1.2 DSH session APIs. */
|
|
346
|
+
function sessionEvents(session: Session): readonly SessionEvent[] {
|
|
347
|
+
const compatible = session as Session & {
|
|
348
|
+
snapshotEvents?: () => readonly SessionEvent[]
|
|
349
|
+
events?: readonly SessionEvent[]
|
|
350
|
+
}
|
|
351
|
+
if (typeof compatible.snapshotEvents === 'function') return compatible.snapshotEvents()
|
|
352
|
+
return compatible.events ?? []
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function hasOpenTurn(session: Session): boolean {
|
|
356
|
+
const events = sessionEvents(session)
|
|
357
|
+
const start = events.findLast(event => event.type === 'turn/start')
|
|
358
|
+
const end = events.findLast(event => event.type === 'turn/end')
|
|
359
|
+
return start !== undefined && (end === undefined || start.seq > end.seq)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Pair the live Codex capacity with the token-meter context projection.
|
|
364
|
+
*
|
|
365
|
+
* The core loop records adapter metadata in `request/context`, while Codex's
|
|
366
|
+
* setting is a request-scoped LLM capacity. Appending the override after the
|
|
367
|
+
* loop's metadata event keeps the official ContextMeter and compaction engine
|
|
368
|
+
* on the same effective capacity.
|
|
369
|
+
*/
|
|
370
|
+
export function syncCodexContextWindow(session: Session, contextWindow: number | undefined): void {
|
|
371
|
+
if (contextWindow === undefined
|
|
372
|
+
|| !Number.isSafeInteger(contextWindow)
|
|
373
|
+
|| contextWindow <= 0
|
|
374
|
+
|| !hasOpenTurn(session)) return
|
|
375
|
+
const config = session.requestHeader()?.config as {
|
|
376
|
+
provider?: unknown
|
|
377
|
+
model?: unknown
|
|
378
|
+
} | undefined
|
|
379
|
+
if (typeof config?.provider !== 'string'
|
|
380
|
+
|| typeof config.model !== 'string'
|
|
381
|
+
|| !isGptModel(config.model)) return
|
|
382
|
+
const current = session.requestContext()
|
|
383
|
+
if (current?.provider === config.provider
|
|
384
|
+
&& current.model === config.model
|
|
385
|
+
&& current.contextWindow === contextWindow) return
|
|
386
|
+
session.append('request/context', {
|
|
387
|
+
provider: config.provider,
|
|
388
|
+
model: config.model,
|
|
389
|
+
contextWindow,
|
|
390
|
+
// Capacity is only one field of the routed capability snapshot.
|
|
391
|
+
...current?.provider === config.provider && current.model === config.model ? {
|
|
392
|
+
...current.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: current.systemPromptUpdate },
|
|
393
|
+
} : {},
|
|
394
|
+
})
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Keep the official context meter synchronized with a live Codex override. */
|
|
398
|
+
function installCodexContextProjection(ctx: Context, current: () => CodexSettings): void {
|
|
399
|
+
const sync = (session: Session, contextWindow = current().contextWindow): void => {
|
|
400
|
+
syncCodexContextWindow(session, contextWindow)
|
|
401
|
+
}
|
|
402
|
+
const pending = new WeakSet<Session>()
|
|
403
|
+
const syncAfterPublication = (session: Session): void => {
|
|
404
|
+
if (pending.has(session)) return
|
|
405
|
+
pending.add(session)
|
|
406
|
+
queueMicrotask(() => {
|
|
407
|
+
try {
|
|
408
|
+
sync(session)
|
|
409
|
+
} finally {
|
|
410
|
+
pending.delete(session)
|
|
411
|
+
}
|
|
412
|
+
})
|
|
413
|
+
}
|
|
414
|
+
const syncAll = (contextWindow = current().contextWindow): void => {
|
|
415
|
+
const sessions = ctx.get('sessions') as { list?: () => readonly Session[] } | undefined
|
|
416
|
+
for (const session of sessions?.list?.() ?? []) sync(session, contextWindow)
|
|
417
|
+
}
|
|
418
|
+
ctx.on('session/event', (session, event) => {
|
|
419
|
+
// Session.append() rejects nested appends until every observer returns.
|
|
420
|
+
if (event.type === 'request/header' || event.type === 'request/context') syncAfterPublication(session)
|
|
421
|
+
})
|
|
422
|
+
// Restored sessions may already contain their request/header seed, so no
|
|
423
|
+
// session/event is emitted for the initial capacity. Catch them at the
|
|
424
|
+
// store publication boundary as well.
|
|
425
|
+
ctx.on('session/created', syncAfterPublication)
|
|
426
|
+
// Use the resolved value carried by the consumer-facing event. This avoids
|
|
427
|
+
// waiting for the settings source closure to refresh before synchronizing
|
|
428
|
+
// already-open sessions.
|
|
429
|
+
// Removed from the current typed Event map, but still emitted by older settings providers.
|
|
430
|
+
const legacyEvents = ctx as unknown as {
|
|
431
|
+
on(event: 'settings/updated', listener: (ns: string, value: CodexSettings) => void): unknown
|
|
432
|
+
}
|
|
433
|
+
legacyEvents.on('settings/updated', (ns, next) => {
|
|
434
|
+
if (ns === CODEX_SETTINGS_NAMESPACE) syncAll(next.contextWindow)
|
|
435
|
+
})
|
|
436
|
+
ctx.on('settings/document-updated', ns => {
|
|
437
|
+
if (ns === CODEX_SETTINGS_NAMESPACE) syncAll()
|
|
438
|
+
})
|
|
439
|
+
syncAll()
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Apply the live Codex controls to one agent request without leaking them to other routes. */
|
|
443
|
+
export function applyCodexRequestSettings(
|
|
444
|
+
request: CodexRequestConfig,
|
|
445
|
+
settings: CodexSettings,
|
|
446
|
+
): CodexRequestConfig {
|
|
447
|
+
const {
|
|
448
|
+
contextWindow: _inheritedContextWindow,
|
|
449
|
+
serviceTier: _inheritedServiceTier,
|
|
450
|
+
...withoutCodexControls
|
|
451
|
+
} = request
|
|
452
|
+
if (!isGptModel(request.model)) return withoutCodexControls
|
|
453
|
+
return {
|
|
454
|
+
...withoutCodexControls,
|
|
455
|
+
...settings.contextWindow === undefined ? {} : { contextWindow: settings.contextWindow },
|
|
456
|
+
...settings.fast ? { serviceTier: 'priority' } : {},
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Put the agent persona first and omit the generic Harness identity opener. */
|
|
461
|
+
export function normalizeCodexPromptAssembly<T extends CodexPromptPresentation>(assembly: T): T {
|
|
462
|
+
const sections = assembly.sections.filter(section => section.name !== 'harness:identity')
|
|
463
|
+
const persona = sections.find(section => section.name === 'deployment:persona-prefix')
|
|
464
|
+
?? sections.find(section => section.name === 'deployment:persona')
|
|
465
|
+
if (persona === undefined) return { ...assembly, sections }
|
|
466
|
+
return {
|
|
467
|
+
...assembly,
|
|
468
|
+
sections: [persona, ...sections.filter(section => section !== persona)],
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function sectionText(assembly: CodexPromptPresentation, name: string): string | undefined {
|
|
473
|
+
const section = assembly.sections.find(candidate => candidate.name === name)
|
|
474
|
+
return section?.text
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function promptVariables(assembly: CodexPromptPresentation): Record<string, string | undefined> {
|
|
478
|
+
const variables = { ...assembly.variables }
|
|
479
|
+
if (variables.sourceRoot === undefined) {
|
|
480
|
+
const source = sectionText(assembly, 'harness:source')
|
|
481
|
+
const match = source?.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u)
|
|
482
|
+
if (match?.[1] !== undefined) variables.sourceRoot = match[1]
|
|
483
|
+
}
|
|
484
|
+
if (variables.webUrl === undefined) {
|
|
485
|
+
const web = sectionText(assembly, 'app:web-surface')
|
|
486
|
+
const match = web?.match(/^You are interacting with the user through the DeepSeek Harness Web GUI at (.+?)\. When/u)
|
|
487
|
+
if (match?.[1] !== undefined) variables.webUrl = match[1]
|
|
488
|
+
}
|
|
489
|
+
return variables
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function interpolateCodexPrompt(text: string, variables: Record<string, string | undefined>): string {
|
|
493
|
+
return text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key: string) => variables[key] ?? whole)
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Apply user-editable Persona and DSH Core runtime prompt templates. */
|
|
497
|
+
function applyCodexPromptOverrides<T extends CodexPromptPresentation>(assembly: T, settings: CodexSettings): T {
|
|
498
|
+
const overrides: Record<string, string | undefined> = {
|
|
499
|
+
'deployment:persona': settings.persona,
|
|
500
|
+
'deployment:persona-prefix': settings.persona,
|
|
501
|
+
'harness:source': settings.harnessSourcePrompt,
|
|
502
|
+
'app:web-surface': settings.webSurfacePrompt,
|
|
503
|
+
}
|
|
504
|
+
const defaults: Record<string, string> = {
|
|
505
|
+
'deployment:persona': DEFAULT_CODEX_PERSONA,
|
|
506
|
+
'deployment:persona-prefix': DEFAULT_CODEX_PERSONA,
|
|
507
|
+
'harness:source': DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
508
|
+
'app:web-surface': DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
509
|
+
}
|
|
510
|
+
const hasCustomOverride = Object.entries(overrides).some(([name, text]) => (
|
|
511
|
+
text !== undefined && text !== defaults[name]
|
|
512
|
+
))
|
|
513
|
+
if (!hasCustomOverride) return assembly
|
|
514
|
+
const variables = promptVariables(assembly)
|
|
515
|
+
const sections = assembly.sections.map(section => {
|
|
516
|
+
const template = overrides[section.name]
|
|
517
|
+
return template === undefined || template === defaults[section.name]
|
|
518
|
+
? section
|
|
519
|
+
: { ...section, text: interpolateCodexPrompt(template, variables) }
|
|
520
|
+
})
|
|
521
|
+
return { ...assembly, sections, variables }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const CODEX_TOOL_NAMES = {
|
|
525
|
+
terminalToolsEnabled: new Set(['exec_command', 'write_stdin']),
|
|
526
|
+
patchToolEnabled: new Set(['apply_patch']),
|
|
527
|
+
planToolEnabled: new Set(['update_plan']),
|
|
528
|
+
} as const
|
|
529
|
+
|
|
530
|
+
/** Remove disabled Codex capabilities from the next model-visible assembly. */
|
|
531
|
+
export function applyCodexCapabilitySettings<T extends CodexPromptPresentation>(
|
|
532
|
+
assembly: T,
|
|
533
|
+
settings: CodexSettings,
|
|
534
|
+
): T {
|
|
535
|
+
const disabled = new Set<string>()
|
|
536
|
+
for (const [setting, names] of Object.entries(CODEX_TOOL_NAMES)) {
|
|
537
|
+
if (settings[setting as keyof typeof CODEX_TOOL_NAMES]) continue
|
|
538
|
+
for (const name of names) disabled.add(name)
|
|
539
|
+
}
|
|
540
|
+
// Legacy hosts expose tools here; current hosts own them in the tool registry
|
|
541
|
+
// and pass only presentation fields. Registration conditions below handle that path.
|
|
542
|
+
const tools = (assembly as CodexPromptPresentation & { tools?: PromptAssembly['tools'] }).tools
|
|
543
|
+
const filtered = disabled.size === 0 || tools === undefined
|
|
544
|
+
? assembly
|
|
545
|
+
: { ...assembly, tools: tools.filter(tool => !disabled.has(tool.name)) }
|
|
546
|
+
return applyCodexPresentationSettings(filtered, settings)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Current SDK declarations remain registry-owned; preferences affect presentation only. */
|
|
550
|
+
function applyCodexPresentationSettings<T extends CodexPromptPresentation>(assembly: T, settings: CodexSettings, protectedNames?: ReadonlySet<string>): T {
|
|
551
|
+
const promptSettings = { ...settings }
|
|
552
|
+
if (protectedNames?.has('deployment:persona-prefix')) delete promptSettings.persona
|
|
553
|
+
const withOverrides = applyCodexPromptOverrides(assembly, promptSettings)
|
|
554
|
+
return settings.promptEnabled ? normalizeCodexPromptAssembly(withOverrides) : withOverrides
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Build the complete plugin-owned prompt, preserving an intentional empty value. */
|
|
558
|
+
export function buildCodexSystemPrompt(config: Pick<Config, 'systemPrompt'> = {}): string {
|
|
559
|
+
return resolveCodexSystemPrompt(config.systemPrompt)
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const EXEC_COMMAND_DESCRIPTION = 'Runs a shell command. By default it uses pipes: a running session can be polled for output but does not accept stdin. Set tty=true before starting a command that needs interactive input; background jobs use pipes.'
|
|
563
|
+
const WRITE_STDIN_DESCRIPTION = 'Polls output from an existing unified exec session. Non-empty chars can be sent only to a session created with tty=true; pipe-backed sessions accept empty chars for polling only.'
|
|
564
|
+
const UPDATE_PLAN_DESCRIPTION =
|
|
565
|
+
'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.'
|
|
566
|
+
|
|
567
|
+
const PLAN_STATUSES = ['pending', 'in_progress', 'completed'] as const
|
|
568
|
+
type PlanStatus = typeof PLAN_STATUSES[number]
|
|
569
|
+
|
|
570
|
+
interface PlanArgumentItem {
|
|
571
|
+
step: string
|
|
572
|
+
status: PlanStatus
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
interface UpdatePlanArgs {
|
|
576
|
+
explanation?: string
|
|
577
|
+
plan: PlanArgumentItem[]
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
interface ExecToolConfig {
|
|
581
|
+
defaultYieldTimeMs: number
|
|
582
|
+
pollYieldTimeMs: number
|
|
583
|
+
writeYieldTimeMs: number
|
|
584
|
+
maxOutputBytes: number
|
|
585
|
+
currentSettings: () => CodexSettings
|
|
586
|
+
presetEnabled?: boolean
|
|
587
|
+
authority?: boolean
|
|
588
|
+
presetOverridesLegacy?: boolean
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function assertCapabilityEnabled(
|
|
592
|
+
ctx: Context,
|
|
593
|
+
current: () => CodexSettings,
|
|
594
|
+
toolName: string,
|
|
595
|
+
agent: Agent | undefined,
|
|
596
|
+
metadata: CodexToolMetadata,
|
|
597
|
+
authority?: boolean,
|
|
598
|
+
): void {
|
|
599
|
+
if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) {
|
|
600
|
+
throw new Error(`${toolName}: disabled in Codex Harness plugin settings`)
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
interface AppliedFile {
|
|
605
|
+
path: string
|
|
606
|
+
operation: 'created' | 'updated' | 'deleted' | 'moved'
|
|
607
|
+
moveTo?: string
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
interface ApplyPatchResult {
|
|
611
|
+
files: AppliedFile[]
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function sessionCwd(ctx: Context, exec: ToolExecution): string | undefined {
|
|
615
|
+
if (exec.agent === undefined) return undefined
|
|
616
|
+
const directories = ctx.get('workingDirectory') as { get(session: Session): string } | undefined
|
|
617
|
+
return directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function resolvePolicy(ctx: Context, exec: ToolExecution): SandboxExecutionPolicy | undefined {
|
|
621
|
+
const policy = ctx.get('sandboxPolicy')
|
|
622
|
+
return policy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async function resolveTarget(ctx: Context, path: string, exec: ToolExecution): Promise<FsTarget> {
|
|
626
|
+
const cwd = sessionCwd(ctx, exec)
|
|
627
|
+
return ctx.fs.resolve(path, cwd === undefined ? { signal: exec.signal } : { cwd, signal: exec.signal })
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async function observedTarget(ctx: Context, target: FsTarget, exec: ToolExecution): Promise<FsInfo> {
|
|
631
|
+
const info = await ctx.fs.stat(target, exec.signal)
|
|
632
|
+
if (info === undefined) throw new Error(`apply_patch: file not found: ${target.displayPath}`)
|
|
633
|
+
if (info.type !== 'file') throw new Error(`apply_patch: not a regular file: ${target.displayPath}`)
|
|
634
|
+
ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec)
|
|
635
|
+
return info
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async function writePatchedFile(
|
|
639
|
+
ctx: Context,
|
|
640
|
+
target: FsTarget,
|
|
641
|
+
content: string,
|
|
642
|
+
fallback: FsWriteIntent,
|
|
643
|
+
exec: ToolExecution,
|
|
644
|
+
policy: SandboxExecutionPolicy | undefined,
|
|
645
|
+
): Promise<'created' | 'updated'> {
|
|
646
|
+
const intent = await ctx.waterfall('fs/write-intent', target, exec, () => fallback)
|
|
647
|
+
const outcome = await ctx.fs.writeText(target, content, intent, exec.signal, policy)
|
|
648
|
+
ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec)
|
|
649
|
+
return outcome.operation === 'create' ? 'created' : 'updated'
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async function deletePatchedFile(
|
|
653
|
+
ctx: Context,
|
|
654
|
+
target: FsTarget,
|
|
655
|
+
version: FsInfo['version'],
|
|
656
|
+
exec: ToolExecution,
|
|
657
|
+
policy: SandboxExecutionPolicy | undefined,
|
|
658
|
+
): Promise<void> {
|
|
659
|
+
// Current providers expose deleteFile; rc.6 providers used remove instead.
|
|
660
|
+
type RemoveFile = (
|
|
661
|
+
target: FsTarget,
|
|
662
|
+
expected: { version: FsInfo['version'] } | undefined,
|
|
663
|
+
signal: AbortSignal,
|
|
664
|
+
sandboxPolicy?: SandboxExecutionPolicy,
|
|
665
|
+
) => Promise<unknown>
|
|
666
|
+
const fs = ctx.fs as unknown as { deleteFile?: RemoveFile; remove?: RemoveFile }
|
|
667
|
+
const remove = fs.deleteFile ?? fs.remove
|
|
668
|
+
if (typeof remove !== 'function') {
|
|
669
|
+
throw new Error('apply_patch: the configured dsh filesystem does not support file deletion')
|
|
670
|
+
}
|
|
671
|
+
const expected = await ctx.waterfall('fs/delete-intent', target, exec, () => ({ version }))
|
|
672
|
+
await remove.call(ctx.fs, target, expected, exec.signal, policy)
|
|
673
|
+
ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async function applyOnePatch(
|
|
677
|
+
ctx: Context,
|
|
678
|
+
file: PatchFile,
|
|
679
|
+
exec: ToolExecution,
|
|
680
|
+
policy: SandboxExecutionPolicy | undefined,
|
|
681
|
+
): Promise<AppliedFile> {
|
|
682
|
+
const target = await resolveTarget(ctx, file.path, exec)
|
|
683
|
+
if (file.kind === 'add') {
|
|
684
|
+
const existing = await ctx.fs.stat(target, exec.signal)
|
|
685
|
+
if (existing !== undefined) throw new Error(`apply_patch: file already exists: ${target.displayPath}`)
|
|
686
|
+
ctx.emit('fs/observed', target, { kind: 'absent' }, exec)
|
|
687
|
+
await writePatchedFile(ctx, target, file.content, { kind: 'createIfAbsent' }, exec, policy)
|
|
688
|
+
return { path: file.path, operation: 'created' }
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const sourceInfo = await observedTarget(ctx, target, exec)
|
|
692
|
+
const original = await ctx.fs.readText(target, exec.signal)
|
|
693
|
+
const updated = file.kind === 'delete' ? undefined : applyPatchHunks(original, file.hunks, file.path)
|
|
694
|
+
if (file.kind === 'delete') {
|
|
695
|
+
await deletePatchedFile(ctx, target, sourceInfo.version, exec, policy)
|
|
696
|
+
return { path: file.path, operation: 'deleted' }
|
|
697
|
+
}
|
|
698
|
+
if (file.moveTo === undefined) {
|
|
699
|
+
await writePatchedFile(ctx, target, updated!, { kind: 'replaceIfVersion', version: sourceInfo.version }, exec, policy)
|
|
700
|
+
return { path: file.path, operation: 'updated' }
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const destination = await resolveTarget(ctx, file.moveTo, exec)
|
|
704
|
+
if (destination.targetKey === target.targetKey) {
|
|
705
|
+
await writePatchedFile(ctx, target, updated!, { kind: 'replaceIfVersion', version: sourceInfo.version }, exec, policy)
|
|
706
|
+
return { path: file.path, operation: 'updated', moveTo: file.moveTo }
|
|
707
|
+
}
|
|
708
|
+
const destinationInfo = await ctx.fs.stat(destination, exec.signal)
|
|
709
|
+
if (destinationInfo !== undefined) throw new Error(`apply_patch: move destination already exists: ${destination.displayPath}`)
|
|
710
|
+
ctx.emit('fs/observed', destination, { kind: 'absent' }, exec)
|
|
711
|
+
await writePatchedFile(ctx, destination, updated!, { kind: 'createIfAbsent' }, exec, policy)
|
|
712
|
+
await deletePatchedFile(ctx, target, sourceInfo.version, exec, policy)
|
|
713
|
+
return { path: file.path, operation: 'moved', moveTo: file.moveTo }
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function patchSummary(value: ApplyPatchResult): string {
|
|
717
|
+
const letter = (operation: AppliedFile['operation']): string => {
|
|
718
|
+
switch (operation) {
|
|
719
|
+
case 'created': return 'A'
|
|
720
|
+
case 'updated': return 'M'
|
|
721
|
+
case 'deleted': return 'D'
|
|
722
|
+
case 'moved': return 'M'
|
|
723
|
+
default: return operation satisfies never
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
return `Success. Updated the following files:\n${value.files.map(file => `${letter(file.operation)} ${file.operation === 'moved' ? file.moveTo : file.path}`).join('\n')}\n`
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function planTodos(args: UpdatePlanArgs): TodoItem[] {
|
|
730
|
+
const seen = new Set<string>()
|
|
731
|
+
let active = 0
|
|
732
|
+
const todos: TodoItem[] = []
|
|
733
|
+
for (const item of args.plan) {
|
|
734
|
+
const content = item.step.trim()
|
|
735
|
+
if (content.length === 0) throw new Error('update_plan: every step must be non-empty')
|
|
736
|
+
if (seen.has(content)) throw new Error(`update_plan: duplicate step ${JSON.stringify(content)}`)
|
|
737
|
+
seen.add(content)
|
|
738
|
+
if (item.status === 'in_progress') active++
|
|
739
|
+
todos.push({ content, status: item.status })
|
|
740
|
+
}
|
|
741
|
+
if (active > 1) throw new Error('update_plan: at most one step may be in_progress')
|
|
742
|
+
return todos
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** Release every registration once, even when one release fails. */
|
|
746
|
+
function composeToolDisposers(disposers: Array<() => void>): () => void {
|
|
747
|
+
return () => {
|
|
748
|
+
const errors: unknown[] = []
|
|
749
|
+
for (const dispose of disposers.splice(0).reverse()) {
|
|
750
|
+
try { dispose() } catch (error) { errors.push(error) }
|
|
751
|
+
}
|
|
752
|
+
if (errors.length > 0) throw new AggregateError(errors, 'Could not unregister Codex tools')
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function registerExecTools(ctx: Context, config: ExecToolConfig): () => void {
|
|
757
|
+
const tools = ctx.get('tools')
|
|
758
|
+
if (tools === undefined) throw new Error('Codex execution tools require ctx.tools')
|
|
759
|
+
const shell = ctx.get('shell')
|
|
760
|
+
if (shell === undefined) throw new Error('Codex execution tools require ctx.shell')
|
|
761
|
+
const confines = shell.sandboxMode !== undefined
|
|
762
|
+
if (confines && ctx.get('sandboxPolicy') === undefined) throw new Error('Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy')
|
|
763
|
+
const legacyShellOptions = supportsLegacyShellOptions(ctx)
|
|
764
|
+
const metadata = { capability: 'terminalToolsEnabled' as const, presetEnabled: config.presetEnabled !== false,
|
|
765
|
+
...(config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) }
|
|
766
|
+
const unregisterExec = tools.register(markCodexTool(defineTool({
|
|
767
|
+
name: 'exec_command',
|
|
768
|
+
description: legacyShellOptions ? EXEC_COMMAND_DESCRIPTION
|
|
769
|
+
: EXEC_COMMAND_DESCRIPTION.replace('Runs a shell command.', 'Runs a command in the host-configured shell.'),
|
|
770
|
+
parameters: {
|
|
771
|
+
cmd: { type: 'string', required: true, description: 'Shell command to execute.' },
|
|
772
|
+
workdir: { type: 'string', description: 'Working directory for the command. Defaults to the turn cwd.' },
|
|
773
|
+
tty: { type: 'boolean', description: confines ? 'This host cannot carry sandbox policy into a PTY; omit tty or use false.' : 'True allocates a PTY for the command; false or omitted uses plain pipes.' },
|
|
774
|
+
run_in_background: { type: 'boolean', description: 'Run as a DSH background job and return its job id immediately; collect output with job_output and stop it with job_kill. Only supported for pipe-backed commands.' },
|
|
775
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.' },
|
|
776
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
777
|
+
...confines ? {
|
|
778
|
+
sandbox_permissions: { type: 'string' as const, enum: [...ESCALATION_TARGETS], description: sandboxPermissionsDescription('command') },
|
|
779
|
+
justification: { type: 'string' as const, description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request.' },
|
|
780
|
+
} : {},
|
|
781
|
+
...legacyShellOptions ? {
|
|
782
|
+
shell: { type: 'string' as const, description: "Shell binary to launch. Defaults to the user's default shell." },
|
|
783
|
+
login: { type: 'boolean' as const, description: 'True runs the shell with -l/-i semantics; false disables them. Defaults to true.' },
|
|
784
|
+
} : {},
|
|
785
|
+
},
|
|
786
|
+
output: {
|
|
787
|
+
schema: {
|
|
788
|
+
type: 'object',
|
|
789
|
+
additionalProperties: false,
|
|
790
|
+
properties: {
|
|
791
|
+
chunk_id: { type: 'string' },
|
|
792
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
793
|
+
exit_code: { type: 'number' },
|
|
794
|
+
session_id: { type: 'number' },
|
|
795
|
+
job_id: { type: 'string' },
|
|
796
|
+
original_token_count: { type: 'number' },
|
|
797
|
+
output: { type: 'string', required: true },
|
|
798
|
+
},
|
|
799
|
+
},
|
|
800
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
801
|
+
},
|
|
802
|
+
async execute(args: ExecCommandArgs, exec): Promise<ExecResult> {
|
|
803
|
+
assertCapabilityEnabled(ctx, config.currentSettings, 'exec_command', exec.agent, metadata, config.authority)
|
|
804
|
+
return runExecCommand(ctx, args, exec, config)
|
|
805
|
+
},
|
|
806
|
+
presentCall: args => ({
|
|
807
|
+
card: 'terminal',
|
|
808
|
+
title: args.cmd,
|
|
809
|
+
...args.workdir === undefined ? {} : { cwd: args.workdir },
|
|
810
|
+
}),
|
|
811
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'exec_command', metadata, config.currentSettings, config.authority) })
|
|
812
|
+
|
|
813
|
+
try {
|
|
814
|
+
const unregisterStdin = tools.register(markCodexTool(defineTool({
|
|
815
|
+
name: 'write_stdin',
|
|
816
|
+
description: WRITE_STDIN_DESCRIPTION,
|
|
817
|
+
parameters: {
|
|
818
|
+
session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
|
|
819
|
+
chars: { type: 'string', description: 'Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions do not accept input.' },
|
|
820
|
+
yield_time_ms: { type: 'number', description: 'Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default.' },
|
|
821
|
+
max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
|
|
822
|
+
},
|
|
823
|
+
output: {
|
|
824
|
+
schema: {
|
|
825
|
+
type: 'object',
|
|
826
|
+
additionalProperties: false,
|
|
827
|
+
properties: {
|
|
828
|
+
chunk_id: { type: 'string' },
|
|
829
|
+
wall_time_seconds: { type: 'number', required: true },
|
|
830
|
+
exit_code: { type: 'number' },
|
|
831
|
+
session_id: { type: 'number' },
|
|
832
|
+
original_token_count: { type: 'number' },
|
|
833
|
+
output: { type: 'string', required: true },
|
|
834
|
+
},
|
|
835
|
+
},
|
|
836
|
+
render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
|
|
837
|
+
},
|
|
838
|
+
async execute(args: WriteStdinArgs, exec): Promise<ExecResult> {
|
|
839
|
+
assertCapabilityEnabled(ctx, config.currentSettings, 'write_stdin', exec.agent, metadata, config.authority)
|
|
840
|
+
return runWriteStdin(ctx, args, exec, config)
|
|
841
|
+
},
|
|
842
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'write_stdin', metadata, config.currentSettings, config.authority) })
|
|
843
|
+
return composeToolDisposers([unregisterExec, unregisterStdin])
|
|
844
|
+
} catch (error) {
|
|
845
|
+
unregisterExec()
|
|
846
|
+
throw error
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function registerPatchTool(ctx: Context, currentSettings: () => CodexSettings, presetEnabled = true, presetOverridesLegacy = false): void {
|
|
851
|
+
const metadata = { capability: 'patchToolEnabled' as const, presetEnabled,
|
|
852
|
+
...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) }
|
|
853
|
+
ctx.tools.register(markCodexTool(defineTool({
|
|
854
|
+
name: 'apply_patch',
|
|
855
|
+
description: APPLY_PATCH_DESCRIPTION,
|
|
856
|
+
parameters: {
|
|
857
|
+
input: { type: 'string', required: true, description: 'The complete patch text.' },
|
|
858
|
+
},
|
|
859
|
+
output: {
|
|
860
|
+
schema: {
|
|
861
|
+
type: 'object',
|
|
862
|
+
additionalProperties: false,
|
|
863
|
+
properties: {
|
|
864
|
+
files: {
|
|
865
|
+
type: 'array',
|
|
866
|
+
required: true,
|
|
867
|
+
items: {
|
|
868
|
+
type: 'object',
|
|
869
|
+
additionalProperties: false,
|
|
870
|
+
properties: {
|
|
871
|
+
path: { type: 'string', required: true },
|
|
872
|
+
operation: { type: 'string', required: true, enum: ['created', 'updated', 'deleted', 'moved'] },
|
|
873
|
+
moveTo: { type: 'string' },
|
|
874
|
+
},
|
|
875
|
+
},
|
|
876
|
+
},
|
|
877
|
+
},
|
|
878
|
+
},
|
|
879
|
+
render: (_args, value) => [{ type: 'text', text: patchSummary(value) }],
|
|
880
|
+
},
|
|
881
|
+
async execute(args: { input: string }, exec): Promise<ApplyPatchResult> {
|
|
882
|
+
assertCapabilityEnabled(ctx, currentSettings, 'apply_patch', exec.agent, metadata)
|
|
883
|
+
const files = parsePatch(args.input)
|
|
884
|
+
const policy = resolvePolicy(ctx, exec)
|
|
885
|
+
const applied: AppliedFile[] = []
|
|
886
|
+
for (const file of files) applied.push(await applyOnePatch(ctx, file, exec, policy))
|
|
887
|
+
return { files: applied }
|
|
888
|
+
},
|
|
889
|
+
presentCall(args): GenericCallView {
|
|
890
|
+
return {
|
|
891
|
+
card: 'generic',
|
|
892
|
+
title: 'Apply patch',
|
|
893
|
+
kind: 'edit',
|
|
894
|
+
rawInput: args.input,
|
|
895
|
+
}
|
|
896
|
+
},
|
|
897
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'apply_patch', metadata, currentSettings) })
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function registerPlanTool(ctx: Context, currentSettings: () => CodexSettings, presetEnabled = true, authority?: boolean, presetOverridesLegacy = false): () => void {
|
|
901
|
+
const tools = ctx.get('tools')
|
|
902
|
+
if (tools === undefined) throw new Error('Codex plan tools require ctx.tools')
|
|
903
|
+
const metadata = { capability: 'planToolEnabled' as const, presetEnabled,
|
|
904
|
+
...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) }
|
|
905
|
+
return tools.register(markCodexTool(defineTool({
|
|
906
|
+
name: 'update_plan',
|
|
907
|
+
description: UPDATE_PLAN_DESCRIPTION,
|
|
908
|
+
parameters: {
|
|
909
|
+
explanation: { type: 'string', description: 'Optional explanation for this plan update.' },
|
|
910
|
+
plan: {
|
|
911
|
+
type: 'array',
|
|
912
|
+
required: true,
|
|
913
|
+
description: 'The list of steps',
|
|
914
|
+
items: {
|
|
915
|
+
type: 'object',
|
|
916
|
+
additionalProperties: false,
|
|
917
|
+
properties: {
|
|
918
|
+
step: { type: 'string', required: true, description: 'Task step text.' },
|
|
919
|
+
status: { type: 'string', required: true, enum: [...PLAN_STATUSES], description: 'Step status.' },
|
|
920
|
+
},
|
|
921
|
+
},
|
|
922
|
+
},
|
|
923
|
+
},
|
|
924
|
+
output: {
|
|
925
|
+
schema: { type: 'object', additionalProperties: false, properties: {} },
|
|
926
|
+
render: () => [{ type: 'text', text: 'Plan updated' }],
|
|
927
|
+
},
|
|
928
|
+
execute(args: UpdatePlanArgs, exec): Promise<Record<string, never>> {
|
|
929
|
+
assertCapabilityEnabled(ctx, currentSettings, 'update_plan', exec.agent, metadata, authority)
|
|
930
|
+
const agent = exec.agent
|
|
931
|
+
if (agent === undefined) throw new Error('update_plan requires an owning agent session')
|
|
932
|
+
agent.session.append('todo/write', { todos: planTodos(args) })
|
|
933
|
+
return Promise.resolve({})
|
|
934
|
+
},
|
|
935
|
+
}), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'update_plan', metadata, currentSettings, authority) })
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/** Select only the execution/plan contributions; omitted capability flags mean enabled. */
|
|
939
|
+
export interface CodexExecAndPlanOptions {
|
|
940
|
+
terminal?: boolean
|
|
941
|
+
plan?: boolean
|
|
942
|
+
defaultYieldTimeMs?: number
|
|
943
|
+
pollYieldTimeMs?: number
|
|
944
|
+
writeYieldTimeMs?: number
|
|
945
|
+
maxOutputBytes?: number
|
|
946
|
+
/** Internal compiled-plan authority; omitted preserves the unsnapshotted legacy path. */
|
|
947
|
+
capabilityAuthority?: Partial<Record<CodexCapability, boolean>>
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/**
|
|
951
|
+
* Register selected Codex tools through the existing pipeline, without file tools or prompt hooks.
|
|
952
|
+
* Compiled adapters receive authority once; the disposer supports an additional owner.
|
|
953
|
+
*/
|
|
954
|
+
export function registerCodexExecAndPlan(ctx: Context, options: CodexExecAndPlanOptions = {}): () => void {
|
|
955
|
+
const currentSettings = (): CodexSettings => ({
|
|
956
|
+
...CODEX_SETTINGS_ENTRY,
|
|
957
|
+
...readHostSettings<CodexSettings>(ctx, CODEX_SETTINGS_NAMESPACE),
|
|
958
|
+
})
|
|
959
|
+
const disposers: Array<() => void> = []
|
|
960
|
+
const dispose = composeToolDisposers(disposers)
|
|
961
|
+
try {
|
|
962
|
+
if (options.terminal !== false) disposers.push(registerExecTools(ctx, {
|
|
963
|
+
defaultYieldTimeMs: options.defaultYieldTimeMs ?? 10_000,
|
|
964
|
+
pollYieldTimeMs: options.pollYieldTimeMs ?? 5_000,
|
|
965
|
+
writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
|
|
966
|
+
maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
967
|
+
currentSettings,
|
|
968
|
+
...(options.capabilityAuthority?.terminalToolsEnabled === undefined ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }),
|
|
969
|
+
}))
|
|
970
|
+
if (options.plan !== false) disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled))
|
|
971
|
+
return dispose
|
|
972
|
+
} catch (error) {
|
|
973
|
+
dispose()
|
|
974
|
+
throw error
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/** Explicit preset instructions win without changing shared tools or permissions. */
|
|
979
|
+
export function withPresetPrompt(settings: CodexSettings, presetPrompt: string | undefined): CodexSettings {
|
|
980
|
+
return presetPrompt === undefined ? settings : { ...settings, systemPrompt: presetPrompt }
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/** Mount the Codex prompt/tool layer inside one fixed agent preset. */
|
|
984
|
+
export function apply(ctx: Context, config: Config = {}): void {
|
|
985
|
+
const resolved = {
|
|
986
|
+
globalEnhancements: config.globalEnhancements ?? true,
|
|
987
|
+
codexCore: config.codexCore ?? true,
|
|
988
|
+
defaultYieldTimeMs: config.defaultYieldTimeMs ?? 10_000,
|
|
989
|
+
pollYieldTimeMs: config.pollYieldTimeMs ?? 5_000,
|
|
990
|
+
writeYieldTimeMs: config.writeYieldTimeMs ?? 250,
|
|
991
|
+
maxOutputBytes: config.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
992
|
+
hostedWebSearch: config.hostedWebSearch ?? true,
|
|
993
|
+
remoteCompact: config.remoteCompact ?? true,
|
|
994
|
+
systemPrompt: config.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
|
|
995
|
+
persona: config.persona ?? DEFAULT_CODEX_PERSONA,
|
|
996
|
+
harnessSourcePrompt: config.harnessSourcePrompt ?? DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
997
|
+
webSurfacePrompt: config.webSurfacePrompt ?? DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
998
|
+
}
|
|
999
|
+
if (resolved.codexCore
|
|
1000
|
+
&& ctx.fs.sandboxMode !== undefined
|
|
1001
|
+
&& ctx.get('sandboxPolicy') === undefined) {
|
|
1002
|
+
throw new Error('codex: a sandboxing filesystem requires ctx.sandboxPolicy')
|
|
1003
|
+
}
|
|
1004
|
+
const sharedSettings = installCodexSettings(
|
|
1005
|
+
ctx,
|
|
1006
|
+
resolved.systemPrompt,
|
|
1007
|
+
resolved.persona,
|
|
1008
|
+
resolved.harnessSourcePrompt,
|
|
1009
|
+
resolved.webSurfacePrompt,
|
|
1010
|
+
)
|
|
1011
|
+
const codexSettings = { current: () => {
|
|
1012
|
+
const shared = withPresetPrompt(sharedSettings.current(), config.presetPrompt)
|
|
1013
|
+
return {
|
|
1014
|
+
...shared,
|
|
1015
|
+
...(config.promptEnabled === undefined ? {} : { promptEnabled: config.promptEnabled }),
|
|
1016
|
+
...(config.terminalToolsEnabled === undefined ? {} : { terminalToolsEnabled: config.terminalToolsEnabled }),
|
|
1017
|
+
...(config.patchToolEnabled === undefined ? {} : { patchToolEnabled: config.patchToolEnabled }),
|
|
1018
|
+
...(config.planToolEnabled === undefined ? {} : { planToolEnabled: config.planToolEnabled }),
|
|
1019
|
+
...(config.hostedWebSearchEnabled === undefined ? {} : { hostedWebSearchEnabled: config.hostedWebSearchEnabled }),
|
|
1020
|
+
...(config.remoteCompactionEnabled === undefined ? {} : { remoteCompactionEnabled: config.remoteCompactionEnabled }),
|
|
1021
|
+
}
|
|
1022
|
+
} }
|
|
1023
|
+
const execConfig = { ...resolved, currentSettings: codexSettings.current,
|
|
1024
|
+
presetEnabled: config.terminalToolsEnabled !== false,
|
|
1025
|
+
presetOverridesLegacy: config.terminalToolsEnabled !== undefined }
|
|
1026
|
+
|
|
1027
|
+
if (resolved.globalEnhancements) {
|
|
1028
|
+
// Native presets reject host services in their isolated composition.
|
|
1029
|
+
installPresetEditor(ctx)
|
|
1030
|
+
// The generic pi-ai plugin remains the owner of provider routes. This
|
|
1031
|
+
// layer adds only request metadata and remote-first transport behavior.
|
|
1032
|
+
watchConfiguredGptModels(ctx)
|
|
1033
|
+
registerCodexActivityProjection(ctx)
|
|
1034
|
+
installCodexContextProjection(ctx, codexSettings.current)
|
|
1035
|
+
ctx.on('agent/request', async (_payload, next) => {
|
|
1036
|
+
const request = await next()
|
|
1037
|
+
return applyCodexRequestSettings(request, codexSettings.current())
|
|
1038
|
+
})
|
|
1039
|
+
if (typeof (ctx as unknown as { effect?: unknown }).effect === 'function') {
|
|
1040
|
+
const disposeHostedWebSearch = installHostedWebSearch()
|
|
1041
|
+
ctx.effect(() => disposeHostedWebSearch, 'codex: Responses transport wrapper')
|
|
1042
|
+
}
|
|
1043
|
+
ctx.on('llm/stream', ((options: any, next: any) => {
|
|
1044
|
+
const settings = codexSettings.current()
|
|
1045
|
+
const contextWindow = options.contextWindow ?? settings.contextWindow
|
|
1046
|
+
const compactionMode = codexCompactionMode()
|
|
1047
|
+
const legacySafeNext = () => repairLegacyPiAiContextOverflow(
|
|
1048
|
+
next(),
|
|
1049
|
+
options.model,
|
|
1050
|
+
contextWindow,
|
|
1051
|
+
)
|
|
1052
|
+
if (options.purpose === 'compaction' && isGptModel(options.model)) {
|
|
1053
|
+
const useRemoteCompaction = compactionMode === 'remote'
|
|
1054
|
+
|| (compactionMode !== 'local' && resolved.remoteCompact && settings.remoteCompactionEnabled)
|
|
1055
|
+
if (useRemoteCompaction) {
|
|
1056
|
+
return remoteCompactStream(ctx, options, legacySafeNext, {
|
|
1057
|
+
hostedWebSearch: resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
|
|
1058
|
+
customApplyPatch: settings.patchToolEnabled,
|
|
1059
|
+
})
|
|
1060
|
+
}
|
|
1061
|
+
return legacySafeNext()
|
|
1062
|
+
}
|
|
1063
|
+
if (options.purpose === undefined && isGptModel(options.model)) {
|
|
1064
|
+
return repairLegacyPiAiContextOverflow(
|
|
1065
|
+
hostedWebSearchStream(next, {
|
|
1066
|
+
serviceTier: options.serviceTier ?? (settings.fast ? 'priority' : undefined),
|
|
1067
|
+
hostedWebSearch: resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
|
|
1068
|
+
customApplyPatch: settings.patchToolEnabled,
|
|
1069
|
+
}),
|
|
1070
|
+
options.model,
|
|
1071
|
+
contextWindow,
|
|
1072
|
+
)
|
|
1073
|
+
}
|
|
1074
|
+
return next()
|
|
1075
|
+
}) as any)
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (resolved.codexCore) {
|
|
1079
|
+
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
1080
|
+
const protectedNames = new Set(['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base']
|
|
1081
|
+
.filter(name => hasPresetPromptOverride(ctx, context, name)))
|
|
1082
|
+
return applyPromptSections(applyCodexPresentationSettings(await next(), codexSettings.current(), protectedNames), config.presetSections ?? {}, protectedNames)
|
|
1083
|
+
})
|
|
1084
|
+
ctx.systemPrompt.section({
|
|
1085
|
+
name: 'codex:base',
|
|
1086
|
+
order: 10,
|
|
1087
|
+
text: () => codexSettings.current().promptEnabled
|
|
1088
|
+
? resolveCodexSystemPrompt(codexSettings.current().systemPrompt)
|
|
1089
|
+
: '',
|
|
1090
|
+
})
|
|
1091
|
+
registerExecTools(ctx, execConfig)
|
|
1092
|
+
registerPatchTool(ctx, codexSettings.current, config.patchToolEnabled !== false, config.patchToolEnabled !== undefined)
|
|
1093
|
+
registerPlanTool(ctx, codexSettings.current, config.planToolEnabled !== false, undefined, config.planToolEnabled !== undefined)
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
export default { name, inject, Config, apply }
|