@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,416 @@
|
|
|
1
|
+
import { ManualCompactionError } from "@deepseek-ai/dsh-compaction";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
|
|
5
|
+
//#region lib/types/contracts/ui-contracts.js
|
|
6
|
+
const CODEX_CONTEXT_MAX = 1e6;
|
|
7
|
+
const OPENAI_CODEX_SETTINGS_NAMESPACE = "llm-openai-codex";
|
|
8
|
+
//#endregion
|
|
9
|
+
//#region lib/types/contracts/prompt.js
|
|
10
|
+
/** Default plugin-owned Codex operating prompt. */
|
|
11
|
+
const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
|
|
12
|
+
|
|
13
|
+
- Follow the current tool catalog, not assumptions from another Codex client. For unknown paths, use the available list/search tools instead of guessing and reuse the returned paths. If only shell search is available, prefer rg or rg --files.
|
|
14
|
+
|
|
15
|
+
## Editing constraints
|
|
16
|
+
|
|
17
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
18
|
+
- Prefer apply_patch (or dedicated file tools when present) over shell heredocs or redirection for file edits; do not re-read a file immediately after apply_patch succeeds unless checking external changes.
|
|
19
|
+
- Add succinct code comments that explain non-obvious code. Do not add comments that merely narrate assignments or control flow.
|
|
20
|
+
- You may be in a dirty git worktree. Never revert existing changes you did not make unless the user explicitly requests it, never amend commits unless asked, and avoid interactive git commands such as git rebase -i or git add -p. If unrelated files are changed, leave them alone.
|
|
21
|
+
|
|
22
|
+
## Planning
|
|
23
|
+
|
|
24
|
+
- Use update_plan for work with multiple meaningful steps. Keep the plan current as the task progresses.
|
|
25
|
+
- Do not use a plan for a trivial one-step request.
|
|
26
|
+
|
|
27
|
+
## dsh session
|
|
28
|
+
|
|
29
|
+
- The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
|
|
30
|
+
- For Harness APIs, first load the relevant Harness skill. When Inspect tools are available, start with cordis_inspect_list, then query the provider's directory before an exact Service contract. Reuse returned names; Inspect is read-only.
|
|
31
|
+
- A not-found path or unknown Service is a discovery error: check the file list or Service directory before retrying. Preserve actual failures; do not hide them or bypass permission denials.
|
|
32
|
+
|
|
33
|
+
## Task execution
|
|
34
|
+
|
|
35
|
+
- Parallelize independent read, search, and check calls. Do not sleep-poll background jobs or subagents; they wake on completion.
|
|
36
|
+
- When delegating parallel edits, assign disjoint write scopes. Record key paths and facts as you go since older large tool outputs may be pruned.
|
|
37
|
+
- Never claim unrun checks passed, and keep the user informed with concise progress updates.
|
|
38
|
+
|
|
39
|
+
## Presenting your work
|
|
40
|
+
|
|
41
|
+
- Be concise, direct, friendly, and actionable, and lead with the result.
|
|
42
|
+
- For substantial work, explain what changed and why, then briefly note how the work was verified and what comes next.
|
|
43
|
+
- For code reviews, lead with concrete findings ordered by severity with file and line references before any brief summary, or state explicitly if no issues were found.
|
|
44
|
+
- Do not dump large files into the conversation; refer to their paths.
|
|
45
|
+
- Use plain text with short sections only when they improve scanability.
|
|
46
|
+
|
|
47
|
+
## Working principles
|
|
48
|
+
|
|
49
|
+
- Actively establish the user's current context from the repository rather than relying on stale assumptions. Execute tasks directly through implementation and verification using the clearest, most effective path; ask the user only when a user-owned choice or external/destructive action cannot be resolved by inspection.
|
|
50
|
+
- Keep only the essential logic and core actions. Don't explain or test what was removed or why something wasn't done, especially when writing documentation or communicating. Convey enough valuable information with as few words as possible.
|
|
51
|
+
- Solve problems by thinking from first principles and at a higher level.
|
|
52
|
+
`;
|
|
53
|
+
/** Default deployment Persona template used by the Codex preset. */
|
|
54
|
+
const DEFAULT_CODEX_PERSONA = String.raw`You are Codex, a coding agent based on the {{model}} model.`;
|
|
55
|
+
/** Default DSH Core source-checkout guidance template. */
|
|
56
|
+
const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. If the supplied path is inside app.asar, treat it as a packaged runtime rather than a source checkout. Discover the installed packageDir via Inspect and read its README and package.json exports; do not assume src or individual lib/types filenames exist. Use Host file-read tools for app.asar; native shell search and glob cannot traverse it.`;
|
|
57
|
+
/** Default DSH Web runtime guidance template. */
|
|
58
|
+
const DEFAULT_DSH_CORE_WEB_PROMPT = [
|
|
59
|
+
"You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}.",
|
|
60
|
+
"When the user refers to \"this page\", \"this GUI\", or \"this app\" without naming another target, they mean this GUI.",
|
|
61
|
+
"The browser provides no implicit DOM, route, or screenshot context.",
|
|
62
|
+
"The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates.",
|
|
63
|
+
"Every other change - the apps/web shell and plain packages - requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh.",
|
|
64
|
+
"Starting another server does not update this GUI.",
|
|
65
|
+
"The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__.",
|
|
66
|
+
"Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL."
|
|
67
|
+
].join(" ");
|
|
68
|
+
//#endregion
|
|
69
|
+
//#region lib/types/contracts/settings.js
|
|
70
|
+
/** Shared host-side Codex settings contract, Host reader, and GPT route matcher. */
|
|
71
|
+
/** Live Codex controls shared by the Web UI and agent layer. */
|
|
72
|
+
const CODEX_SETTINGS_NAMESPACE = "codex";
|
|
73
|
+
z.object({
|
|
74
|
+
fast: z.boolean().default(false),
|
|
75
|
+
fastModeControlEnabled: z.boolean().default(true),
|
|
76
|
+
contextWindowControlEnabled: z.boolean().default(true),
|
|
77
|
+
contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX).hidden(),
|
|
78
|
+
persona: z.string().default(DEFAULT_CODEX_PERSONA),
|
|
79
|
+
harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
80
|
+
webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
|
|
81
|
+
systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
|
|
82
|
+
promptEnabled: z.boolean().default(true),
|
|
83
|
+
terminalToolsEnabled: z.boolean().default(true).hidden(),
|
|
84
|
+
patchToolEnabled: z.boolean().default(true).hidden(),
|
|
85
|
+
planToolEnabled: z.boolean().default(true).hidden(),
|
|
86
|
+
hostedWebSearchEnabled: z.boolean().default(true),
|
|
87
|
+
remoteCompactionEnabled: z.boolean().default(true),
|
|
88
|
+
activityIndicatorEnabled: z.boolean().default(true)
|
|
89
|
+
});
|
|
90
|
+
/** Host-only reads: never expose the unredacted provider configuration to clients. */
|
|
91
|
+
function readHostSettings(ctx, namespace) {
|
|
92
|
+
if (namespace === "codex") {
|
|
93
|
+
const preferences = ctx.get("codexPreferences");
|
|
94
|
+
if (preferences !== void 0) return preferences.current();
|
|
95
|
+
}
|
|
96
|
+
return ctx.get("settings")?.describe?.().find((row) => row.ns === namespace)?.value;
|
|
97
|
+
}
|
|
98
|
+
/** Match GPT / ChatGPT model ids that consume Codex wire & capacity extensions. */
|
|
99
|
+
function isGptModel(model) {
|
|
100
|
+
return typeof model === "string" && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region lib/types/entries/compaction.js
|
|
104
|
+
/** Codex compaction backend that honors the latest durable request capacity. */
|
|
105
|
+
/**
|
|
106
|
+
* The main plugin entry and the compact-command subpath can be evaluated as
|
|
107
|
+
* separate bundles. Keep their async context carrier on the process global so
|
|
108
|
+
* an explicit command mode reaches the global llm/stream listener.
|
|
109
|
+
*/
|
|
110
|
+
const COMPACTION_MODE_KEY = Symbol.for("shuind.dsh-codex-harness.compaction-mode");
|
|
111
|
+
const COMPACTION_MODE = (() => {
|
|
112
|
+
const registry = globalThis;
|
|
113
|
+
const existing = registry[COMPACTION_MODE_KEY];
|
|
114
|
+
if (existing !== void 0) return existing;
|
|
115
|
+
const storage = new AsyncLocalStorage();
|
|
116
|
+
registry[COMPACTION_MODE_KEY] = storage;
|
|
117
|
+
return storage;
|
|
118
|
+
})();
|
|
119
|
+
/** Run one manual compaction with an explicit local/remote preference. */
|
|
120
|
+
function runCodexCompactionMode(mode, task) {
|
|
121
|
+
return COMPACTION_MODE.run(mode, task);
|
|
122
|
+
}
|
|
123
|
+
/** Read the explicit preference for the current compaction stream, if any. */
|
|
124
|
+
function codexCompactionMode() {
|
|
125
|
+
return COMPACTION_MODE.getStore();
|
|
126
|
+
}
|
|
127
|
+
/** Read the live Codex capacity without requiring a custom LLM service API. */
|
|
128
|
+
function configuredContextWindow(ctx) {
|
|
129
|
+
const settings = ctx.get("settings");
|
|
130
|
+
const preferences = ctx.get("codexPreferences");
|
|
131
|
+
if (settings?.describe === void 0 && preferences?.current === void 0) return { available: false };
|
|
132
|
+
const value = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE);
|
|
133
|
+
return {
|
|
134
|
+
available: true,
|
|
135
|
+
...value?.contextWindow !== void 0 && Number.isSafeInteger(value.contextWindow) && value.contextWindow > 0 ? { value: value.contextWindow } : {}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** Read an explicit capacity persisted in the request header when settings are unavailable. */
|
|
139
|
+
function requestContextWindow(session, provider, model) {
|
|
140
|
+
const config = session.requestHeader()?.config;
|
|
141
|
+
if (config?.provider !== provider || config.model !== model) return void 0;
|
|
142
|
+
const value = config.contextWindow;
|
|
143
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
|
|
144
|
+
}
|
|
145
|
+
/** Resolve the capacity currently in force for an active Codex compaction. */
|
|
146
|
+
function activeContextWindow(ctx, activeSession, provider, model) {
|
|
147
|
+
if (provider === "openai-codex") return void 0;
|
|
148
|
+
const session = activeSession.getStore();
|
|
149
|
+
const requestContext = session?.requestContext();
|
|
150
|
+
const configured = isGptModel(model) ? configuredContextWindow(ctx) : { available: false };
|
|
151
|
+
return configured.available ? configured.value : (session === void 0 ? void 0 : requestContextWindow(session, provider, model)) ?? (requestContext?.provider === provider && requestContext.model === model ? requestContext.contextWindow : void 0);
|
|
152
|
+
}
|
|
153
|
+
const DSH_COMPACT_PROMPT_PREFIX = "You are now acting as a compaction engine";
|
|
154
|
+
/**
|
|
155
|
+
* When `/compact local` is active, neutralize DSH's exact compaction prompt
|
|
156
|
+
* prefix on a shallow clone so external adapters (`dsh-codex-connect`) fall
|
|
157
|
+
* through to local text summarization instead of firing `compaction_trigger`.
|
|
158
|
+
*/
|
|
159
|
+
function withExplicitLocalCompactionInstruction(options) {
|
|
160
|
+
if (codexCompactionMode() !== "local" || options.purpose !== "compaction" || options.messages.length === 0) return options;
|
|
161
|
+
const last = options.messages.at(-1);
|
|
162
|
+
if (last === void 0 || last.role !== "user" || "id" in last && last.id !== void 0) return options;
|
|
163
|
+
const first = last.content[0];
|
|
164
|
+
if (first === void 0 || first.type !== "text" || !first.text.startsWith(DSH_COMPACT_PROMPT_PREFIX)) return options;
|
|
165
|
+
const updatedLast = {
|
|
166
|
+
...last,
|
|
167
|
+
content: [{
|
|
168
|
+
...first,
|
|
169
|
+
text: `\n${first.text}`
|
|
170
|
+
}, ...last.content.slice(1)]
|
|
171
|
+
};
|
|
172
|
+
return {
|
|
173
|
+
...options,
|
|
174
|
+
messages: [...options.messages.slice(0, -1), updatedLast]
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/** Overlay capacity lookup and auxiliary summary requests for compaction. */
|
|
178
|
+
function withDurableContextCapacity(llm, ctx, activeSession) {
|
|
179
|
+
return new Proxy(llm, { get(target, property) {
|
|
180
|
+
if (property === "resolveModelInfo") return async (provider, model, signal) => {
|
|
181
|
+
const info = await target.resolveModelInfo(provider, model, signal);
|
|
182
|
+
const contextWindow = activeContextWindow(ctx, activeSession, provider, model);
|
|
183
|
+
if (contextWindow === void 0) return info;
|
|
184
|
+
return {
|
|
185
|
+
...info,
|
|
186
|
+
context: {
|
|
187
|
+
...info.context,
|
|
188
|
+
contextWindow
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
};
|
|
192
|
+
if (property === "stream") return (options) => {
|
|
193
|
+
const contextWindow = activeContextWindow(ctx, activeSession, options.provider, options.model);
|
|
194
|
+
const patched = withExplicitLocalCompactionInstruction(options);
|
|
195
|
+
if (contextWindow === void 0 || patched.contextWindow === contextWindow) return target.stream(patched);
|
|
196
|
+
return target.stream({
|
|
197
|
+
...patched,
|
|
198
|
+
contextWindow
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
const value = Reflect.get(target, property, target);
|
|
202
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
203
|
+
} });
|
|
204
|
+
}
|
|
205
|
+
(class extends BasicCompactionEngine {
|
|
206
|
+
static inject = BasicCompactionEngine.inject;
|
|
207
|
+
static Config = BasicCompactionEngine.Config;
|
|
208
|
+
codexSmallWindowReady = true;
|
|
209
|
+
activeSession;
|
|
210
|
+
constructor(ctx, config = {}) {
|
|
211
|
+
const activeSession = new AsyncLocalStorage();
|
|
212
|
+
const llm = ctx.get("llm");
|
|
213
|
+
if (llm === void 0) throw new Error("codex compaction requires ctx.llm");
|
|
214
|
+
const normalizedConfig = {
|
|
215
|
+
...config,
|
|
216
|
+
headroomTokens: config.headroomTokens ?? 8192,
|
|
217
|
+
maxTokens: config.maxTokens ?? config.headroomTokens ?? 65536
|
|
218
|
+
};
|
|
219
|
+
super(ctx.extend({ llm: withDurableContextCapacity(llm, ctx, activeSession) }), normalizedConfig);
|
|
220
|
+
this.activeSession = activeSession;
|
|
221
|
+
}
|
|
222
|
+
compactIfNeeded(agent, trigger, signal) {
|
|
223
|
+
return this.activeSession.run(agent.session, () => super.compactIfNeeded(agent, trigger, signal));
|
|
224
|
+
}
|
|
225
|
+
compactRegion(...args) {
|
|
226
|
+
return this.activeSession.run(args[2].session, () => super.compactRegion(...args));
|
|
227
|
+
}
|
|
228
|
+
compactNow(agent, signal, sourceCommandId) {
|
|
229
|
+
return this.activeSession.run(agent.session, () => super.compactNow(agent, signal, sourceCommandId));
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region lib/types/entries/compact-command.js
|
|
234
|
+
/** Codex-aware `/compact` command with an optional transport preference. */
|
|
235
|
+
const USAGE = "Usage: /compact [remote|local]";
|
|
236
|
+
/** Convert expected backend failures into the same concise command results as DSH Core. */
|
|
237
|
+
function expectedFailure(error) {
|
|
238
|
+
switch (error.code) {
|
|
239
|
+
case "busy": return {
|
|
240
|
+
kind: "error",
|
|
241
|
+
text: "Compaction is unavailable because this process has an active compaction, or the agent is not idle."
|
|
242
|
+
};
|
|
243
|
+
case "cancelled": return {
|
|
244
|
+
kind: "error",
|
|
245
|
+
text: "Compaction cancelled."
|
|
246
|
+
};
|
|
247
|
+
case "changed": return {
|
|
248
|
+
kind: "error",
|
|
249
|
+
text: "Compaction could not replace the selected history because it changed. The conversation is unchanged."
|
|
250
|
+
};
|
|
251
|
+
case "summary": return {
|
|
252
|
+
kind: "error",
|
|
253
|
+
text: "Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log."
|
|
254
|
+
};
|
|
255
|
+
case "commit": return {
|
|
256
|
+
kind: "error",
|
|
257
|
+
text: "Compaction did not finish cleanly; inspect the current session state before retrying."
|
|
258
|
+
};
|
|
259
|
+
case "persistence": return {
|
|
260
|
+
kind: "error",
|
|
261
|
+
text: "Compaction finished, but the session could not be saved."
|
|
262
|
+
};
|
|
263
|
+
default: return {
|
|
264
|
+
kind: "error",
|
|
265
|
+
text: `Unknown compaction failure: ${String(error.code)}`
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function modeOf(rawInput) {
|
|
270
|
+
const value = rawInput.trim().toLowerCase();
|
|
271
|
+
if (value === "") return void 0;
|
|
272
|
+
if (value === "remote" || value === "local") return value;
|
|
273
|
+
return "invalid";
|
|
274
|
+
}
|
|
275
|
+
function resolveCompactionService(hostCtx, agent) {
|
|
276
|
+
const fromPreset = hostCtx.get?.("agentPresets")?.serviceFor?.(agent, "compaction");
|
|
277
|
+
if (fromPreset?.compactNow !== void 0) return fromPreset;
|
|
278
|
+
const fromAgent = agent.ctx?.get?.("compaction");
|
|
279
|
+
if (fromAgent?.compactNow !== void 0) return fromAgent;
|
|
280
|
+
const fromHost = hostCtx.get?.("compaction") ?? hostCtx.compaction;
|
|
281
|
+
return fromHost?.compactNow !== void 0 ? fromHost : void 0;
|
|
282
|
+
}
|
|
283
|
+
function needsCodexConnectRemoteHint(hostCtx, agent, mode) {
|
|
284
|
+
if (mode !== "remote") return false;
|
|
285
|
+
const agentRef = agent;
|
|
286
|
+
if ((agentRef.session?.requestHeader?.()?.config?.provider ?? agentRef.model?.current?.()?.provider) !== "openai-codex") return false;
|
|
287
|
+
const descriptors = hostCtx.get?.("settings")?.describe?.();
|
|
288
|
+
if (descriptors === void 0 || !descriptors.some((d) => d.ns === "llm-openai-codex")) return false;
|
|
289
|
+
return readHostSettings(hostCtx, OPENAI_CODEX_SETTINGS_NAMESPACE)?.enableNativeCompaction !== true;
|
|
290
|
+
}
|
|
291
|
+
async function ensureCodexConnectRemoteCompaction(hostCtx, agent, mode) {
|
|
292
|
+
if (!needsCodexConnectRemoteHint(hostCtx, agent, mode)) return false;
|
|
293
|
+
const settings = hostCtx.get?.("settings");
|
|
294
|
+
if (typeof settings?.update !== "function") return true;
|
|
295
|
+
try {
|
|
296
|
+
await settings.update(OPENAI_CODEX_SETTINGS_NAMESPACE, { enableNativeCompaction: true });
|
|
297
|
+
return needsCodexConnectRemoteHint(hostCtx, agent, mode);
|
|
298
|
+
} catch {
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async function executeCompact(hostCtx, invocation) {
|
|
303
|
+
const mode = modeOf(invocation.rawInput);
|
|
304
|
+
if (mode === "invalid") return {
|
|
305
|
+
kind: "error",
|
|
306
|
+
text: USAGE
|
|
307
|
+
};
|
|
308
|
+
const compaction = resolveCompactionService(hostCtx, invocation.agent);
|
|
309
|
+
if (compaction === void 0) return {
|
|
310
|
+
kind: "error",
|
|
311
|
+
text: "Compaction is unavailable because no compaction service is configured for this session."
|
|
312
|
+
};
|
|
313
|
+
const needsHint = await ensureCodexConnectRemoteCompaction(hostCtx, invocation.agent, mode);
|
|
314
|
+
const compact = () => compaction.compactNow(invocation.agent, invocation.signal, invocation.commandId);
|
|
315
|
+
try {
|
|
316
|
+
const result = mode === void 0 ? await compact() : await runCodexCompactionMode(mode, compact);
|
|
317
|
+
if (result === null) return {
|
|
318
|
+
kind: "success",
|
|
319
|
+
text: "No compactable history yet."
|
|
320
|
+
};
|
|
321
|
+
const suffix = needsHint ? "; enable Native Compaction in Codex Connect settings for remote mode" : "";
|
|
322
|
+
return {
|
|
323
|
+
kind: "success",
|
|
324
|
+
text: `Compacted ${result.shadowedSeqs.length} history items (~${result.shadowedTokenCount} tokens${suffix}).`,
|
|
325
|
+
sourceEventSeq: result.summarySeq
|
|
326
|
+
};
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (invocation.signal.aborted) return {
|
|
329
|
+
kind: "error",
|
|
330
|
+
text: "Compaction cancelled."
|
|
331
|
+
};
|
|
332
|
+
if (error instanceof ManualCompactionError) return expectedFailure(error);
|
|
333
|
+
throw error;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
function createCompactDefinition(hostCtx, active) {
|
|
337
|
+
const handler = (invocation) => {
|
|
338
|
+
const operation = executeCompact(hostCtx, invocation);
|
|
339
|
+
active.add(operation);
|
|
340
|
+
const retire = () => {
|
|
341
|
+
active.delete(operation);
|
|
342
|
+
};
|
|
343
|
+
operation.then(retire, retire);
|
|
344
|
+
return operation;
|
|
345
|
+
};
|
|
346
|
+
return {
|
|
347
|
+
name: "compact",
|
|
348
|
+
description: "Compact older conversation history, optionally using remote or local mode",
|
|
349
|
+
input: { hint: "[remote|local]" },
|
|
350
|
+
handler
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
function mountPerAgentCommands(commandsCtx) {
|
|
354
|
+
const active = /* @__PURE__ */ new Set();
|
|
355
|
+
const disposers = /* @__PURE__ */ new Map();
|
|
356
|
+
const definition = createCompactDefinition(commandsCtx, active);
|
|
357
|
+
const attach = (agent) => {
|
|
358
|
+
if (agent === void 0 || typeof agent !== "object" || disposers.has(agent)) return;
|
|
359
|
+
const agentCommands = agent.ctx?.get?.("commands");
|
|
360
|
+
if (agentCommands?.register === void 0) return;
|
|
361
|
+
disposers.set(agent, agentCommands.register(definition));
|
|
362
|
+
};
|
|
363
|
+
const existing = commandsCtx.get?.("agents")?.list?.() ?? [];
|
|
364
|
+
for (const agent of existing) attach(agent);
|
|
365
|
+
const offCreated = commandsCtx.on("agent/created", (({ agent }) => {
|
|
366
|
+
attach(agent);
|
|
367
|
+
}));
|
|
368
|
+
const offDisposed = commandsCtx.on("agent/disposed", (({ agent }) => {
|
|
369
|
+
const off = disposers.get(agent);
|
|
370
|
+
disposers.delete(agent);
|
|
371
|
+
off?.();
|
|
372
|
+
}));
|
|
373
|
+
return async () => {
|
|
374
|
+
offCreated?.();
|
|
375
|
+
offDisposed?.();
|
|
376
|
+
for (const off of disposers.values()) off();
|
|
377
|
+
disposers.clear();
|
|
378
|
+
await Promise.allSettled(active);
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
/** Register `/compact [remote|local]` on each live and future Agent scope across all presets. */
|
|
382
|
+
function installGlobalCompactCommand(ctx) {
|
|
383
|
+
if (typeof ctx.on !== "function") return;
|
|
384
|
+
if (typeof ctx.inject === "function") {
|
|
385
|
+
ctx.inject(["commands"], ((commandsCtx) => {
|
|
386
|
+
const cleanup = mountPerAgentCommands(commandsCtx);
|
|
387
|
+
commandsCtx.effect?.(() => cleanup, "codex: per-agent /compact command");
|
|
388
|
+
}));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (ctx.get?.("commands") !== void 0) {
|
|
392
|
+
const cleanup = mountPerAgentCommands(ctx);
|
|
393
|
+
ctx.effect?.(() => cleanup, "codex: per-agent /compact command");
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/** Replace the Core command inside the Codex compaction scope. */
|
|
397
|
+
function apply(ctx) {
|
|
398
|
+
const commands = ctx.commands;
|
|
399
|
+
const active = /* @__PURE__ */ new Set();
|
|
400
|
+
const definition = createCompactDefinition(ctx, active);
|
|
401
|
+
ctx.effect(function* () {
|
|
402
|
+
yield async () => {
|
|
403
|
+
await Promise.allSettled(active);
|
|
404
|
+
};
|
|
405
|
+
yield commands.register(definition);
|
|
406
|
+
}, "codex compact command lifecycle");
|
|
407
|
+
}
|
|
408
|
+
const name = "compact-command";
|
|
409
|
+
const inject = ["commands", "compaction"];
|
|
410
|
+
var compact_command_default = {
|
|
411
|
+
name,
|
|
412
|
+
inject,
|
|
413
|
+
apply
|
|
414
|
+
};
|
|
415
|
+
//#endregion
|
|
416
|
+
export { apply, compact_command_default as default, inject, installGlobalCompactCommand, name };
|
package/lib/compaction.js
CHANGED
|
@@ -1,6 +1,104 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
|
|
3
|
-
|
|
3
|
+
import z from "@deepseek-ai/schemastery";
|
|
4
|
+
//#region lib/types/contracts/ui-contracts.js
|
|
5
|
+
const CODEX_CONTEXT_MAX = 1e6;
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region lib/types/contracts/prompt.js
|
|
8
|
+
/** Default plugin-owned Codex operating prompt. */
|
|
9
|
+
const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
|
|
10
|
+
|
|
11
|
+
- Follow the current tool catalog, not assumptions from another Codex client. For unknown paths, use the available list/search tools instead of guessing and reuse the returned paths. If only shell search is available, prefer rg or rg --files.
|
|
12
|
+
|
|
13
|
+
## Editing constraints
|
|
14
|
+
|
|
15
|
+
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
|
16
|
+
- Prefer apply_patch (or dedicated file tools when present) over shell heredocs or redirection for file edits; do not re-read a file immediately after apply_patch succeeds unless checking external changes.
|
|
17
|
+
- Add succinct code comments that explain non-obvious code. Do not add comments that merely narrate assignments or control flow.
|
|
18
|
+
- You may be in a dirty git worktree. Never revert existing changes you did not make unless the user explicitly requests it, never amend commits unless asked, and avoid interactive git commands such as git rebase -i or git add -p. If unrelated files are changed, leave them alone.
|
|
19
|
+
|
|
20
|
+
## Planning
|
|
21
|
+
|
|
22
|
+
- Use update_plan for work with multiple meaningful steps. Keep the plan current as the task progresses.
|
|
23
|
+
- Do not use a plan for a trivial one-step request.
|
|
24
|
+
|
|
25
|
+
## dsh session
|
|
26
|
+
|
|
27
|
+
- The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
|
|
28
|
+
- For Harness APIs, first load the relevant Harness skill. When Inspect tools are available, start with cordis_inspect_list, then query the provider's directory before an exact Service contract. Reuse returned names; Inspect is read-only.
|
|
29
|
+
- A not-found path or unknown Service is a discovery error: check the file list or Service directory before retrying. Preserve actual failures; do not hide them or bypass permission denials.
|
|
30
|
+
|
|
31
|
+
## Task execution
|
|
32
|
+
|
|
33
|
+
- Parallelize independent read, search, and check calls. Do not sleep-poll background jobs or subagents; they wake on completion.
|
|
34
|
+
- When delegating parallel edits, assign disjoint write scopes. Record key paths and facts as you go since older large tool outputs may be pruned.
|
|
35
|
+
- Never claim unrun checks passed, and keep the user informed with concise progress updates.
|
|
36
|
+
|
|
37
|
+
## Presenting your work
|
|
38
|
+
|
|
39
|
+
- Be concise, direct, friendly, and actionable, and lead with the result.
|
|
40
|
+
- For substantial work, explain what changed and why, then briefly note how the work was verified and what comes next.
|
|
41
|
+
- For code reviews, lead with concrete findings ordered by severity with file and line references before any brief summary, or state explicitly if no issues were found.
|
|
42
|
+
- Do not dump large files into the conversation; refer to their paths.
|
|
43
|
+
- Use plain text with short sections only when they improve scanability.
|
|
44
|
+
|
|
45
|
+
## Working principles
|
|
46
|
+
|
|
47
|
+
- Actively establish the user's current context from the repository rather than relying on stale assumptions. Execute tasks directly through implementation and verification using the clearest, most effective path; ask the user only when a user-owned choice or external/destructive action cannot be resolved by inspection.
|
|
48
|
+
- Keep only the essential logic and core actions. Don't explain or test what was removed or why something wasn't done, especially when writing documentation or communicating. Convey enough valuable information with as few words as possible.
|
|
49
|
+
- Solve problems by thinking from first principles and at a higher level.
|
|
50
|
+
`;
|
|
51
|
+
/** Default deployment Persona template used by the Codex preset. */
|
|
52
|
+
const DEFAULT_CODEX_PERSONA = String.raw`You are Codex, a coding agent based on the {{model}} model.`;
|
|
53
|
+
/** Default DSH Core source-checkout guidance template. */
|
|
54
|
+
const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. If the supplied path is inside app.asar, treat it as a packaged runtime rather than a source checkout. Discover the installed packageDir via Inspect and read its README and package.json exports; do not assume src or individual lib/types filenames exist. Use Host file-read tools for app.asar; native shell search and glob cannot traverse it.`;
|
|
55
|
+
/** Default DSH Web runtime guidance template. */
|
|
56
|
+
const DEFAULT_DSH_CORE_WEB_PROMPT = [
|
|
57
|
+
"You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}.",
|
|
58
|
+
"When the user refers to \"this page\", \"this GUI\", or \"this app\" without naming another target, they mean this GUI.",
|
|
59
|
+
"The browser provides no implicit DOM, route, or screenshot context.",
|
|
60
|
+
"The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates.",
|
|
61
|
+
"Every other change - the apps/web shell and plain packages - requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh.",
|
|
62
|
+
"Starting another server does not update this GUI.",
|
|
63
|
+
"The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__.",
|
|
64
|
+
"Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL."
|
|
65
|
+
].join(" ");
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region lib/types/contracts/settings.js
|
|
68
|
+
/** Shared host-side Codex settings contract, Host reader, and GPT route matcher. */
|
|
69
|
+
/** Live Codex controls shared by the Web UI and agent layer. */
|
|
70
|
+
const CODEX_SETTINGS_NAMESPACE = "codex";
|
|
71
|
+
z.object({
|
|
72
|
+
fast: z.boolean().default(false),
|
|
73
|
+
fastModeControlEnabled: z.boolean().default(true),
|
|
74
|
+
contextWindowControlEnabled: z.boolean().default(true),
|
|
75
|
+
contextWindow: z.number().step(1).min(1).max(CODEX_CONTEXT_MAX).hidden(),
|
|
76
|
+
persona: z.string().default(DEFAULT_CODEX_PERSONA),
|
|
77
|
+
harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
|
|
78
|
+
webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
|
|
79
|
+
systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
|
|
80
|
+
promptEnabled: z.boolean().default(true),
|
|
81
|
+
terminalToolsEnabled: z.boolean().default(true).hidden(),
|
|
82
|
+
patchToolEnabled: z.boolean().default(true).hidden(),
|
|
83
|
+
planToolEnabled: z.boolean().default(true).hidden(),
|
|
84
|
+
hostedWebSearchEnabled: z.boolean().default(true),
|
|
85
|
+
remoteCompactionEnabled: z.boolean().default(true),
|
|
86
|
+
activityIndicatorEnabled: z.boolean().default(true)
|
|
87
|
+
});
|
|
88
|
+
/** Host-only reads: never expose the unredacted provider configuration to clients. */
|
|
89
|
+
function readHostSettings(ctx, namespace) {
|
|
90
|
+
if (namespace === "codex") {
|
|
91
|
+
const preferences = ctx.get("codexPreferences");
|
|
92
|
+
if (preferences !== void 0) return preferences.current();
|
|
93
|
+
}
|
|
94
|
+
return ctx.get("settings")?.describe?.().find((row) => row.ns === namespace)?.value;
|
|
95
|
+
}
|
|
96
|
+
/** Match GPT / ChatGPT model ids that consume Codex wire & capacity extensions. */
|
|
97
|
+
function isGptModel(model) {
|
|
98
|
+
return typeof model === "string" && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region lib/types/entries/compaction.js
|
|
4
102
|
/** Codex compaction backend that honors the latest durable request capacity. */
|
|
5
103
|
/**
|
|
6
104
|
* The main plugin entry and the compact-command subpath can be evaluated as
|
|
@@ -24,16 +122,12 @@ function runCodexCompactionMode(mode, task) {
|
|
|
24
122
|
function codexCompactionMode() {
|
|
25
123
|
return COMPACTION_MODE.getStore();
|
|
26
124
|
}
|
|
27
|
-
const CODEX_SETTINGS_NAMESPACE = "codex";
|
|
28
|
-
/** Codex context overrides apply only to GPT-compatible model routes. */
|
|
29
|
-
function isGptModel(model) {
|
|
30
|
-
return /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
|
|
31
|
-
}
|
|
32
125
|
/** Read the live Codex capacity without requiring a custom LLM service API. */
|
|
33
126
|
function configuredContextWindow(ctx) {
|
|
34
127
|
const settings = ctx.get("settings");
|
|
35
|
-
|
|
36
|
-
|
|
128
|
+
const preferences = ctx.get("codexPreferences");
|
|
129
|
+
if (settings?.describe === void 0 && preferences?.current === void 0) return { available: false };
|
|
130
|
+
const value = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE);
|
|
37
131
|
return {
|
|
38
132
|
available: true,
|
|
39
133
|
...value?.contextWindow !== void 0 && Number.isSafeInteger(value.contextWindow) && value.contextWindow > 0 ? { value: value.contextWindow } : {}
|
|
@@ -48,11 +142,36 @@ function requestContextWindow(session, provider, model) {
|
|
|
48
142
|
}
|
|
49
143
|
/** Resolve the capacity currently in force for an active Codex compaction. */
|
|
50
144
|
function activeContextWindow(ctx, activeSession, provider, model) {
|
|
145
|
+
if (provider === "openai-codex") return void 0;
|
|
51
146
|
const session = activeSession.getStore();
|
|
52
147
|
const requestContext = session?.requestContext();
|
|
53
148
|
const configured = isGptModel(model) ? configuredContextWindow(ctx) : { available: false };
|
|
54
149
|
return configured.available ? configured.value : (session === void 0 ? void 0 : requestContextWindow(session, provider, model)) ?? (requestContext?.provider === provider && requestContext.model === model ? requestContext.contextWindow : void 0);
|
|
55
150
|
}
|
|
151
|
+
const DSH_COMPACT_PROMPT_PREFIX = "You are now acting as a compaction engine";
|
|
152
|
+
/**
|
|
153
|
+
* When `/compact local` is active, neutralize DSH's exact compaction prompt
|
|
154
|
+
* prefix on a shallow clone so external adapters (`dsh-codex-connect`) fall
|
|
155
|
+
* through to local text summarization instead of firing `compaction_trigger`.
|
|
156
|
+
*/
|
|
157
|
+
function withExplicitLocalCompactionInstruction(options) {
|
|
158
|
+
if (codexCompactionMode() !== "local" || options.purpose !== "compaction" || options.messages.length === 0) return options;
|
|
159
|
+
const last = options.messages.at(-1);
|
|
160
|
+
if (last === void 0 || last.role !== "user" || "id" in last && last.id !== void 0) return options;
|
|
161
|
+
const first = last.content[0];
|
|
162
|
+
if (first === void 0 || first.type !== "text" || !first.text.startsWith(DSH_COMPACT_PROMPT_PREFIX)) return options;
|
|
163
|
+
const updatedLast = {
|
|
164
|
+
...last,
|
|
165
|
+
content: [{
|
|
166
|
+
...first,
|
|
167
|
+
text: `\n${first.text}`
|
|
168
|
+
}, ...last.content.slice(1)]
|
|
169
|
+
};
|
|
170
|
+
return {
|
|
171
|
+
...options,
|
|
172
|
+
messages: [...options.messages.slice(0, -1), updatedLast]
|
|
173
|
+
};
|
|
174
|
+
}
|
|
56
175
|
/** Overlay capacity lookup and auxiliary summary requests for compaction. */
|
|
57
176
|
function withDurableContextCapacity(llm, ctx, activeSession) {
|
|
58
177
|
return new Proxy(llm, { get(target, property) {
|
|
@@ -70,9 +189,10 @@ function withDurableContextCapacity(llm, ctx, activeSession) {
|
|
|
70
189
|
};
|
|
71
190
|
if (property === "stream") return (options) => {
|
|
72
191
|
const contextWindow = activeContextWindow(ctx, activeSession, options.provider, options.model);
|
|
73
|
-
|
|
192
|
+
const patched = withExplicitLocalCompactionInstruction(options);
|
|
193
|
+
if (contextWindow === void 0 || patched.contextWindow === contextWindow) return target.stream(patched);
|
|
74
194
|
return target.stream({
|
|
75
|
-
...
|
|
195
|
+
...patched,
|
|
76
196
|
contextWindow
|
|
77
197
|
});
|
|
78
198
|
};
|
|
@@ -88,20 +208,29 @@ function withDurableContextCapacity(llm, ctx, activeSession) {
|
|
|
88
208
|
var CodexCompactionEngine = class extends BasicCompactionEngine {
|
|
89
209
|
static inject = BasicCompactionEngine.inject;
|
|
90
210
|
static Config = BasicCompactionEngine.Config;
|
|
211
|
+
codexSmallWindowReady = true;
|
|
91
212
|
activeSession;
|
|
92
213
|
constructor(ctx, config = {}) {
|
|
93
214
|
const activeSession = new AsyncLocalStorage();
|
|
94
215
|
const llm = ctx.get("llm");
|
|
95
216
|
if (llm === void 0) throw new Error("codex compaction requires ctx.llm");
|
|
96
|
-
|
|
217
|
+
const normalizedConfig = {
|
|
218
|
+
...config,
|
|
219
|
+
headroomTokens: config.headroomTokens ?? 8192,
|
|
220
|
+
maxTokens: config.maxTokens ?? config.headroomTokens ?? 65536
|
|
221
|
+
};
|
|
222
|
+
super(ctx.extend({ llm: withDurableContextCapacity(llm, ctx, activeSession) }), normalizedConfig);
|
|
97
223
|
this.activeSession = activeSession;
|
|
98
224
|
}
|
|
99
225
|
compactIfNeeded(agent, trigger, signal) {
|
|
100
226
|
return this.activeSession.run(agent.session, () => super.compactIfNeeded(agent, trigger, signal));
|
|
101
227
|
}
|
|
228
|
+
compactRegion(...args) {
|
|
229
|
+
return this.activeSession.run(args[2].session, () => super.compactRegion(...args));
|
|
230
|
+
}
|
|
102
231
|
compactNow(agent, signal, sourceCommandId) {
|
|
103
232
|
return this.activeSession.run(agent.session, () => super.compactNow(agent, signal, sourceCommandId));
|
|
104
233
|
}
|
|
105
234
|
};
|
|
106
235
|
//#endregion
|
|
107
|
-
export { codexCompactionMode, CodexCompactionEngine as default, runCodexCompactionMode };
|
|
236
|
+
export { codexCompactionMode, CodexCompactionEngine as default, runCodexCompactionMode, withExplicitLocalCompactionInstruction };
|