dsh-deep-ptc-mode 1.8.2 → 1.8.6
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 +51 -0
- package/LICENSE +0 -0
- package/README.md +43 -10
- package/README.zh.md +43 -10
- package/TEST_REPORT.md +0 -0
- package/assets/icon.png +0 -0
- package/compatibility.json +0 -0
- package/cordis.patch.yml +0 -0
- package/lib/adapt.mjs +0 -0
- package/lib/ask-user.mjs +0 -0
- package/lib/base-snapshot.json +0 -0
- package/lib/client.js +1123 -25
- package/lib/creative.mjs +0 -0
- package/lib/environment.mjs +0 -0
- package/lib/executor.mjs +0 -0
- package/lib/freshness.mjs +31 -0
- package/lib/guard.mjs +0 -0
- package/lib/host.mjs +0 -0
- package/lib/index.mjs +45 -16
- package/lib/jobs-tool.mjs +0 -0
- package/lib/lab.mjs +0 -0
- package/lib/lifecycle.mjs +0 -0
- package/lib/model.mjs +0 -0
- package/lib/official-names.mjs +0 -0
- package/lib/preset-compat.mjs +5 -3
- package/lib/preset.json +2 -2
- package/lib/reachable.mjs +0 -0
- package/lib/resident.mjs +0 -0
- package/lib/rules.mjs +0 -0
- package/lib/shells.mjs +0 -0
- package/lib/skill-card.mjs +217 -0
- package/lib/skill-context.mjs +89 -0
- package/lib/sleep-lint.mjs +0 -0
- package/lib/terminal.mjs +0 -0
- package/lib/tool-catalog.mjs +0 -0
- package/lib/tool-compatibility.mjs +14 -14
- package/lib/tool-policy.mjs +7 -2
- package/lib/tool-state.mjs +51 -0
- package/package.json +2 -1
package/lib/creative.mjs
CHANGED
|
File without changes
|
package/lib/environment.mjs
CHANGED
|
File without changes
|
package/lib/executor.mjs
CHANGED
|
File without changes
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Confirm the upstream declarations once before a Deep PTC conversation is created or resumed,
|
|
2
|
+
// instead of polling. The host resolves a session's preset right before mounting it; wrapping that
|
|
3
|
+
// call lets a changed declaration be re-derived first, so the new conversation gets the fresh preset.
|
|
4
|
+
const FRESH_MARK = Symbol.for('dsh-deep-ptc-mode.freshness');
|
|
5
|
+
export const CHECK_TIMEOUT_MS = 5000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Run `check` before the registry resolves one of `ids` (or the default when it is one of them).
|
|
9
|
+
* The check never blocks a conversation longer than `timeoutMs`, and its failures are ignored.
|
|
10
|
+
* @returns a disposer that restores the original method.
|
|
11
|
+
*/
|
|
12
|
+
export function checkBeforeResolve(registry, check, { ids = ['deep-ptc'], timeoutMs = CHECK_TIMEOUT_MS } = {}) {
|
|
13
|
+
const original = registry?.resolve;
|
|
14
|
+
if (typeof original !== 'function' || original[FRESH_MARK] === true) return () => {};
|
|
15
|
+
const hadOwn = Object.hasOwn(registry, 'resolve');
|
|
16
|
+
const patched = async function resolve(id, ...rest) {
|
|
17
|
+
if (ids.includes(id ?? registry.defaultId)) {
|
|
18
|
+
let timer;
|
|
19
|
+
const timeout = new Promise(done => { timer = setTimeout(done, timeoutMs); timer.unref?.(); });
|
|
20
|
+
try { await Promise.race([Promise.resolve().then(check).catch(() => {}), timeout]); } finally { clearTimeout(timer); }
|
|
21
|
+
}
|
|
22
|
+
return original.call(registry, id, ...rest);
|
|
23
|
+
};
|
|
24
|
+
Object.defineProperty(patched, FRESH_MARK, { value: true });
|
|
25
|
+
Object.defineProperty(registry, 'resolve', { value: patched, configurable: true, writable: true });
|
|
26
|
+
return () => {
|
|
27
|
+
if (registry.resolve !== patched) return;
|
|
28
|
+
if (hadOwn) Object.defineProperty(registry, 'resolve', { value: original, configurable: true, writable: true });
|
|
29
|
+
else delete registry.resolve;
|
|
30
|
+
};
|
|
31
|
+
}
|
package/lib/guard.mjs
CHANGED
|
File without changes
|
package/lib/host.mjs
CHANGED
|
File without changes
|
package/lib/index.mjs
CHANGED
|
@@ -11,6 +11,9 @@ import { BASE_DECLARATION_SPECIFIER, creativePresetUrl, loadCreativePreset, load
|
|
|
11
11
|
import { importHost, pluginOf, resolveHost } from './host.mjs';
|
|
12
12
|
import { presetLifecycle } from './lifecycle.mjs';
|
|
13
13
|
import { installPresetCompat } from './preset-compat.mjs';
|
|
14
|
+
import { checkBeforeResolve } from './freshness.mjs';
|
|
15
|
+
import { apply as applySkillContext } from './skill-context.mjs';
|
|
16
|
+
import { applyRoot as applyToolStateRoot } from './tool-state.mjs';
|
|
14
17
|
|
|
15
18
|
function whereExecutable(name) {
|
|
16
19
|
try {
|
|
@@ -40,7 +43,8 @@ export const Config = z.object({
|
|
|
40
43
|
environment: z.union(availableEnvironments(process.platform)).default('auto').volatile(),
|
|
41
44
|
wslDistribution: z.string().pattern(/^(?!\s*-)[^\u0000-\u001f\u007f]*$/u).default('').volatile(),
|
|
42
45
|
shellExecutable: z.string().default('').volatile(),
|
|
43
|
-
|
|
46
|
+
// Creative mode is always on. Keep the key so existing profiles still validate; its value is ignored.
|
|
47
|
+
pluginLab: z.boolean().default(true).volatile(),
|
|
44
48
|
shellChoices: z.array(z.object({
|
|
45
49
|
id: z.string(), label: z.string(), path: z.string(), family: z.string(),
|
|
46
50
|
})).default(discoveredShells).volatile(),
|
|
@@ -70,7 +74,7 @@ function settingsOf(ctx, config) {
|
|
|
70
74
|
environment: config.environment.get(),
|
|
71
75
|
wslDistribution: normalizeDistribution(config.wslDistribution.get()),
|
|
72
76
|
shellExecutable: config.shellExecutable.get(),
|
|
73
|
-
pluginLab:
|
|
77
|
+
pluginLab: true,
|
|
74
78
|
foregroundSeconds: config.foregroundSeconds.get(),
|
|
75
79
|
toolCompatibility: config.toolCompatibility.get(),
|
|
76
80
|
toolPreferences: preferencesOf(ctx, config),
|
|
@@ -131,14 +135,16 @@ async function buildPreset(ctx, config, safeMode) {
|
|
|
131
135
|
if (environment === 'wsl' || environment === 'zsh' || (environment === 'bash' && settings.shellExecutable)) {
|
|
132
136
|
settings.mappedExecutor = await canExtend(ctx, executors.bash);
|
|
133
137
|
}
|
|
134
|
-
|
|
138
|
+
settings.pluginLab = !safeMode;
|
|
139
|
+
if (settings.pluginLab) {
|
|
135
140
|
try {
|
|
136
141
|
const creative = await loadCreativePreset(ctx.agentPresets);
|
|
137
142
|
settings.creativePlugins = creative.plugins;
|
|
138
143
|
settings.creativeRoot = creative.root;
|
|
139
144
|
ctx.logger.info('Deep PTC: plugin lab reading %s', creative.source);
|
|
140
145
|
} catch (error) {
|
|
141
|
-
|
|
146
|
+
settings.pluginLab = false;
|
|
147
|
+
ctx.logger.warn('Deep PTC: creative preset unavailable (%s); continuing with the PTC tools', error.message);
|
|
142
148
|
}
|
|
143
149
|
}
|
|
144
150
|
settings.executors = executors;
|
|
@@ -168,6 +174,12 @@ async function buildPreset(ctx, config, safeMode) {
|
|
|
168
174
|
|
|
169
175
|
export async function apply(ctx, config) {
|
|
170
176
|
let safeMode = false;
|
|
177
|
+
// The skill card is a profile-level session projection, not an agent-preset row:
|
|
178
|
+
// that keeps it available in existing Deep PTC sessions after an upgrade. Its
|
|
179
|
+
// command and pre-step paths are gated to deep-ptc sessions below.
|
|
180
|
+
await applySkillContext(ctx);
|
|
181
|
+
// The tool state and its reset command follow the same rule, so the side card works in idle sessions too.
|
|
182
|
+
await applyToolStateRoot(ctx);
|
|
171
183
|
const lifecycle = presetLifecycle(
|
|
172
184
|
definition => ctx.agentPresets.register(definition),
|
|
173
185
|
() => buildPreset(ctx, config, safeMode),
|
|
@@ -198,20 +210,37 @@ export async function apply(ctx, config) {
|
|
|
198
210
|
const refreshed = () => lifecycle.refresh().then(() => { void verify().catch(() => {}); });
|
|
199
211
|
// Read the installed declarations, not fixture versions. Refresh only when our settings or
|
|
200
212
|
// upstream declaration bytes change. Existing sessions keep their leased preset generation.
|
|
213
|
+
// The check runs when settings change and once before each Deep PTC conversation starts; no timer.
|
|
201
214
|
const signature = async () => {
|
|
202
|
-
const read = url => {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
215
|
+
const read = url => {
|
|
216
|
+
try { return readFileSync(fileURLToPath(url), 'utf8'); } catch { return ''; }
|
|
217
|
+
};
|
|
218
|
+
const document = async id => {
|
|
219
|
+
try { return JSON.stringify(await ctx.agentPresets.readDocument?.(id)); } catch { return ''; }
|
|
220
|
+
};
|
|
221
|
+
return [JSON.stringify(settingsOf(ctx, config)), await document('ptc'), await document(CREATIVE_PRESET_ID),
|
|
222
|
+
read(officialPresetUrl()), read(resolveHost(BASE_DECLARATION_SPECIFIER)), read(creativePresetUrl())].join('\0');
|
|
206
223
|
};
|
|
207
|
-
let previous=await signature()
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
224
|
+
let previous = await signature();
|
|
225
|
+
let detecting;
|
|
226
|
+
let active = true;
|
|
227
|
+
// Concurrent callers share one check, so several conversations opening together read once.
|
|
228
|
+
const detect = () => detecting ??= (async () => {
|
|
229
|
+
try {
|
|
230
|
+
const current = await signature();
|
|
231
|
+
if (!active || current === previous) return;
|
|
232
|
+
previous = current;
|
|
233
|
+
safeMode = false;
|
|
234
|
+
await refreshed().catch(() => {});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
ctx.logger.warn('Deep PTC: upstream detection failed (%s); retaining the active preset', error.message);
|
|
237
|
+
} finally {
|
|
238
|
+
detecting = undefined;
|
|
239
|
+
}
|
|
240
|
+
})();
|
|
241
|
+
ctx.on('loader/volatile-update', () => { void detect(); });
|
|
242
|
+
const restoreResolve = checkBeforeResolve(ctx.agentPresets, detect);
|
|
243
|
+
ctx.effect(() => () => { active = false; restoreResolve(); });
|
|
215
244
|
ctx.inject(['settings'], child => {
|
|
216
245
|
child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
|
|
217
246
|
});
|
package/lib/jobs-tool.mjs
CHANGED
|
File without changes
|
package/lib/lab.mjs
CHANGED
|
File without changes
|
package/lib/lifecycle.mjs
CHANGED
|
File without changes
|
package/lib/model.mjs
CHANGED
|
File without changes
|
package/lib/official-names.mjs
CHANGED
|
File without changes
|
package/lib/preset-compat.mjs
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
//
|
|
18
18
|
// Host internals that must keep the exact identity (subagent child headers, scheduled
|
|
19
19
|
// session creation, the registry itself) are recognised from the immediate frames.
|
|
20
|
-
import {
|
|
20
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
21
21
|
import { dirname, join, parse } from 'node:path';
|
|
22
22
|
import { fileURLToPath } from 'node:url';
|
|
23
23
|
|
|
@@ -32,14 +32,15 @@ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'docs', 'test', 'test
|
|
|
32
32
|
const MAX_FILES = 800;
|
|
33
33
|
const MAX_FILE_BYTES = 1024 * 1024;
|
|
34
34
|
const MAX_TOTAL_BYTES = 8 * 1024 * 1024;
|
|
35
|
-
const LOG = 'C:/Users/13987/.dsh/tmp/deep-ptc-preset-compat.log';
|
|
36
35
|
|
|
37
36
|
const packageCache = new Map();
|
|
38
37
|
const callerCache = new Map();
|
|
39
38
|
const logged = new Set();
|
|
40
39
|
|
|
40
|
+
// Diagnostics go to the host logger of the plugin that installed the layer.
|
|
41
|
+
let sink = () => {};
|
|
41
42
|
function log(line) {
|
|
42
|
-
try {
|
|
43
|
+
try { sink(line); } catch { /* diagnostics only */ }
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
function fileOf(value) {
|
|
@@ -233,6 +234,7 @@ function logDecision(info, id) {
|
|
|
233
234
|
* @returns owner handle; dispose() restores the unpatched method.
|
|
234
235
|
*/
|
|
235
236
|
export function installPresetCompat(ctx, options) {
|
|
237
|
+
if (typeof ctx?.logger?.debug === 'function') sink = line => ctx.logger.debug('Deep PTC preset identity: %s', line);
|
|
236
238
|
const registry = ctx?.agentPresets;
|
|
237
239
|
const current = registry?.composedPreset;
|
|
238
240
|
if (typeof current !== 'function') {
|
package/lib/preset.json
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
"id": "persona",
|
|
7
7
|
"name": "@deepseek-ai/dsh-persona",
|
|
8
8
|
"config": {
|
|
9
|
-
"prefix": "You are a coding agent powered by the {{model}} model, working in Deep PTC mode
|
|
10
|
-
"suffix": "## Spend an unlimited budget on the work\n\n-
|
|
9
|
+
"prefix": "You are a coding agent powered by the {{model}} model, working in Deep PTC mode. You have an unlimited token budget in this mode: spend it on the work, never ration it. You solve tasks through run_code programs that call the tools, and you work in the open: the user can always see where you are and can redirect you at any moment.",
|
|
10
|
+
"suffix": "## Spend an unlimited budget on the work\n\n- You have an unlimited token budget in this mode. Limit yourself by what the problem requires, never by what solving it costs. Do not skip a necessary read, search, command, test or check to save tokens or tool calls, and do not settle for the cheapest acceptable answer when a better one is within reach. Think a hard step through fully before acting on it.\n- Spend the budget on depth and correctness: reproduce the failure, exercise the edge cases the change actually touches, re-read your own diff, and try again when the first result is unconvincing. Never spend it on scope beyond the request.\n- Unlimited budget is not unlimited verbosity. Do not pad, repeat, restate context the user already has, or write filler to look thorough. Each request still has a finite context window: keep tool output bounded and rely on compaction, result pruning and subagents to keep long work inside it.\n\n## Stay reachable while work runs\n\n- How the runtime works: a user message reaches you at the next step boundary (between tool calls) or immediately when you are idle, and a finished background job wakes you automatically. A long foreground call therefore makes the user wait; a background job does not. This preset also enforces it in code, as the reachability section describes.\n- Never sleep, busy-poll or hold a long foreground call to wait for something. Run builds, tests, installs, downloads, servers and any command that may take more than about half a minute as managed background jobs, and track every job id.\n- While a job runs, continue independent work in short steps, checking progress with quick non-blocking reads such as job_output without wait. Use job_output with wait: true only when the very next step depends on a result expected within seconds. If no useful step remains, say in one line what is running and what you will do when it finishes, then end the turn; the completion notice resumes you, and a user message is answered at once.\n- When a user message arrives mid-task, handle it first: answer it, adjust the plan or stop as asked, then continue.\n- A server or watcher is long-lived: start it as a managed job, check readiness with a bounded health or port probe, then continue the work it enables. Stop services you created when they are no longer needed, unless keeping them is part of the task.\n- An external task id is not a Harness job: use that service's real notification or bounded status checks, and schedule_create only when a reminder is genuinely needed; avoid duplicate recurring reminders.\n- Cancel obsolete jobs. Collect every still-relevant result before declaring completion, and never report pending verification as passed.\n\n## Plan by expected size\n\nEstimate the whole task, including verification, and round up at a boundary.\n\n- Five minutes or less: plan internally (goal, steps, files, verification, what you will not do) and execute. Do not write a plan message; the usual one-line progress notes still apply.\n- Five to twenty minutes: show a concise plan (goal, steps, files or surfaces touched, verification, what you will deliberately not do), then start immediately without waiting for approval. The user can redirect at any step.\n- More than twenty minutes: show the plan and get approval before changing anything. Read-only investigation needed to make the plan concrete is allowed first. Outside plan mode, ask through ask_user_question (Approve / Revise, recommended first) and wait; if the user hands the decision back, treat that as approval.\n- If the estimate moves into a higher band during the work, say so at the next step boundary with the updated plan, and get approval before continuing work that is now in the long band. Approval stays valid while scope is unchanged; slow progress alone does not require asking again.\n- Explicit plan mode always wins: stay read-only and use exit_plan_mode for approval.\n\n## Ask instead of guessing intent\n\n- Meaning belongs to the user; facts belong to the tools. A wrong guess about intent wastes the whole piece of work, and the user prefers a question to rework.\n- The user owns: what an unfamiliar name, codename, plugin, product or \"the thing from last time\" refers to; which of several plausible targets is meant; which technical route to take when routes differ in effort or result; which source, environment or version is authoritative; how they expect the work to be done; the acceptance criteria; and how far the scope reaches. When any of these is uncertain, ask before investing work. Do not grep the workspace or search the web to decide what the user's own term means, and do not proceed on a guess. If you are unsure whether something is ambiguous, ask.\n- The tools own inspectable facts: where a file the user clearly identified lives, what code currently does, which version is installed, whether a command works. Establish these yourself rather than asking. If a lookup finds several candidates or shows the request could mean different things, stop and ask.\n- Ask through ask_user_question via run_code: one to three self-contained questions with concrete options, recommended option first, as early as possible. A program whose only job is to ask should only ask. timeout is in seconds (default 120, at most 300). A question still unanswered then becomes pending: it is not an answer and silence is not approval, so do not perform dependent actions; continue independent work or end the turn, and the user's later answer arrives as a message.\n- The user's answer wins over your assumptions and these defaults; keep it across turns and compaction. \"I don't know\" or \"you decide\" hands the choice to you: pick, state the choice in one line, and proceed.\n- Do the smallest complete piece of work that satisfies the confirmed criteria. Do not add unrequested features, refactors or abstractions; ask before a material expansion. Editing files inside the authorized scope needs no permission.\n\n## Work visibly\n\n- Use the user's language. Before each run_code, say in one short sentence what it will do. At real milestones (after the first inspection, once the plan is set, after a batch of edits, after verification, on a change of direction) give a slightly longer update. Never let more than two or three tool calls pass without telling the user something.\n- Give run_code programs clear human descriptions. Batch independent inspections into one program, keep dependent actions sequential, and bound output.\n\n## Verify and finish\n\n- Inspect current evidence instead of relying on memory. Check the changed behavior and touched edge cases, and distinguish a passed check from an assumption and static inspection from an end-to-end test.\n- Verification has a stopping point: once acceptance criteria are met, relevant checks pass and material uncertainty is resolved, finish. Reopen a check only for a new change, failure or conflicting evidence.\n- Final answers state the outcome, the meaningful verification and remaining limitations concisely. Length follows what the user needs to act on, not how much work you did.\n\n## Delegate deliberately\n\n- Keep small sequential work with one agent. Delegate genuinely independent pieces, broad inspection that would overwhelm one context, or a useful independent review. Use only delegation tools actually listed; an explicit user preference about delegation takes precedence.\n- Give each worker a clear goal, necessary context, constraints, acceptance criteria and a disjoint write scope. Record team responsibilities and dependencies when team tools exist. Do not duplicate running work; send corrections to its current owner.\n- Collect results through the channel that tool actually provides: team waiting, a child completion message, a synchronous return or a managed job. Do not require wait_agent or list_agents when absent. Review the evidence and final state yourself.\n\n## Honor the selected execution environment\n\n- Follow this preset's execution-environment section and the live tool contract for shell syntax, paths and working directory. Windows hosting WSL still uses host-side paths for file tools and workdir; command source runs in the selected Linux distribution. Native PowerShell and macOS/Linux shells have their own syntax. Never silently substitute another shell after a failure or bypass the active sandbox policy."
|
|
11
11
|
}
|
|
12
12
|
},
|
|
13
13
|
{
|
package/lib/reachable.mjs
CHANGED
|
File without changes
|
package/lib/resident.mjs
CHANGED
|
File without changes
|
package/lib/rules.mjs
CHANGED
|
File without changes
|
package/lib/shells.mjs
CHANGED
|
File without changes
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// Pure state and view logic for the skill context card.
|
|
2
|
+
//
|
|
3
|
+
// The card shows only skills whose instructions are still loaded in the model-visible
|
|
4
|
+
// context. A user can release a skill before the next turn; the runtime then replaces
|
|
5
|
+
// that skill's tool result with a short marker. The durable session log is untouched.
|
|
6
|
+
|
|
7
|
+
export const SKILL_CARD_KEY = 'deepPtcSkills';
|
|
8
|
+
export const SKILL_STATE_EVENT = 'plugin:dsh-deep-ptc-mode/skill-state';
|
|
9
|
+
export const SKILL_COMMAND = 'deep-ptc-skill-state';
|
|
10
|
+
export const SKILL_DISABLED_MARK = '[deep-ptc-skill-disabled]';
|
|
11
|
+
|
|
12
|
+
const MAX_SKILLS = 64;
|
|
13
|
+
const MAX_SEQUENCES = 32;
|
|
14
|
+
const MAX_NAME = 128;
|
|
15
|
+
const MAX_DESCRIPTION = 500;
|
|
16
|
+
const SKILL_NAME = /<skill_content\s+name="([A-Za-z0-9._-]+)"/u;
|
|
17
|
+
const CATALOG_BLOCK = /<available_skills>([\s\S]*?)<\/available_skills>/u;
|
|
18
|
+
const CATALOG_LINE = /^\s*-\s+`([^`]+)`:\s*(.*)$/u;
|
|
19
|
+
|
|
20
|
+
const objects = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
|
|
22
|
+
function text(value, max = MAX_DESCRIPTION) {
|
|
23
|
+
return typeof value === 'string' ? value.slice(0, max) : '';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Text blocks from a stored tool result or user message. */
|
|
27
|
+
function messageText(data) {
|
|
28
|
+
const content = Array.isArray(data?.content) ? data.content : data?.message?.content;
|
|
29
|
+
if (!Array.isArray(content)) return '';
|
|
30
|
+
return content.map(block => block?.type === 'text' ? text(block.text, Number.MAX_SAFE_INTEGER) : '').join('\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Skill name carried by the official <skill_content> result. */
|
|
34
|
+
export function skillNameOfResult(value) {
|
|
35
|
+
return SKILL_NAME.exec(String(value ?? ''))?.[1] ?? '';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Name-to-description pairs from the persisted skill catalog. */
|
|
39
|
+
export function catalogDescriptions(value) {
|
|
40
|
+
const block = CATALOG_BLOCK.exec(String(value ?? ''))?.[1];
|
|
41
|
+
if (!block) return {};
|
|
42
|
+
const descriptions = {};
|
|
43
|
+
for (const line of block.split('\n')) {
|
|
44
|
+
const match = CATALOG_LINE.exec(line);
|
|
45
|
+
if (!match) continue;
|
|
46
|
+
const name = text(match[1], MAX_NAME);
|
|
47
|
+
if (name) descriptions[name] = text(match[2]);
|
|
48
|
+
}
|
|
49
|
+
return descriptions;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function blankSkillState(header) {
|
|
53
|
+
// The projection init receives the session header. Inactive sessions never fold
|
|
54
|
+
// skill events, so the card state exists only for Deep PTC sessions.
|
|
55
|
+
const active = header === undefined ? true : header.agentPreset === 'deep-ptc';
|
|
56
|
+
return { v: 1, active, turn: 0, phase: 'idle', skills: [], committed: null, descriptions: {} };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sequences(value) {
|
|
60
|
+
if (!Array.isArray(value) || value.length > MAX_SEQUENCES) throw new Error('Invalid skill result list');
|
|
61
|
+
const seen = new Set();
|
|
62
|
+
for (const seq of value) {
|
|
63
|
+
if (!Number.isSafeInteger(seq) || seq <= 0 || seen.has(seq)) throw new Error('Invalid skill result sequence');
|
|
64
|
+
seen.add(seq);
|
|
65
|
+
}
|
|
66
|
+
return [...seen];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Validate and normalize one durable skill-card state. */
|
|
70
|
+
export function parseSkillState(value) {
|
|
71
|
+
if (!objects(value) || value.v !== 1 || !Number.isSafeInteger(value.turn) || value.turn < 0
|
|
72
|
+
|| (value.phase !== 'idle' && value.phase !== 'running') || !Array.isArray(value.skills)
|
|
73
|
+
|| value.skills.length > MAX_SKILLS) throw new Error('Invalid Deep PTC skill state');
|
|
74
|
+
const skills = value.skills.map(row => {
|
|
75
|
+
if (!objects(row) || typeof row.name !== 'string' || row.name.length === 0 || row.name.length > MAX_NAME
|
|
76
|
+
|| typeof row.description !== 'string' || row.description.length > MAX_DESCRIPTION
|
|
77
|
+
|| typeof row.enabled !== 'boolean' || !Number.isSafeInteger(row.loadedTurn) || row.loadedTurn < 0) {
|
|
78
|
+
throw new Error('Invalid Deep PTC skill row');
|
|
79
|
+
}
|
|
80
|
+
const source = row.source === 'ptc' ? 'ptc' : 'tool';
|
|
81
|
+
return { name: row.name, description: text(row.description), enabled: row.enabled,
|
|
82
|
+
loadedTurn: row.loadedTurn, source, callId: text(row.callId, 128), seqs: sequences(row.seqs) };
|
|
83
|
+
});
|
|
84
|
+
const names = new Set(skills.map(row => row.name));
|
|
85
|
+
if (names.size !== skills.length) throw new Error('Duplicate Deep PTC skill name');
|
|
86
|
+
const committed = value.committed === null ? null : objects(value.committed) ? Object.fromEntries(
|
|
87
|
+
Object.entries(value.committed).filter(([name, enabled]) => names.has(name) && typeof enabled === 'boolean')) : null;
|
|
88
|
+
const descriptions = objects(value.descriptions) ? Object.fromEntries(
|
|
89
|
+
Object.entries(value.descriptions).filter(([name, description]) => typeof name === 'string' && name.length <= MAX_NAME && typeof description === 'string')
|
|
90
|
+
.map(([name, description]) => [name, text(description)])) : {};
|
|
91
|
+
return { v: 1, active: value.active !== false, turn: value.turn, phase: value.phase, skills, committed, descriptions };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function withDescription(state, name) {
|
|
95
|
+
return state.descriptions[name] ?? state.skills.find(row => row.name === name)?.description ?? '';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Fold one session event into the card state. */
|
|
99
|
+
export function foldSkillState(state, event) {
|
|
100
|
+
if (state.active === false) return state;
|
|
101
|
+
if (event.type === SKILL_STATE_EVENT) {
|
|
102
|
+
try { return parseSkillState(event.data); } catch { return state; }
|
|
103
|
+
}
|
|
104
|
+
if (event.type === 'turn/start') {
|
|
105
|
+
const turn = event.data?.turn;
|
|
106
|
+
if (!Number.isSafeInteger(turn) || turn < 0) return state;
|
|
107
|
+
return { ...state, turn, phase: 'running',
|
|
108
|
+
committed: Object.fromEntries(state.skills.map(row => [row.name, row.enabled])) };
|
|
109
|
+
}
|
|
110
|
+
if (event.type === 'turn/end') {
|
|
111
|
+
const turn = event.data?.turn;
|
|
112
|
+
if (!Number.isSafeInteger(turn) || turn < 0) return state;
|
|
113
|
+
return { ...state, turn, phase: 'idle', committed: null };
|
|
114
|
+
}
|
|
115
|
+
if (event.type === 'user/message') {
|
|
116
|
+
const found = catalogDescriptions(messageText(event.data));
|
|
117
|
+
if (Object.keys(found).length === 0) return state;
|
|
118
|
+
const descriptions = { ...state.descriptions, ...found };
|
|
119
|
+
return { ...state, descriptions,
|
|
120
|
+
skills: state.skills.map(row => found[row.name] === undefined ? row : { ...row, description: found[row.name] }) };
|
|
121
|
+
}
|
|
122
|
+
if (event.type !== 'tool/result' && event.type !== 'tool/ptc-dispatch') return state;
|
|
123
|
+
if (event.type === 'tool/ptc-dispatch' && event.data?.name !== 'skill') return state;
|
|
124
|
+
const body = messageText(event.data);
|
|
125
|
+
if (!body) return state;
|
|
126
|
+
const trimmed = body.trimStart();
|
|
127
|
+
const seq = event.seq;
|
|
128
|
+
if (event.type === 'tool/result') {
|
|
129
|
+
if (!Number.isSafeInteger(seq) || seq <= 0) return state;
|
|
130
|
+
if (trimmed.startsWith(SKILL_DISABLED_MARK)) {
|
|
131
|
+
const callId = typeof event.data?.callId === 'string' ? event.data.callId : '';
|
|
132
|
+
const removed = new Set();
|
|
133
|
+
for (const row of state.skills) if (callId !== '' && row.callId === callId) for (const value of row.seqs) removed.add(value);
|
|
134
|
+
return removeResults(state, removed);
|
|
135
|
+
}
|
|
136
|
+
// Only the skill tool's own result starts with the wrapper. A read of docs that
|
|
137
|
+
// merely quotes the template must not become a card row.
|
|
138
|
+
if (!trimmed.startsWith('<skill_content')) return state;
|
|
139
|
+
}
|
|
140
|
+
const name = skillNameOfResult(trimmed);
|
|
141
|
+
if (!name) return state;
|
|
142
|
+
const source = event.type === 'tool/result' ? 'tool' : 'ptc';
|
|
143
|
+
const existing = state.skills.find(row => row.name === name);
|
|
144
|
+
if (existing !== undefined) {
|
|
145
|
+
return { ...state, skills: state.skills.map(row => row.name !== name ? row : {
|
|
146
|
+
...row, description: withDescription(state, name), enabled: true, loadedTurn: state.turn, source,
|
|
147
|
+
callId: typeof event.data?.callId === 'string' ? event.data.callId : row.callId,
|
|
148
|
+
seqs: source === 'tool' ? [...new Set([...row.seqs, seq])].slice(-MAX_SEQUENCES) : row.seqs,
|
|
149
|
+
}) };
|
|
150
|
+
}
|
|
151
|
+
return { ...state, skills: [...state.skills, {
|
|
152
|
+
name, description: withDescription(state, name), enabled: true, loadedTurn: state.turn, source,
|
|
153
|
+
callId: typeof event.data?.callId === 'string' ? event.data.callId : '',
|
|
154
|
+
seqs: source === 'tool' ? [seq] : [],
|
|
155
|
+
}] };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Remove successful (or compacted) result sequences from the active set. */
|
|
159
|
+
export function removeResults(state, removed) {
|
|
160
|
+
if (!(removed instanceof Set) || removed.size === 0) return state;
|
|
161
|
+
const skills = state.skills.map(row => ({ ...row, seqs: row.seqs.filter(seq => !removed.has(seq)) }))
|
|
162
|
+
.filter(row => row.seqs.length > 0);
|
|
163
|
+
return { ...state, skills };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Rows the next pre-step must release before the model request. */
|
|
167
|
+
export function skillsToUnload(state) {
|
|
168
|
+
if (state.committed === null) return [];
|
|
169
|
+
return state.skills.filter(row => state.committed[row.name] === false);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Parse the JSON payload sent by the card command. */
|
|
173
|
+
export function parseSkillCommand(rawInput) {
|
|
174
|
+
let request;
|
|
175
|
+
try { request = JSON.parse(String(rawInput ?? '')); } catch { return undefined; }
|
|
176
|
+
if (!objects(request)) return undefined;
|
|
177
|
+
if (request.action === 'all' && typeof request.enabled === 'boolean') return { action: 'all', enabled: request.enabled };
|
|
178
|
+
if (request.action === 'set' && typeof request.name === 'string' && request.name.length > 0
|
|
179
|
+
&& request.name.length <= MAX_NAME && typeof request.enabled === 'boolean') {
|
|
180
|
+
return { action: 'set', name: request.name, enabled: request.enabled };
|
|
181
|
+
}
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Apply a card command without side effects. */
|
|
186
|
+
export function applySkillCommand(state, rawInput) {
|
|
187
|
+
const request = parseSkillCommand(rawInput);
|
|
188
|
+
if (request === undefined) return undefined;
|
|
189
|
+
if (request.action === 'all') return { ...state, skills: state.skills.map(row => ({ ...row, enabled: request.enabled })) };
|
|
190
|
+
return { ...state, skills: state.skills.map(row => row.name === request.name ? { ...row, enabled: request.enabled } : row) };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The client receives only what the card needs. */
|
|
194
|
+
export function skillCardView(state) {
|
|
195
|
+
return { v: 1, turn: state.turn, phase: state.phase,
|
|
196
|
+
skills: state.skills.map(row => ({ name: row.name, description: row.description,
|
|
197
|
+
enabled: row.enabled, loadedTurn: row.loadedTurn })) };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Validate the client wire view. */
|
|
201
|
+
export function parseSkillCardView(value) {
|
|
202
|
+
if (!objects(value) || value.v !== 1 || !Number.isSafeInteger(value.turn) || value.turn < 0
|
|
203
|
+
|| (value.phase !== 'idle' && value.phase !== 'running') || !Array.isArray(value.skills)
|
|
204
|
+
|| value.skills.length > MAX_SKILLS) throw new Error('Invalid Deep PTC skill card view');
|
|
205
|
+
return { v: 1, turn: value.turn, phase: value.phase, skills: value.skills.map(row => ({
|
|
206
|
+
name: text(row?.name, MAX_NAME), description: text(row?.description), enabled: row?.enabled === true,
|
|
207
|
+
loadedTurn: Number.isSafeInteger(row?.loadedTurn) ? row.loadedTurn : 0,
|
|
208
|
+
})) };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Replacement data preserves every tool-result field except its rendered content. */
|
|
212
|
+
export function replacementData(event, name) {
|
|
213
|
+
const data = structuredClone(event.data);
|
|
214
|
+
data.message = { ...data.message, content: [{ type: 'text',
|
|
215
|
+
text: `${SKILL_DISABLED_MARK} Skill "${name}" was disabled by the user for this task. Load it again if needed.` }] };
|
|
216
|
+
return data;
|
|
217
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Runtime for the skill context card.
|
|
2
|
+
//
|
|
3
|
+
// The official skill tool keeps its instruction body in the tool result history until
|
|
4
|
+
// compaction. This layer lets the user release individual skills before a new turn:
|
|
5
|
+
// at the first step of that turn it replaces the model-visible tool result with a short
|
|
6
|
+
// marker. The durable session log and the human transcript keep the original body.
|
|
7
|
+
|
|
8
|
+
import { importHost } from './host.mjs';
|
|
9
|
+
import { applySkillCommand, blankSkillState, foldSkillState, parseSkillCardView, parseSkillState, removeResults,
|
|
10
|
+
replacementData, skillCardView, skillsToUnload, SKILL_CARD_KEY, SKILL_COMMAND, SKILL_STATE_EVENT } from './skill-card.mjs';
|
|
11
|
+
|
|
12
|
+
export const name = 'deep-ptc-skill-context';
|
|
13
|
+
// The layer is optional: a missing service disables the card rather than rejecting the preset.
|
|
14
|
+
export const inject = [];
|
|
15
|
+
const REQUIRED = ['commands', 'sessionProjections'];
|
|
16
|
+
const DEEP_PTC = 'deep-ptc';
|
|
17
|
+
|
|
18
|
+
/** The card must never observe or mutate another preset's session. */
|
|
19
|
+
function isDeepPtcSession(session) {
|
|
20
|
+
return session?.header?.agentPreset === DEEP_PTC;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function apply(ctx) {
|
|
24
|
+
// Wait for the host services before the profile finishes booting, so the
|
|
25
|
+
// projection exists before session histories are replayed.
|
|
26
|
+
return ctx.plugin({ name: 'deep-ptc-skill-context-layer', inject: REQUIRED, apply: install }).await()
|
|
27
|
+
.catch(error => ctx.logger.warn('Deep PTC: skill context card is off (%s)', error.message));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function install(ctx) {
|
|
31
|
+
const { appendPluginRecord } = await importHost('@deepseek-ai/dsh-session');
|
|
32
|
+
if (typeof appendPluginRecord !== 'function') throw new Error('the installed session module has no appendPluginRecord');
|
|
33
|
+
const schema = { parse: parseSkillState };
|
|
34
|
+
const projection = await ctx.sessionProjections.register({ key: SKILL_CARD_KEY, stateVersion: 1,
|
|
35
|
+
stateSchema: schema, init: blankSkillState, apply: foldSkillState,
|
|
36
|
+
wire: { viewSchema: { parse: parseSkillCardView }, view: skillCardView, summary: false } });
|
|
37
|
+
ctx.effect(() => () => projection.dispose());
|
|
38
|
+
const save = (session, state) => appendPluginRecord(session, SKILL_STATE_EVENT, state);
|
|
39
|
+
ctx.commands.register({ name: SKILL_COMMAND, description: '设置下一轮继续加载的 Skill / Choose which loaded skills stay in context',
|
|
40
|
+
recordInput: false,
|
|
41
|
+
handler: ({ agent, rawInput }) => {
|
|
42
|
+
if (!agent?.session) return { kind: 'error', text: 'No active conversation. / 当前没有活动对话。' };
|
|
43
|
+
if (!isDeepPtcSession(agent.session)) return { kind: 'error', text: 'This command is available in Deep PTC sessions only. / 该功能仅在深度 PTC 会话中可用。' };
|
|
44
|
+
const state = projection.stateOf(agent.session) ?? blankSkillState();
|
|
45
|
+
const updated = applySkillCommand(state, rawInput);
|
|
46
|
+
if (updated === undefined) return { kind: 'error', text: 'Invalid skill card command. / 无效的 Skill 卡片操作。' };
|
|
47
|
+
save(agent.session, updated);
|
|
48
|
+
return { kind: 'success', text: 'Skill card updated; it applies to the next message. / Skill 卡片已更新,将在下一条消息生效。' };
|
|
49
|
+
} });
|
|
50
|
+
ctx.effect(() => ctx.on('agent/pre-step', async (payload, next) => {
|
|
51
|
+
if (!isDeepPtcSession(payload.agent?.session)) return typeof next === 'function' ? next() : undefined;
|
|
52
|
+
try { await releaseSkillResults(ctx, projection, save, payload.agent); }
|
|
53
|
+
catch (error) { ctx.logger.warn('Deep PTC: releasing skills failed (%s)', error.message); }
|
|
54
|
+
return typeof next === 'function' ? next() : undefined;
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Release every skill the committed card state no longer keeps. */
|
|
59
|
+
export async function releaseSkillResults(ctx, projection, save, agent) {
|
|
60
|
+
if (agent === undefined) return;
|
|
61
|
+
const session = agent.session;
|
|
62
|
+
if (!isDeepPtcSession(session)) return;
|
|
63
|
+
const state = projection.stateOf(session) ?? blankSkillState();
|
|
64
|
+
const rows = skillsToUnload(state);
|
|
65
|
+
if (rows.length === 0) return;
|
|
66
|
+
const visible = new Set(Array.isArray(session.surface?.nodes) ? session.surface.nodes : []);
|
|
67
|
+
const removed = new Set();
|
|
68
|
+
const dropped = new Set();
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
if (row.seqs.length === 0) { dropped.add(row.name); continue; }
|
|
71
|
+
for (const seq of row.seqs) {
|
|
72
|
+
if (!visible.has(seq)) { removed.add(seq); continue; }
|
|
73
|
+
let event;
|
|
74
|
+
try { event = session.eventAt(seq); } catch { continue; }
|
|
75
|
+
if (event?.type !== 'tool/result' || event.data?.message === undefined) { removed.add(seq); continue; }
|
|
76
|
+
try {
|
|
77
|
+
session.append('tool/result', replacementData(event, row.name), {
|
|
78
|
+
surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq],
|
|
79
|
+
});
|
|
80
|
+
removed.add(seq);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
ctx.logger.warn('Deep PTC: could not release skill "%s" (%s)', row.name, error.message);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (removed.size === 0 && dropped.size === 0) return;
|
|
87
|
+
const next = removeResults(state, removed);
|
|
88
|
+
save(session, { ...next, skills: next.skills.filter(row => !dropped.has(row.name)) });
|
|
89
|
+
}
|
package/lib/sleep-lint.mjs
CHANGED
|
File without changes
|
package/lib/terminal.mjs
CHANGED
|
File without changes
|
package/lib/tool-catalog.mjs
CHANGED
|
File without changes
|
|
@@ -2,7 +2,8 @@ import z from '@deepseek-ai/schemastery';
|
|
|
2
2
|
import { failOpen, installToolCompatibility, officialToolSource } from './tool-policy.mjs';
|
|
3
3
|
import { importHost } from './host.mjs';
|
|
4
4
|
import { toolDirectory } from './official-names.mjs';
|
|
5
|
-
import { DIRECTORY_TOOL, RESET_COMMAND, STATE_EVENT,
|
|
5
|
+
import { DIRECTORY_TOOL, RESET_COMMAND, STATE_EVENT, searchCatalog, toolSchema } from './tool-catalog.mjs';
|
|
6
|
+
import { registerState, resetText, rootToolState, sessionRecords } from './tool-state.mjs';
|
|
6
7
|
|
|
7
8
|
export const name = 'deep-ptc-tool-compatibility';
|
|
8
9
|
// Discovery and quarantine are an optional layer: a failed preset row rejects the whole preset mount,
|
|
@@ -23,23 +24,22 @@ export function apply(ctx, config) {
|
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
async function install(ctx, config) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
27
|
+
const root = rootToolState();
|
|
28
|
+
let projection = root?.projection;
|
|
29
|
+
let write = root?.write;
|
|
30
|
+
if (root === undefined) {
|
|
31
|
+
const appendPluginRecord = await sessionRecords();
|
|
32
|
+
projection = await registerState(ctx);
|
|
33
|
+
ctx.effect(() => () => projection.dispose());
|
|
34
|
+
write = (session, value) => appendPluginRecord(session, STATE_EVENT, value);
|
|
35
|
+
}
|
|
33
36
|
const directory = toolDirectory(() => ctx.get('loader'), { modules: config.officialModules, base: ctx.baseUrl });
|
|
34
37
|
const state = installToolCompatibility(ctx, { preferences: config.preferences, directory, storage: {
|
|
35
38
|
read: session => projection.stateOf(session),
|
|
36
|
-
write
|
|
39
|
+
write,
|
|
37
40
|
} });
|
|
38
|
-
ctx.commands.register({ name: RESET_COMMAND, description: '重载所有工具状态 / Reload all tool states',
|
|
39
|
-
handler: ({ agent }) => {
|
|
40
|
-
const count = state.reset(agent);
|
|
41
|
-
return { kind: 'success', text: `已重载本对话全部工具状态,清除 ${count} 个故障标记。正在运行的任务继续执行。 / All tool states reloaded for this conversation; ${count} quarantine marks cleared. Running jobs continue.` };
|
|
42
|
-
} });
|
|
41
|
+
if (root === undefined) ctx.commands.register({ name: RESET_COMMAND, description: '重载所有工具状态 / Reload all tool states',
|
|
42
|
+
handler: ({ agent }) => ({ kind: 'success', text: resetText(state.reset(agent)) }) });
|
|
43
43
|
ctx.tools.register({ name: DIRECTORY_TOOL,
|
|
44
44
|
description: 'Find tools or skills by function without loading all schemas. search returns compact tool summaries; load reveals complete schemas for selected tool names; skills returns summaries to load with the official skill tool. Never executes task tools or reads skill bodies.',
|
|
45
45
|
parameters: { type: 'object', additionalProperties: false, properties: {
|