@shuind/dsh-codex-harness 0.2.21 → 0.3.0
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 +185 -0
- package/README.md +38 -50
- package/RELEASE.md +61 -0
- package/assets/codex.svg +5 -0
- package/cordis.patch.yml +181 -6
- package/docs/preset-library.md +33 -23
- package/docs/tool-policy-benchmark.json +310 -0
- package/docs/tool-policy.md +148 -0
- package/lib/client.js +4774 -2416
- package/lib/compact-command.js +416 -0
- package/lib/compaction.js +141 -12
- package/lib/hybrid-executor.js +1196 -0
- package/lib/index.js +3658 -2334
- package/lib/preferences.js +117 -0
- package/lib/tool-policy.js +2422 -0
- package/lib/typert.js +86 -79
- package/lib/types/client/activity.d.ts +33 -9
- package/lib/types/client/activity.js +4 -3
- package/lib/types/client/desktop.d.ts +67 -0
- package/lib/types/client/desktop.js +229 -0
- package/lib/types/client/index.d.ts +207 -110
- package/lib/types/client/index.js +99 -492
- package/lib/types/client/policy-drafts.d.ts +25 -0
- package/lib/types/client/policy-drafts.js +47 -0
- package/lib/types/client/policy-locale.d.ts +260 -0
- package/lib/types/client/policy-locale.js +357 -0
- package/lib/types/client/preset-manager.d.ts +38 -10
- package/lib/types/client/preset-manager.js +235 -185
- package/lib/types/client/preset-requests.d.ts +12 -0
- package/lib/types/client/preset-requests.js +101 -0
- package/lib/types/client/tool-policy.d.ts +33 -0
- package/lib/types/client/tool-policy.js +336 -0
- package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
- package/lib/types/contracts/preset-editor-schema.js +95 -0
- package/lib/types/{prompt.js → contracts/prompt.js} +13 -7
- package/lib/types/{settings.d.ts → contracts/settings.d.ts} +11 -4
- package/lib/types/{settings.js → contracts/settings.js} +22 -6
- package/lib/types/contracts/tool-policy-contract.d.ts +63 -0
- package/lib/types/contracts/tool-policy-contract.js +33 -0
- package/lib/types/contracts/ui-contracts.d.ts +92 -0
- package/lib/types/contracts/ui-contracts.js +83 -0
- package/lib/types/entries/client.d.ts +10 -0
- package/lib/types/entries/client.js +10 -0
- package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
- package/lib/types/entries/compact-command.js +176 -0
- package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +15 -3
- package/lib/types/{compaction.js → entries/compaction.js} +47 -11
- package/lib/types/entries/hybrid-executor.d.ts +19 -0
- package/lib/types/entries/hybrid-executor.js +57 -0
- package/lib/types/entries/index.d.ts +66 -0
- package/lib/types/entries/index.js +192 -0
- package/lib/types/entries/preferences.d.ts +11 -0
- package/lib/types/entries/preferences.js +16 -0
- package/lib/types/entries/tool-policy.d.ts +97 -0
- package/lib/types/entries/tool-policy.js +158 -0
- package/lib/types/entries/typert.host.d.ts +23 -0
- package/lib/types/entries/typert.host.js +24 -0
- package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
- package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
- package/lib/types/hybrid/hybrid-sdk.js +196 -0
- package/lib/types/hybrid/program-calls.d.ts +28 -0
- package/lib/types/hybrid/program-calls.js +193 -0
- package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
- package/lib/types/hybrid/subcall-scheduler.js +343 -0
- package/lib/types/policy/deferred-tools.d.ts +42 -0
- package/lib/types/policy/deferred-tools.js +264 -0
- package/lib/types/policy/overlay-installer.d.ts +12 -0
- package/lib/types/policy/overlay-installer.js +179 -0
- package/lib/types/policy/rule-resolver.d.ts +94 -0
- package/lib/types/policy/rule-resolver.js +114 -0
- package/lib/types/policy/tool-capabilities.d.ts +33 -0
- package/lib/types/policy/tool-capabilities.js +46 -0
- package/lib/types/{activity.d.ts → presets/activity.d.ts} +3 -5
- package/lib/types/{activity.js → presets/activity.js} +51 -27
- package/lib/types/presets/desktop-preset.d.ts +22 -0
- package/lib/types/presets/desktop-preset.js +43 -0
- package/lib/types/presets/preset-editor.d.ts +47 -0
- package/lib/types/presets/preset-editor.js +81 -0
- package/lib/types/presets/preset-prompt-catalog.d.ts +23 -0
- package/lib/types/presets/preset-prompt-catalog.js +215 -0
- package/lib/types/presets/preset-tool-catalog.d.ts +5 -0
- package/lib/types/presets/preset-tool-catalog.js +58 -0
- package/lib/types/presets/runtime-enhancements.d.ts +45 -0
- package/lib/types/presets/runtime-enhancements.js +349 -0
- package/lib/types/presets/small-window-compaction.d.ts +15 -0
- package/lib/types/presets/small-window-compaction.js +121 -0
- package/lib/types/responses/compact-checkpoint.d.ts +27 -0
- package/lib/types/responses/compact-checkpoint.js +257 -0
- package/lib/types/responses/fetch-transport.d.ts +16 -0
- package/lib/types/responses/fetch-transport.js +257 -0
- package/lib/types/responses/remote-compact.d.ts +13 -0
- package/lib/types/responses/remote-compact.js +319 -0
- package/lib/types/responses/sse-diagnostics.d.ts +9 -0
- package/lib/types/responses/sse-diagnostics.js +157 -0
- package/lib/types/responses/wire-rewrite.d.ts +35 -0
- package/lib/types/responses/wire-rewrite.js +237 -0
- package/lib/types/tools/exec-output.d.ts +58 -0
- package/lib/types/tools/exec-output.js +173 -0
- package/lib/types/tools/exec-plan-tools.d.ts +37 -0
- package/lib/types/tools/exec-plan-tools.js +265 -0
- package/lib/types/tools/exec-runner.d.ts +21 -0
- package/lib/types/tools/exec-runner.js +385 -0
- package/lib/types/tools/patch-tool.d.ts +16 -0
- package/lib/types/tools/patch-tool.js +258 -0
- package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
- package/lib/types/{patch.js → tools/patch.js} +96 -21
- package/locale/en.json +6 -0
- package/locale/hybrid-executor/en.json +6 -0
- package/locale/hybrid-executor/zh.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 +297 -299
- package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
- package/presets/codex-hybrid/preset.yml +3 -0
- package/scripts/benchmark-tool-policy.mjs +186 -0
- package/scripts/build-preset.mjs +19 -0
- package/scripts/clean-build.mjs +11 -0
- package/src/client/activity.ts +83 -0
- package/src/client/desktop.tsx +276 -0
- package/src/client/index.tsx +391 -0
- package/src/client/policy-drafts.ts +56 -0
- package/src/client/policy-locale.ts +362 -0
- package/src/client/preset-manager.tsx +376 -0
- package/src/client/preset-requests.ts +113 -0
- package/src/client/tool-policy.tsx +402 -0
- package/src/contracts/preset-editor-schema.ts +110 -0
- package/src/contracts/prompt.ts +66 -0
- package/src/contracts/settings.ts +103 -0
- package/src/contracts/tool-policy-contract.ts +93 -0
- package/src/contracts/ui-contracts.ts +173 -0
- package/src/entries/client.tsx +14 -0
- package/src/entries/compact-command.ts +256 -0
- package/src/entries/compaction.ts +218 -0
- package/src/entries/hybrid-executor.ts +76 -0
- package/src/entries/index.ts +298 -0
- package/src/entries/preferences.ts +17 -0
- package/src/entries/tool-policy.ts +162 -0
- package/src/entries/typert.host.ts +29 -0
- package/src/hybrid/codex-hybrid-executor.ts +310 -0
- package/src/hybrid/hybrid-sdk.ts +217 -0
- package/src/hybrid/program-calls.ts +202 -0
- package/src/hybrid/subcall-scheduler.ts +446 -0
- package/src/policy/deferred-tools.ts +331 -0
- package/src/policy/overlay-installer.ts +191 -0
- package/src/policy/rule-resolver.ts +128 -0
- package/src/policy/tool-capabilities.ts +88 -0
- package/src/presets/activity.ts +146 -0
- package/src/presets/desktop-preset.ts +60 -0
- package/src/presets/preset-editor.ts +101 -0
- package/src/presets/preset-prompt-catalog.ts +221 -0
- package/src/presets/preset-tool-catalog.ts +58 -0
- package/src/presets/runtime-enhancements.ts +415 -0
- package/src/presets/small-window-compaction.ts +166 -0
- package/src/responses/compact-checkpoint.ts +264 -0
- package/src/responses/fetch-transport.ts +290 -0
- package/src/responses/remote-compact.ts +393 -0
- package/src/responses/sse-diagnostics.ts +156 -0
- package/src/responses/wire-rewrite.ts +261 -0
- package/src/tools/exec-output.ts +211 -0
- package/src/tools/exec-plan-tools.ts +307 -0
- package/src/tools/exec-runner.ts +445 -0
- package/src/tools/patch-tool.ts +331 -0
- package/src/tools/patch.ts +328 -0
- package/tsconfig.json +29 -0
- package/tsdown.config.ts +110 -0
- package/lib/installer.js +0 -237
- package/lib/invariant.js +0 -23
- package/lib/types/activity-types.d.ts +0 -6
- package/lib/types/activity-types.js +0 -3
- package/lib/types/client/preset-copy.d.ts +0 -42
- package/lib/types/client/preset-copy.js +0 -81
- package/lib/types/compact-command.js +0 -79
- package/lib/types/context.d.ts +0 -8
- package/lib/types/context.js +0 -14
- package/lib/types/exec.d.ts +0 -46
- package/lib/types/exec.js +0 -365
- package/lib/types/index.d.ts +0 -95
- package/lib/types/index.js +0 -738
- package/lib/types/installer.d.ts +0 -27
- package/lib/types/installer.js +0 -146
- package/lib/types/invariant.d.ts +0 -16
- package/lib/types/invariant.js +0 -22
- package/lib/types/preset-contract.d.ts +0 -69
- package/lib/types/preset-contract.js +0 -22
- package/lib/types/preset-editor-remote.d.ts +0 -30
- package/lib/types/preset-editor-remote.js +0 -37
- package/lib/types/preset-editor.d.ts +0 -69
- package/lib/types/preset-editor.js +0 -557
- package/lib/types/preset-templates.d.ts +0 -36
- package/lib/types/preset-templates.js +0 -12
- package/lib/types/prompt-sections.d.ts +0 -15
- package/lib/types/prompt-sections.js +0 -23
- package/lib/types/remote.d.ts +0 -40
- package/lib/types/remote.js +0 -683
- package/lib/types/typert.host.d.ts +0 -47
- package/lib/types/typert.host.js +0 -99
- package/presets/codex-collaboration/preset.yml +0 -3
- /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Read-only capability inventory for a preset; never creates an Agent or evaluates `when`. */
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
|
4
|
+
import type {} from '@deepseek-ai/dsh-tools'
|
|
5
|
+
import { createScope } from '@deepseek-ai/dsh-scope'
|
|
6
|
+
import type { Scope } from '@deepseek-ai/dsh-scope'
|
|
7
|
+
import type { PresetToolCatalog, PresetToolReplacement } from '../contracts/tool-policy-contract.ts'
|
|
8
|
+
import { codexToolMetadata, readLegacyCapabilities } from '../policy/tool-capabilities.ts'
|
|
9
|
+
import { readDefaultDeferredTools, readDefaultHiddenTools } from '../policy/deferred-tools.ts'
|
|
10
|
+
|
|
11
|
+
export async function readPresetToolCatalog(ctx: Context, preset: string): Promise<PresetToolCatalog> {
|
|
12
|
+
if (typeof preset !== 'string' || !preset.trim() || preset.length > 256) throw new Error('invalid-preset-id')
|
|
13
|
+
const registry = ctx.get('agentPresets')
|
|
14
|
+
const tools = ctx.get('tools')
|
|
15
|
+
if (registry === undefined || typeof registry.acquireScope !== 'function' || tools === undefined) {
|
|
16
|
+
throw new Error('preset-tool-catalog-unavailable')
|
|
17
|
+
}
|
|
18
|
+
const lease = await registry.acquireScope(preset)
|
|
19
|
+
let view: Scope | undefined
|
|
20
|
+
try {
|
|
21
|
+
// A child view applies inherited masks exactly as an Agent would, but has no
|
|
22
|
+
// Agent driver, session, model selection, or initialization callbacks.
|
|
23
|
+
const key = {}
|
|
24
|
+
view = createScope(ctx, key, { parent: lease.key })
|
|
25
|
+
const defaultHidden = readDefaultHiddenTools(view.ctx, key)
|
|
26
|
+
const definitions = tools.definitions(key).filter(tool => !defaultHidden?.has(tool.name))
|
|
27
|
+
const names = new Set(definitions.map(tool => tool.name))
|
|
28
|
+
const defaultDeferred = readDefaultDeferredTools(view.ctx, key)
|
|
29
|
+
return {
|
|
30
|
+
preset,
|
|
31
|
+
registeredOnly: true,
|
|
32
|
+
legacyCapabilities: readLegacyCapabilities(ctx),
|
|
33
|
+
tools: definitions.map(definition => {
|
|
34
|
+
const conditional = tools.executable(definition.name, key) !== definition
|
|
35
|
+
const replacements: PresetToolReplacement[] = []
|
|
36
|
+
const action = definition.name === 'bash' || definition.name === 'pwsh' ? 'codex-exec'
|
|
37
|
+
: definition.name === 'todo_write' ? 'codex-plan'
|
|
38
|
+
: definition.name === 'edit' || definition.name === 'write' ? 'codex-patch' : undefined
|
|
39
|
+
if (action !== undefined) {
|
|
40
|
+
const targets = action === 'codex-exec' ? ['exec_command', 'write_stdin']
|
|
41
|
+
: action === 'codex-plan' ? ['update_plan']
|
|
42
|
+
: ['apply_patch']
|
|
43
|
+
const reason = conditional ? 'conditional' as const
|
|
44
|
+
: targets.some(target => names.has(target)) ? 'target-exists' as const : undefined
|
|
45
|
+
replacements.push({ action, tools: targets, available: reason === undefined,
|
|
46
|
+
...(reason === undefined ? {} : { reason }) })
|
|
47
|
+
}
|
|
48
|
+
const codexTool = codexToolMetadata(definition)
|
|
49
|
+
return { name: definition.name, description: definition.description.slice(0, 300), conditional, replacements,
|
|
50
|
+
...(defaultDeferred?.has(definition.name) ? { defaultDeferred: true } : {}),
|
|
51
|
+
...(codexTool === undefined ? {} : { codexTool }) }
|
|
52
|
+
}).sort((a, b) => a.name.localeCompare(b.name, 'en')),
|
|
53
|
+
}
|
|
54
|
+
} finally {
|
|
55
|
+
try { await view?.dispose() }
|
|
56
|
+
finally { await lease[Symbol.asyncDispose]() }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/** Host runtime enhancements: GPT model enrichment, context-window projection, and prompt templates. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import type { LlmCallConfig } from '@deepseek-ai/dsh-llm'
|
|
5
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
6
|
+
import type { PromptAssembly } from '@deepseek-ai/dsh-system-prompt'
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_CODEX_PERSONA,
|
|
9
|
+
DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
10
|
+
DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
11
|
+
resolveCodexSystemPrompt,
|
|
12
|
+
} from '../contracts/prompt.ts'
|
|
13
|
+
import { CODEX_SETTINGS_NAMESPACE, isGptModel, readHostSettings } from '../contracts/settings.ts'
|
|
14
|
+
import type { CodexSettings } from '../contracts/settings.ts'
|
|
15
|
+
import {
|
|
16
|
+
OPENAI_CODEX_MODEL_LIMITS,
|
|
17
|
+
OPENAI_CODEX_PROVIDER,
|
|
18
|
+
OPENAI_CODEX_SETTINGS_NAMESPACE,
|
|
19
|
+
} from '../contracts/ui-contracts.ts'
|
|
20
|
+
import { CodexPresetEditor } from './preset-editor.ts'
|
|
21
|
+
|
|
22
|
+
/** Add the preset editor when DSH's optional user-preset service is available. */
|
|
23
|
+
export function installPresetEditor(ctx: Context): void {
|
|
24
|
+
// `agentPresets` is supplied by dsh-agent-presets and may be installed after
|
|
25
|
+
// this plugin. Waiting through inject keeps the Codex core usable on hosts
|
|
26
|
+
// without that optional service while still mounting the Remote as soon as
|
|
27
|
+
// the Web preset catalog becomes available.
|
|
28
|
+
ctx.inject(['agentPresets'], presetCtx => {
|
|
29
|
+
void (async () => {
|
|
30
|
+
try {
|
|
31
|
+
await presetCtx.plugin(CodexPresetEditor)
|
|
32
|
+
} catch (error) {
|
|
33
|
+
ctx.logger.warn('codex: preset editor is unavailable on this host')
|
|
34
|
+
ctx.logger.warn(error)
|
|
35
|
+
}
|
|
36
|
+
})()
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const LLM_PI_AI_SETTINGS = 'llm-pi-ai' as const
|
|
41
|
+
|
|
42
|
+
/** Codex request envelope with the plugin's provider-facing service-tier field. */
|
|
43
|
+
export interface CodexRequestConfig extends LlmCallConfig {
|
|
44
|
+
/** Codex request context capacity override, retained for older DSH hosts. */
|
|
45
|
+
contextWindow?: number
|
|
46
|
+
/** Provider-facing service tier, for example Responses `priority`. */
|
|
47
|
+
serviceTier?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const GPT_REASONING_EFFORTS = {
|
|
51
|
+
low: 'low',
|
|
52
|
+
medium: 'medium',
|
|
53
|
+
high: 'high',
|
|
54
|
+
xhigh: 'xhigh',
|
|
55
|
+
max: 'max',
|
|
56
|
+
} as const
|
|
57
|
+
|
|
58
|
+
type CodexReasoningEfforts = false | Record<string, string | null>
|
|
59
|
+
|
|
60
|
+
function codexReasoningEfforts(configured: CodexReasoningEfforts | undefined): CodexReasoningEfforts {
|
|
61
|
+
if (configured === false) return false
|
|
62
|
+
const filtered = configured === undefined
|
|
63
|
+
? {}
|
|
64
|
+
: Object.fromEntries(Object.entries(configured).filter(([level]) => level !== 'off' && level !== 'minimal'))
|
|
65
|
+
return Object.keys(filtered).length === 0 ? GPT_REASONING_EFFORTS : filtered
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface CodexModelProfile {
|
|
69
|
+
id: string
|
|
70
|
+
input?: string[]
|
|
71
|
+
reasoningEfforts?: false | Record<string, string | null>
|
|
72
|
+
[key: string]: unknown
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface CodexModelOverride {
|
|
76
|
+
input?: string[]
|
|
77
|
+
reasoningEfforts?: false | Record<string, string | null>
|
|
78
|
+
[key: string]: unknown
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface CodexProviderProfile {
|
|
82
|
+
models?: CodexModelProfile[]
|
|
83
|
+
modelOverrides?: Record<string, CodexModelOverride>
|
|
84
|
+
[key: string]: unknown
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface LlmPiAiSettings {
|
|
88
|
+
providers?: Record<string, CodexProviderProfile>
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Add Codex defaults without overwriting explicit user capabilities. */
|
|
92
|
+
export function enrichCodexModel(model: CodexModelProfile): CodexModelProfile {
|
|
93
|
+
if (!isGptModel(model.id)) return model
|
|
94
|
+
const input = model.input === undefined || model.input.length === 0
|
|
95
|
+
? ['text', 'image']
|
|
96
|
+
: model.input
|
|
97
|
+
const efforts = codexReasoningEfforts(model.reasoningEfforts)
|
|
98
|
+
if (input === model.input && efforts === model.reasoningEfforts) return model
|
|
99
|
+
return { ...model, input, reasoningEfforts: efforts }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The settings schema keys modelOverrides by id, so its values must not carry an id field. */
|
|
103
|
+
function enrichCodexOverride(id: string, model: CodexModelOverride): CodexModelOverride {
|
|
104
|
+
if (!isGptModel(id)) return model
|
|
105
|
+
const enriched = enrichCodexModel({ ...model, id })
|
|
106
|
+
const { id: _id, ...withoutId } = enriched
|
|
107
|
+
const inputMissing = model.input === undefined || model.input.length === 0
|
|
108
|
+
const nextEfforts = codexReasoningEfforts(model.reasoningEfforts)
|
|
109
|
+
const reasoningChanged = JSON.stringify(nextEfforts) !== JSON.stringify(model.reasoningEfforts)
|
|
110
|
+
if (!inputMissing && !reasoningChanged) return model
|
|
111
|
+
return { ...withoutId, reasoningEfforts: nextEfforts }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Persist only missing GPT capabilities into the user's existing pi-ai model config. */
|
|
115
|
+
async function enrichConfiguredGptModels(ctx: Context): Promise<void> {
|
|
116
|
+
const settings = ctx.get('settings') as { update(ns: string, patch: object): Promise<void> } | undefined
|
|
117
|
+
if (settings === undefined) return
|
|
118
|
+
const current = readHostSettings<LlmPiAiSettings>(ctx, LLM_PI_AI_SETTINGS)
|
|
119
|
+
if (current?.providers === undefined) return
|
|
120
|
+
const providers: Record<string, Record<string, unknown>> = {}
|
|
121
|
+
let changed = false
|
|
122
|
+
for (const [provider, profile] of Object.entries(current.providers)) {
|
|
123
|
+
const models = profile.models
|
|
124
|
+
const overrides = profile.modelOverrides
|
|
125
|
+
const nextModels = Array.isArray(models) ? models.map(enrichCodexModel) : undefined
|
|
126
|
+
const nextOverrides = overrides === undefined
|
|
127
|
+
? undefined
|
|
128
|
+
: Object.fromEntries(Object.entries(overrides).map(([id, model]) => [id, enrichCodexOverride(id, model)]))
|
|
129
|
+
const modelsChanged = nextModels !== undefined && nextModels.some((model, index) => model !== models?.[index])
|
|
130
|
+
const overridesChanged = nextOverrides !== undefined
|
|
131
|
+
&& overrides !== undefined
|
|
132
|
+
&& Object.entries(nextOverrides).some(([id, model]) => model !== overrides[id])
|
|
133
|
+
if (modelsChanged || overridesChanged) {
|
|
134
|
+
changed = true
|
|
135
|
+
providers[provider] = {
|
|
136
|
+
...modelsChanged ? { models: nextModels } : {},
|
|
137
|
+
...overridesChanged ? { modelOverrides: nextOverrides } : {},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (changed) await settings.update(LLM_PI_AI_SETTINGS, { providers })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Keep newly edited GPT model entries enriched while Codex mode is mounted. */
|
|
145
|
+
export function watchConfiguredGptModels(ctx: Context): void {
|
|
146
|
+
let tail = Promise.resolve()
|
|
147
|
+
const schedule = (): void => {
|
|
148
|
+
tail = tail.then(() => enrichConfiguredGptModels(ctx)).catch(error => {
|
|
149
|
+
ctx.logger.warn('codex: could not enrich configured GPT model capabilities')
|
|
150
|
+
ctx.logger.warn(error)
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
ctx.on('settings/document-updated', (ns) => {
|
|
154
|
+
if (ns === LLM_PI_AI_SETTINGS) schedule()
|
|
155
|
+
})
|
|
156
|
+
schedule()
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
type CodexPromptPresentation = Pick<PromptAssembly, 'sections' | 'contexts' | 'variables'>
|
|
160
|
+
|
|
161
|
+
type SessionEvent = { type: string; seq: number }
|
|
162
|
+
|
|
163
|
+
function hasOpenTurn(session: Session): boolean {
|
|
164
|
+
const events = session.snapshotEvents() as readonly SessionEvent[]
|
|
165
|
+
const start = events.findLast(event => event.type === 'turn/start')
|
|
166
|
+
const end = events.findLast(event => event.type === 'turn/end')
|
|
167
|
+
return start !== undefined && (end === undefined || start.seq > end.seq)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Pair the live Codex capacity with the token-meter context projection.
|
|
172
|
+
*
|
|
173
|
+
* The core loop records adapter metadata in `request/context`, while Codex's
|
|
174
|
+
* setting is a request-scoped LLM capacity. Appending the override after the
|
|
175
|
+
* loop's metadata event keeps the official ContextMeter and compaction engine
|
|
176
|
+
* on the same effective capacity.
|
|
177
|
+
*/
|
|
178
|
+
function appendRequestContextWindow(
|
|
179
|
+
session: Session,
|
|
180
|
+
provider: string,
|
|
181
|
+
model: string,
|
|
182
|
+
contextWindow: number,
|
|
183
|
+
): void {
|
|
184
|
+
const current = session.requestContext()
|
|
185
|
+
if (current?.provider === provider
|
|
186
|
+
&& current.model === model
|
|
187
|
+
&& current.contextWindow === contextWindow) return
|
|
188
|
+
session.append('request/context', {
|
|
189
|
+
provider,
|
|
190
|
+
model,
|
|
191
|
+
contextWindow,
|
|
192
|
+
// Capacity is only one field of the routed capability snapshot.
|
|
193
|
+
...current?.provider === provider && current.model === model ? {
|
|
194
|
+
...current.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: current.systemPromptUpdate },
|
|
195
|
+
} : {},
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function syncCodexContextWindow(session: Session, contextWindow: number | undefined): void {
|
|
200
|
+
if (contextWindow === undefined
|
|
201
|
+
|| !Number.isSafeInteger(contextWindow)
|
|
202
|
+
|| contextWindow <= 0
|
|
203
|
+
|| !hasOpenTurn(session)) return
|
|
204
|
+
const config = session.requestHeader()?.config as {
|
|
205
|
+
provider?: unknown
|
|
206
|
+
model?: unknown
|
|
207
|
+
} | undefined
|
|
208
|
+
if (typeof config?.provider !== 'string'
|
|
209
|
+
|| config.provider === OPENAI_CODEX_PROVIDER
|
|
210
|
+
|| typeof config.model !== 'string'
|
|
211
|
+
|| !isGptModel(config.model)) return
|
|
212
|
+
appendRequestContextWindow(session, config.provider, config.model, contextWindow)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Keep open Codex Connect turns aligned with per-model `llm-openai-codex` overrides. */
|
|
216
|
+
export function syncOpenAICodexTurnContext(ctx: Context, session: Session): void {
|
|
217
|
+
if (!hasOpenTurn(session)) return
|
|
218
|
+
const config = session.requestHeader()?.config as { provider?: unknown; model?: unknown } | undefined
|
|
219
|
+
if (config?.provider !== OPENAI_CODEX_PROVIDER || typeof config.model !== 'string' || !isGptModel(config.model)) return
|
|
220
|
+
const overrides = readHostSettings<{ contextWindowOverrides?: Record<string, number | null> }>(
|
|
221
|
+
ctx,
|
|
222
|
+
OPENAI_CODEX_SETTINGS_NAMESPACE,
|
|
223
|
+
)?.contextWindowOverrides
|
|
224
|
+
const override = overrides?.[config.model]
|
|
225
|
+
const llm = ctx.get('llm') as {
|
|
226
|
+
resolveModelInfo?: (provider: string, model: string) => { contextWindow?: number } | undefined
|
|
227
|
+
} | undefined
|
|
228
|
+
const effective = typeof override === 'number' && Number.isSafeInteger(override) && override > 0
|
|
229
|
+
? override
|
|
230
|
+
: OPENAI_CODEX_MODEL_LIMITS[config.model]?.defaultTokens
|
|
231
|
+
?? llm?.resolveModelInfo?.(OPENAI_CODEX_PROVIDER, config.model)?.contextWindow
|
|
232
|
+
if (effective === undefined || !Number.isSafeInteger(effective) || effective <= 0) return
|
|
233
|
+
appendRequestContextWindow(session, OPENAI_CODEX_PROVIDER, config.model, effective)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Keep the official context meter synchronized with a live Codex override. */
|
|
237
|
+
export function installCodexContextProjection(ctx: Context, current: () => CodexSettings): void {
|
|
238
|
+
const sync = (session: Session, contextWindow = current().contextWindow): void => {
|
|
239
|
+
syncCodexContextWindow(session, contextWindow)
|
|
240
|
+
}
|
|
241
|
+
const pending = new WeakSet<Session>()
|
|
242
|
+
const syncAfterPublication = (session: Session): void => {
|
|
243
|
+
if (pending.has(session)) return
|
|
244
|
+
pending.add(session)
|
|
245
|
+
queueMicrotask(() => {
|
|
246
|
+
try {
|
|
247
|
+
sync(session)
|
|
248
|
+
} finally {
|
|
249
|
+
pending.delete(session)
|
|
250
|
+
}
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
const listSessions = (): readonly Session[] => {
|
|
254
|
+
const sessions = ctx.get('sessions') as { list?: () => readonly Session[] } | undefined
|
|
255
|
+
return sessions?.list?.() ?? []
|
|
256
|
+
}
|
|
257
|
+
const syncAll = (contextWindow = current().contextWindow): void => {
|
|
258
|
+
for (const session of listSessions()) sync(session, contextWindow)
|
|
259
|
+
}
|
|
260
|
+
ctx.on('session/event', (session, event) => {
|
|
261
|
+
// Session.append() rejects nested appends until every observer returns.
|
|
262
|
+
if (event.type === 'request/header' || event.type === 'request/context') syncAfterPublication(session)
|
|
263
|
+
})
|
|
264
|
+
// Restored sessions may already contain their request/header seed, so no
|
|
265
|
+
// session/event is emitted for the initial capacity. Catch them at the
|
|
266
|
+
// store publication boundary as well.
|
|
267
|
+
ctx.on('session/created', syncAfterPublication)
|
|
268
|
+
ctx.on('settings/document-updated', ns => {
|
|
269
|
+
if (ns === CODEX_SETTINGS_NAMESPACE) syncAll()
|
|
270
|
+
else if (ns === OPENAI_CODEX_SETTINGS_NAMESPACE) {
|
|
271
|
+
for (const session of listSessions()) syncOpenAICodexTurnContext(ctx, session)
|
|
272
|
+
}
|
|
273
|
+
})
|
|
274
|
+
syncAll()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Apply the live Codex controls to one agent request without leaking them to other routes. */
|
|
278
|
+
export function applyCodexRequestSettings(
|
|
279
|
+
request: CodexRequestConfig,
|
|
280
|
+
settings: CodexSettings,
|
|
281
|
+
): CodexRequestConfig {
|
|
282
|
+
const {
|
|
283
|
+
contextWindow: _inheritedContextWindow,
|
|
284
|
+
serviceTier: _inheritedServiceTier,
|
|
285
|
+
...withoutCodexControls
|
|
286
|
+
} = request
|
|
287
|
+
if (request.provider === 'openai-codex' || !isGptModel(request.model)) return withoutCodexControls
|
|
288
|
+
return {
|
|
289
|
+
...withoutCodexControls,
|
|
290
|
+
...settings.contextWindow === undefined ? {} : { contextWindow: settings.contextWindow },
|
|
291
|
+
...settings.fast ? { serviceTier: 'priority' } : {},
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Put the agent persona first and omit the generic Harness identity opener. */
|
|
296
|
+
export function normalizeCodexPromptAssembly<T extends CodexPromptPresentation>(assembly: T): T {
|
|
297
|
+
const sections = assembly.sections.filter(section => section.name !== 'harness:identity')
|
|
298
|
+
const persona = sections.find(section => section.name === 'deployment:persona-prefix')
|
|
299
|
+
?? sections.find(section => section.name === 'deployment:persona')
|
|
300
|
+
if (persona === undefined) return { ...assembly, sections }
|
|
301
|
+
return {
|
|
302
|
+
...assembly,
|
|
303
|
+
sections: [persona, ...sections.filter(section => section !== persona)],
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function unquoteContextValue(raw: string): string {
|
|
308
|
+
const trimmed = raw.trim().replace(/\.$/, '')
|
|
309
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
310
|
+
try {
|
|
311
|
+
const parsed = JSON.parse(trimmed) as unknown
|
|
312
|
+
if (typeof parsed === 'string') return parsed
|
|
313
|
+
} catch {
|
|
314
|
+
// Leave unparsed literal text when not a valid JSON string literal.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return trimmed
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function cwdContextValue(cwdText: string | undefined): string | undefined {
|
|
321
|
+
const match = cwdText?.match(/^Current working directory:\s*(.+?)\.?$/u)
|
|
322
|
+
return match?.[1] === undefined ? undefined : unquoteContextValue(match[1])
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function promptVariables(assembly: CodexPromptPresentation): Record<string, string | undefined> {
|
|
326
|
+
const variables = { ...assembly.variables }
|
|
327
|
+
if (variables.cwd === undefined) {
|
|
328
|
+
const cwdText = assembly.contexts?.find(candidate => candidate.name === 'working-directory:current')?.text
|
|
329
|
+
const contextMatch = cwdContextValue(cwdText)
|
|
330
|
+
if (contextMatch !== undefined) variables.cwd = contextMatch
|
|
331
|
+
}
|
|
332
|
+
if (variables.sourceRoot === undefined) {
|
|
333
|
+
const source = assembly.sections.find(candidate => candidate.name === 'harness:source')?.text
|
|
334
|
+
const legacyMatch = source?.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u)
|
|
335
|
+
if (legacyMatch?.[1] !== undefined) {
|
|
336
|
+
variables.sourceRoot = legacyMatch[1]
|
|
337
|
+
} else {
|
|
338
|
+
const ctxText = assembly.contexts?.find(candidate => candidate.name === 'harness:source')?.text
|
|
339
|
+
const contextMatch = ctxText?.match(/^Current DeepSeek Harness implementation checkout:\s*(.+?)\.?$/u)
|
|
340
|
+
if (contextMatch?.[1] !== undefined) variables.sourceRoot = unquoteContextValue(contextMatch[1])
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (variables.webUrl === undefined) {
|
|
344
|
+
const web = assembly.sections.find(candidate => candidate.name === 'app:web-surface')?.text
|
|
345
|
+
const legacyMatch = web?.match(/^You are interacting with the user through the DeepSeek Harness Web GUI at (.+?)\. When/u)
|
|
346
|
+
if (legacyMatch?.[1] !== undefined) {
|
|
347
|
+
variables.webUrl = legacyMatch[1]
|
|
348
|
+
} else {
|
|
349
|
+
const ctxText = assembly.contexts?.find(candidate => candidate.name === 'app:web-surface')?.text
|
|
350
|
+
const contextMatch = ctxText?.match(/^Current DeepSeek Harness Web GUI URL:\s*(.+?)\.?$/u)
|
|
351
|
+
if (contextMatch?.[1] !== undefined) variables.webUrl = unquoteContextValue(contextMatch[1])
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return variables
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function interpolateCodexPrompt(text: string, variables: Record<string, string | undefined>): string {
|
|
358
|
+
return text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key: string) => variables[key] ?? whole)
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Apply user-editable Persona and DSH Core runtime prompt templates. */
|
|
362
|
+
function applyCodexPromptOverrides<T extends CodexPromptPresentation>(assembly: T, settings: CodexSettings): T {
|
|
363
|
+
const overrides: Record<string, string | undefined> = {
|
|
364
|
+
'deployment:persona': settings.persona,
|
|
365
|
+
'deployment:persona-prefix': settings.persona,
|
|
366
|
+
'harness:source': settings.harnessSourcePrompt,
|
|
367
|
+
'app:web-surface': settings.webSurfacePrompt,
|
|
368
|
+
}
|
|
369
|
+
const defaults: Record<string, string> = {
|
|
370
|
+
'deployment:persona': DEFAULT_CODEX_PERSONA,
|
|
371
|
+
'deployment:persona-prefix': DEFAULT_CODEX_PERSONA,
|
|
372
|
+
'harness:source': DEFAULT_DSH_CORE_SOURCE_PROMPT,
|
|
373
|
+
'app:web-surface': DEFAULT_DSH_CORE_WEB_PROMPT,
|
|
374
|
+
}
|
|
375
|
+
const hasCustomOverride = Object.entries(overrides).some(([name, text]) => (
|
|
376
|
+
text !== undefined && text !== defaults[name]
|
|
377
|
+
))
|
|
378
|
+
if (!hasCustomOverride) return assembly
|
|
379
|
+
const variables = promptVariables(assembly)
|
|
380
|
+
const sections = assembly.sections.map(section => {
|
|
381
|
+
const template = overrides[section.name]
|
|
382
|
+
return template === undefined || template === defaults[section.name]
|
|
383
|
+
? section
|
|
384
|
+
: { ...section, text: interpolateCodexPrompt(template, variables) }
|
|
385
|
+
})
|
|
386
|
+
return { ...assembly, sections, variables }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Apply Persona/DSH Core prompt overrides and optional ordering normalization. */
|
|
390
|
+
export function applyCodexPresentationSettings<T extends CodexPromptPresentation>(
|
|
391
|
+
assembly: T,
|
|
392
|
+
settings: CodexSettings,
|
|
393
|
+
protectedNames?: ReadonlySet<string>,
|
|
394
|
+
): T {
|
|
395
|
+
const promptSettings = { ...settings }
|
|
396
|
+
if (protectedNames?.has('deployment:persona-prefix')) delete promptSettings.persona
|
|
397
|
+
const withOverrides = applyCodexPromptOverrides(assembly, promptSettings)
|
|
398
|
+
const normalized = settings.promptEnabled ? normalizeCodexPromptAssembly(withOverrides) : withOverrides
|
|
399
|
+
if (normalized.variables.cwd === undefined
|
|
400
|
+
&& normalized.sections.some(section => section.interpolate !== false && section.text.includes('{{cwd}}'))) {
|
|
401
|
+
const variables = promptVariables(normalized)
|
|
402
|
+
if (variables.cwd !== undefined) return { ...normalized, variables }
|
|
403
|
+
}
|
|
404
|
+
return normalized
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Build the complete plugin-owned prompt, preserving an intentional empty value. */
|
|
408
|
+
export function buildCodexSystemPrompt(config: { systemPrompt?: string } = {}): string {
|
|
409
|
+
return resolveCodexSystemPrompt(config.systemPrompt)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Explicit preset instructions win without changing shared tools or permissions. */
|
|
413
|
+
export function withPresetPrompt(settings: CodexSettings, presetPrompt: string | undefined): CodexSettings {
|
|
414
|
+
return presetPrompt === undefined ? settings : { ...settings, systemPrompt: presetPrompt }
|
|
415
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/** Automatic compaction fallback when a GPT session uses a window below DSH's 65K headroom floor. */
|
|
2
|
+
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import { toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction'
|
|
5
|
+
import type { Session, SessionSeq } from '@deepseek-ai/dsh-session'
|
|
6
|
+
import type { TokenMeasurement } from '@deepseek-ai/dsh-token-meter'
|
|
7
|
+
import { isGptModel } from '../contracts/settings.ts'
|
|
8
|
+
import type { CodexSettings } from '../contracts/settings.ts'
|
|
9
|
+
|
|
10
|
+
const UPSTREAM_HEADROOM_FLOOR = 80_000
|
|
11
|
+
const DEFAULT_SMALL_THRESHOLD_RATIO = 0.8
|
|
12
|
+
const DEFAULT_SMALL_RETAIN_RATIO = 0.16
|
|
13
|
+
|
|
14
|
+
interface CompactRange {
|
|
15
|
+
readonly start: SessionSeq
|
|
16
|
+
readonly end: SessionSeq
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface ScopedCompactionService {
|
|
20
|
+
readonly codexSmallWindowReady?: boolean
|
|
21
|
+
compactRegion?: (start: SessionSeq, end: SessionSeq, agent: unknown, signal: AbortSignal) => Promise<unknown>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface AgentPresetsLookup {
|
|
25
|
+
serviceFor?: (agent: unknown, name: string) => unknown
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface AgentLike {
|
|
29
|
+
readonly ctx?: Context
|
|
30
|
+
readonly session: Session
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Select the oldest tool-balanced span outside `retainTokens`, preserving a leading system node. */
|
|
34
|
+
export function selectSmallWindowRange(
|
|
35
|
+
session: Session,
|
|
36
|
+
measurement: TokenMeasurement,
|
|
37
|
+
retainTokens: number,
|
|
38
|
+
): CompactRange | null {
|
|
39
|
+
const pricedNodes = measurement.nodes
|
|
40
|
+
if (pricedNodes.length === 0) return null
|
|
41
|
+
const surfaceNodes = session.surface.nodes
|
|
42
|
+
if (surfaceNodes.length !== pricedNodes.length
|
|
43
|
+
|| surfaceNodes.some((seq, index) => seq !== pricedNodes[index]?.seq)) return null
|
|
44
|
+
const firstIdx = session.eventAt(surfaceNodes[0]!)?.type === 'system/message' ? 1 : 0
|
|
45
|
+
let accumulated = 0
|
|
46
|
+
let keepFromIdx = pricedNodes.length
|
|
47
|
+
for (let index = pricedNodes.length - 1; index >= 0; index -= 1) {
|
|
48
|
+
accumulated += pricedNodes[index]!.tokens
|
|
49
|
+
keepFromIdx = index
|
|
50
|
+
if (accumulated >= retainTokens) break
|
|
51
|
+
}
|
|
52
|
+
while (keepFromIdx > firstIdx && !toolPairingBalancedBefore(session, surfaceNodes[keepFromIdx]!)) {
|
|
53
|
+
keepFromIdx -= 1
|
|
54
|
+
}
|
|
55
|
+
if (keepFromIdx <= firstIdx) return null
|
|
56
|
+
return { start: surfaceNodes[firstIdx]!, end: surfaceNodes[keepFromIdx - 1]! }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function compactSmallWindowIfNeeded(
|
|
60
|
+
ctx: Context,
|
|
61
|
+
agent: AgentLike,
|
|
62
|
+
header: { readonly config?: { readonly provider?: unknown; readonly model?: unknown; readonly contextWindow?: unknown } },
|
|
63
|
+
signal: AbortSignal,
|
|
64
|
+
currentSettings: () => CodexSettings,
|
|
65
|
+
requireBelowThreshold: boolean,
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
const provider = header.config?.provider
|
|
68
|
+
const model = header.config?.model
|
|
69
|
+
if (typeof provider !== 'string' || typeof model !== 'string' || !isGptModel(model)) return
|
|
70
|
+
|
|
71
|
+
const agentCtx = agent.ctx ?? ctx
|
|
72
|
+
const agentPresets = (ctx as unknown as {
|
|
73
|
+
get?: (name: string) => AgentPresetsLookup | undefined
|
|
74
|
+
}).get?.('agentPresets')
|
|
75
|
+
const compaction = (agentPresets?.serviceFor?.(agent, 'compaction') ?? agentCtx.get('compaction')) as ScopedCompactionService | undefined
|
|
76
|
+
if (compaction?.compactRegion === undefined || compaction.codexSmallWindowReady === true) return
|
|
77
|
+
const tokenMeter = agentCtx.get('tokenMeter') as {
|
|
78
|
+
measure?: (session: Session, header?: unknown) => TokenMeasurement
|
|
79
|
+
} | undefined
|
|
80
|
+
if (tokenMeter?.measure === undefined) return
|
|
81
|
+
|
|
82
|
+
const llm = agentCtx.get('llm') as {
|
|
83
|
+
resolveModelInfo?: (p: string, m: string, s?: AbortSignal) => Promise<{ context?: { contextWindow?: number } } | undefined>
|
|
84
|
+
} | undefined
|
|
85
|
+
const info = await llm?.resolveModelInfo?.(provider, model, signal)
|
|
86
|
+
const headerWindow = typeof header.config?.contextWindow === 'number' ? header.config.contextWindow : undefined
|
|
87
|
+
const effectiveWindow = provider === 'openai-codex'
|
|
88
|
+
? info?.context?.contextWindow
|
|
89
|
+
: (currentSettings().contextWindow ?? headerWindow ?? info?.context?.contextWindow)
|
|
90
|
+
if (typeof effectiveWindow !== 'number'
|
|
91
|
+
|| !Number.isSafeInteger(effectiveWindow)
|
|
92
|
+
|| effectiveWindow <= 0
|
|
93
|
+
|| effectiveWindow >= UPSTREAM_HEADROOM_FLOOR) return
|
|
94
|
+
|
|
95
|
+
const thresholdTokens = Math.max(1_024, Math.floor(effectiveWindow * DEFAULT_SMALL_THRESHOLD_RATIO))
|
|
96
|
+
const retainTokens = Math.floor(effectiveWindow * DEFAULT_SMALL_RETAIN_RATIO)
|
|
97
|
+
let measurement = tokenMeter.measure(agent.session, header)
|
|
98
|
+
if (measurement.totalTokens < thresholdTokens) return
|
|
99
|
+
|
|
100
|
+
const pruner = (agentPresets?.serviceFor?.(agent, 'toolResultPruner') ?? agentCtx.get('toolResultPruner')) as { pruneSession?: (session: Session) => void } | undefined
|
|
101
|
+
if (pruner?.pruneSession !== undefined) {
|
|
102
|
+
pruner.pruneSession(agent.session)
|
|
103
|
+
measurement = tokenMeter.measure(agent.session, header)
|
|
104
|
+
if (measurement.totalTokens < thresholdTokens) return
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (let attempt = 0; attempt <= 1; attempt += 1) {
|
|
108
|
+
const range = selectSmallWindowRange(agent.session, measurement, retainTokens)
|
|
109
|
+
if (range === null) {
|
|
110
|
+
if (requireBelowThreshold) throw new Error('no safe compaction range can reduce context below small-window threshold')
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
await compaction.compactRegion(range.start, range.end, agent, signal)
|
|
114
|
+
measurement = tokenMeter.measure(agent.session, header)
|
|
115
|
+
if (measurement.totalTokens < thresholdTokens) return
|
|
116
|
+
}
|
|
117
|
+
if (requireBelowThreshold) throw new Error('compaction still above small-window threshold')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Bridge pre-step and model-switch compaction for small GPT windows under BasicCompactionEngine. */
|
|
121
|
+
export function installSmallWindowCompaction(
|
|
122
|
+
ctx: Context,
|
|
123
|
+
currentSettings: () => CodexSettings,
|
|
124
|
+
lastRequestByAgent: WeakMap<object, unknown>,
|
|
125
|
+
): void {
|
|
126
|
+
ctx.on('agent/pre-step', (async ({ agent, signal }: { agent: AgentLike; signal: AbortSignal }, next: () => Promise<unknown>) => {
|
|
127
|
+
if (!signal.aborted) {
|
|
128
|
+
try {
|
|
129
|
+
const header = agent.session.requestHeader()
|
|
130
|
+
if (header !== undefined) await compactSmallWindowIfNeeded(ctx, agent, header, signal, currentSettings, false)
|
|
131
|
+
} catch (error) {
|
|
132
|
+
(ctx.logger as { warn?: (value: unknown) => void } | undefined)?.warn?.(error)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return next()
|
|
136
|
+
}) as never, { prepend: true } as never)
|
|
137
|
+
|
|
138
|
+
ctx.on('agent/request', (async (payload: { agent?: AgentLike; signal?: AbortSignal }, next: () => Promise<unknown>) => {
|
|
139
|
+
try {
|
|
140
|
+
return await next()
|
|
141
|
+
} catch (error) {
|
|
142
|
+
const code = (error as { code?: unknown } | undefined)?.code
|
|
143
|
+
const causeText = String((error as { cause?: unknown } | undefined)?.cause ?? error)
|
|
144
|
+
const agent = payload.agent
|
|
145
|
+
const resolvedConfig = agent !== undefined && typeof agent === 'object' ? lastRequestByAgent.get(agent) : undefined
|
|
146
|
+
if (!payload.signal?.aborted
|
|
147
|
+
&& code === 'MODEL_SWITCH_COMPACTION_FAILED'
|
|
148
|
+
&& causeText.includes('headroom tokens')
|
|
149
|
+
&& agent !== undefined
|
|
150
|
+
&& resolvedConfig !== undefined
|
|
151
|
+
&& payload.signal !== undefined) {
|
|
152
|
+
const previous = agent.session.requestHeader()
|
|
153
|
+
await compactSmallWindowIfNeeded(
|
|
154
|
+
ctx,
|
|
155
|
+
agent,
|
|
156
|
+
{ ...previous, config: resolvedConfig as Record<string, unknown> },
|
|
157
|
+
payload.signal,
|
|
158
|
+
currentSettings,
|
|
159
|
+
true,
|
|
160
|
+
)
|
|
161
|
+
return resolvedConfig
|
|
162
|
+
}
|
|
163
|
+
throw error
|
|
164
|
+
}
|
|
165
|
+
}) as never, { prepend: true } as never)
|
|
166
|
+
}
|