dsh-deep-ptc-mode 1.7.2 → 1.7.4
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 +105 -71
- package/README.md +204 -174
- package/README.zh.md +219 -189
- package/TEST_REPORT.md +33 -0
- package/lib/ask-user.mjs +2 -1
- package/lib/client.js +59 -9
- package/lib/creative.mjs +127 -0
- package/lib/environment.mjs +2 -1
- package/lib/executor.mjs +31 -6
- package/lib/guard.mjs +2 -1
- package/lib/host.mjs +25 -17
- package/lib/index.mjs +105 -11
- package/lib/jobs-tool.mjs +2 -1
- package/lib/lab.mjs +13 -0
- package/lib/model.mjs +47 -21
- package/lib/official-names.mjs +115 -0
- package/lib/resident.mjs +27 -0
- package/lib/rules.mjs +5 -5
- package/lib/shells.mjs +114 -0
- package/lib/sleep-lint.mjs +391 -41
- package/lib/tool-catalog.mjs +1 -1
- package/lib/tool-compatibility.mjs +29 -11
- package/lib/tool-policy.mjs +250 -184
- package/lib/upstream.mjs +94 -1
- package/package.json +127 -125
- package/lib/official-tools.mjs +0 -8
package/lib/tool-policy.mjs
CHANGED
|
@@ -1,184 +1,250 @@
|
|
|
1
|
-
import { DIRECTORY_TOOL, blankState, toolSchema, searchCatalog } from './tool-catalog.mjs';
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
export function
|
|
7
|
-
export function
|
|
8
|
-
export
|
|
9
|
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
if (
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
},
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
if (!
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
row.
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const row = entry(agent);
|
|
149
|
-
if (!row)
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
1
|
+
import { DIRECTORY_TOOL, blankState, toolSchema, searchCatalog } from './tool-catalog.mjs';
|
|
2
|
+
import { staysResident } from './resident.mjs';
|
|
3
|
+
const officialDefinitions = new WeakMap();
|
|
4
|
+
const validName = name => typeof name === 'string' && name.length > 0 && name.length <= 256 && !/[\u0000-\u001f]/u.test(name);
|
|
5
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
+
export function markOfficialTool(definition, provider = 'official PTC') { officialDefinitions.set(definition, provider); return definition; }
|
|
7
|
+
export function isOfficialTool(definition) { return officialDefinitions.has(definition); }
|
|
8
|
+
export function officialToolSource(definition) { return officialDefinitions.get(definition); }
|
|
9
|
+
export const compatibilityPolicy = `## Efficient tool cooperation
|
|
10
|
+
- Search available external capabilities by function using deep_ptc_tools. Load only matching definitions; then use their actual schemas. If none fit, use an admitted official PTC tool. Provider discovery/loaders remain authoritative for provider-specific SDKs.
|
|
11
|
+
- When an external capability fails, read the error: correct wrong input, and retry a temporary failure at most twice. A capability that is unavailable or keeps failing is quarantined for this conversation. Unless the user asks you to investigate it, do not retry, probe, diagnose or repair a quarantined capability; promptly use a working equivalent or the official fallback and focus on finishing the task. Only the user's Reload all tool states button resets quarantine.
|
|
12
|
+
- At task completion, briefly list the failed tool names and their declared plugins (or unknown source) and say there may be a compatibility problem. Do not claim a root cause. Mention completed work first.
|
|
13
|
+
- Preserve authorization, cancellation, the selected shell and managed jobs. Empty results and running/background jobs are not failures. Before replacing a partially completed write or command, read only the task state needed to avoid duplicate effects; this is task recovery, not plugin diagnosis.
|
|
14
|
+
- Search skills through deep_ptc_tools(action=skills), then use the official loader named by loadWith and follow its full instructions. Reuse already-loaded instructions in the current context; discovery summaries are not skill instructions.
|
|
15
|
+
- Never bypass hidden tools, policy denials, cancelled work or an unavailable whole executor. Deep PTC's existing foreground/steering wrappers continue to govern official execution.`;
|
|
16
|
+
// Error text is only consulted when a failure carries no code. Plain throws are the common case for
|
|
17
|
+
// plugins, so these patterns separate a broken provider from wrong input and passing trouble.
|
|
18
|
+
const MISSING_TEXT = /is not a (?:function|constructor)|cannot find (?:module|package)|err_module_not_found|not implemented|cannot read propert(?:y|ies) of (?:undefined|null)/iu;
|
|
19
|
+
const DENIED_TEXT = /permission denied|eacces|eperm|forbidden|unauthori[sz]ed|\b40[13]\b/iu;
|
|
20
|
+
const INPUT_TEXT = /enoent|no such file|not found|does not exist|invalid|missing required|bad request|\b40[04]\b/iu;
|
|
21
|
+
const TEMPORARY_TEXT = /timed? ?out|timeout|etimedout|econnreset|econnrefused|eai_again|enotfound|socket hang up|network|fetch failed|rate.?limit|too many requests|\b429\b|\b50[234]\b|temporar|try again|overloaded/iu;
|
|
22
|
+
/** Consecutive unexplained or temporary failures before a capability is quarantined. */
|
|
23
|
+
export const QUARANTINE_STRIKES = 3;
|
|
24
|
+
const IMMEDIATE = new Set(['unavailable', 'partial']);
|
|
25
|
+
|
|
26
|
+
export function classifyToolOutcome(exec, result) {
|
|
27
|
+
if (exec.signal?.aborted) return { kind: 'cancelled', effect: 'unknown' };
|
|
28
|
+
const value = object(result?.value) ? result.value : undefined;
|
|
29
|
+
if (value?.cancelled === true || ['cancelled', 'aborted'].includes(value?.status)) return { kind: 'cancelled', effect: 'unknown' };
|
|
30
|
+
if (value?.sandbox?.denied === true) return { kind: 'denied', effect: 'unknown' };
|
|
31
|
+
// A call that returned is the tool working; its status field describes the tool's own subject (a
|
|
32
|
+
// failed build, an unavailable service). Only an explicit failure object reports on the tool itself.
|
|
33
|
+
const failure = object(value?.failure) ? value.failure : undefined;
|
|
34
|
+
if (!result?.isError && !failure) {
|
|
35
|
+
return value?.kind === 'foreground' && typeof value.exitCode === 'number' && value.exitCode !== 0
|
|
36
|
+
? { kind: 'command', effect: 'unknown' } : undefined;
|
|
37
|
+
}
|
|
38
|
+
// The host reports a thrown HarnessError's code under error.info.
|
|
39
|
+
const rawCode = result?.error?.info?.code ?? result?.error?.code ?? failure?.code;
|
|
40
|
+
const code = typeof rawCode === 'string' && /^[A-Z0-9_:-]{1,96}$/u.test(rawCode) ? rawCode : '';
|
|
41
|
+
const effect = ['none', 'unknown', 'partial', 'completed'].includes(failure?.effectState)
|
|
42
|
+
? failure.effectState : 'unknown';
|
|
43
|
+
const status = typeof value?.status === 'string' ? value.status.toLowerCase() : '';
|
|
44
|
+
if (/ABORT|CANCEL/u.test(code) || status === 'cancelled') return { kind: 'cancelled', effect };
|
|
45
|
+
if (/DENIED|FORBIDDEN|POLICY|APPROVAL|PERMISSION|EACCES|EPERM|READ_ONLY/u.test(code))
|
|
46
|
+
return { kind: 'denied', effect };
|
|
47
|
+
if (code === 'ENOENT' && /\bspawn(?:sync)?\b[^\n]*\bENOENT\b/iu.test(String(result?.error?.message ?? failure?.message ?? ''))) return {kind:'unavailable',effect};
|
|
48
|
+
if (/ARGUMENT|INVALID_ARGS|VALIDATION|ENOENT|NOT_FOUND/u.test(code) && code !== 'UNKNOWN_TOOL')
|
|
49
|
+
return { kind: 'input', effect };
|
|
50
|
+
if (status === 'partial') return { kind: 'partial', effect };
|
|
51
|
+
if (/UNKNOWN_TOOL|UNAVAILABLE|WORKER_MISSING|RUNTIME_MISSING/u.test(code) || status === 'unavailable')
|
|
52
|
+
return { kind: 'unavailable', effect };
|
|
53
|
+
if (code) return { kind: /TIMEOUT|RATE|BUSY|OVERLOAD/u.test(code) ? 'temporary' : 'failure', effect };
|
|
54
|
+
const message = String(result?.error?.message ?? failure?.message ?? '');
|
|
55
|
+
if (MISSING_TEXT.test(message)) return { kind: 'unavailable', effect };
|
|
56
|
+
if (DENIED_TEXT.test(message)) return { kind: 'denied', effect };
|
|
57
|
+
if (TEMPORARY_TEXT.test(message)) return { kind: 'temporary', effect };
|
|
58
|
+
if (INPUT_TEXT.test(message)) return { kind: 'input', effect };
|
|
59
|
+
return { kind: 'failure', effect };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function normalizePreferences(preferences = []) {
|
|
63
|
+
if (!Array.isArray(preferences) || preferences.length > 32) throw new Error('toolPreferences must be an array with at most 32 entries');
|
|
64
|
+
const seen = new Set();
|
|
65
|
+
return preferences.map(row => {
|
|
66
|
+
if (!object(row) || !validName(row.preferred) || row.preferred === 'run_code'
|
|
67
|
+
|| !Array.isArray(row.fallback) || row.fallback.length === 0 || row.fallback.length > 12
|
|
68
|
+
|| row.fallback.some(name => !validName(name) || name === 'run_code' || name === row.preferred)
|
|
69
|
+
|| seen.has(row.preferred)) throw new Error('Each tool preference needs a unique preferred tool and 1–12 distinct fallback names (not run_code)');
|
|
70
|
+
if (new Set(row.fallback).size !== row.fallback.length) throw new Error('Duplicate fallback names in toolPreferences');
|
|
71
|
+
seen.add(row.preferred);
|
|
72
|
+
return { preferred: row.preferred, fallback: [...row.fallback] };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function createCompatibilityState(tools, preferences = [], storage = {}, directory = {}) {
|
|
77
|
+
const routes = normalizePreferences(preferences);
|
|
78
|
+
let sessions = new WeakMap();
|
|
79
|
+
let calls = new WeakMap();
|
|
80
|
+
const sessionOf = agent => object(agent?.session) ? agent.session : agent;
|
|
81
|
+
function entry(agent) {
|
|
82
|
+
if (storage.read && !object(agent?.session)) return undefined;
|
|
83
|
+
const session = sessionOf(agent);
|
|
84
|
+
if (!object(session)) return undefined;
|
|
85
|
+
let row = sessions.get(session);
|
|
86
|
+
if (!row) { row = { state: storage.read?.(session) ?? blankState(), selected: new Set(), strikes: new Map() }; sessions.set(session, row); }
|
|
87
|
+
const current = storage.read?.(session);
|
|
88
|
+
if (current && current !== row.state) { if (current.epoch !== row.state.epoch) { row.selected.clear(); row.strikes.clear(); } row.state = current; }
|
|
89
|
+
return row;
|
|
90
|
+
}
|
|
91
|
+
function save(agent, row, state) {
|
|
92
|
+
storage.write?.(sessionOf(agent), state); // Persist first: an unsuccessful reset never clears quarantine.
|
|
93
|
+
row.state = state;
|
|
94
|
+
}
|
|
95
|
+
function definitions(agent, toolSet) { return tools.definitions(agent, toolSet).filter(def => validName(def.name)); }
|
|
96
|
+
// Unknown ownership is deliberately fail-open. Source scraping can miss dynamic official
|
|
97
|
+
// registrations; only a positively attributed external provider may be quarantined or hidden.
|
|
98
|
+
const declaredExternal = def => typeof def?.deepPtc?.provider === 'string' && !def.deepPtc.provider.startsWith('@deepseek-ai/');
|
|
99
|
+
const official = def => !!def && (isOfficialTool(def) || (!declaredExternal(def) && directory.isOfficial?.(def.name) === true));
|
|
100
|
+
const external = def => !!def && !official(def) && (typeof def.deepPtc?.provider === 'string' || directory.isExternal?.(def.name) === true || (typeof directory.providerOf?.(def.name) === 'string' && !directory.providerOf(def.name).startsWith('@deepseek-ai/')));
|
|
101
|
+
const resident = def => staysResident(def, directory.providerOf?.(def?.name) ?? '');
|
|
102
|
+
const protectedName = (agent, name) => {
|
|
103
|
+
const def = tools.get(name, agent);
|
|
104
|
+
if (def && resident(def)) return true;
|
|
105
|
+
return def ? !external(def) : directory.isOfficial?.(name) === true;
|
|
106
|
+
};
|
|
107
|
+
const usableState = agent => {
|
|
108
|
+
const state = entry(agent)?.state ?? blankState();
|
|
109
|
+
const filter = rows => rows.filter(row => !protectedName(agent, row.name));
|
|
110
|
+
return { ...state, blocked: filter(state.blocked), report: state.report ? {...state.report,tools:filter(state.report.tools)} : null };
|
|
111
|
+
};
|
|
112
|
+
const blocked = (agent, name) => !protectedName(agent, name) && entry(agent)?.state.blocked.some(row => row.name === name) === true;
|
|
113
|
+
// Most official tools are known by the name their module declares; the feature wrappers also mark theirs.
|
|
114
|
+
|
|
115
|
+
const providerOf = def => officialDefinitions.get(def) ?? (typeof def?.deepPtc?.provider === 'string' ? def.deepPtc.provider.slice(0, 160) : undefined) ?? directory.providerOf?.(def?.name) ?? 'unknown plugin';
|
|
116
|
+
const api = {
|
|
117
|
+
dispatched(exec) {
|
|
118
|
+
const row = entry(exec.agent);
|
|
119
|
+
if (!row || calls.has(exec)) return;
|
|
120
|
+
const cleaned=usableState(exec.agent);
|
|
121
|
+
if(JSON.stringify(cleaned)!==JSON.stringify(row.state)) save(exec.agent,row,cleaned);
|
|
122
|
+
const definition = tools.get(exec.name, exec.agent, exec.toolSet);
|
|
123
|
+
calls.set(exec, { epoch: row.state.epoch, definition, official: !external(definition), provider: providerOf(definition) });
|
|
124
|
+
},
|
|
125
|
+
guard(exec) { return blocked(exec.agent, exec.name) ? `Deep PTC: ${JSON.stringify(exec.name)} is quarantined in this conversation. Do not retry or diagnose it. Continue with another admitted equivalent or official tool. Only the user can reload all tool states.` : undefined; },
|
|
126
|
+
observe(exec, result) {
|
|
127
|
+
const call = calls.get(exec);
|
|
128
|
+
// No definition means the name never belonged to a plugin, so there is nothing to quarantine.
|
|
129
|
+
if (!call?.definition || call.official || resident(call.definition) || exec.name === DIRECTORY_TOOL || exec.name === 'run_code') return;
|
|
130
|
+
const row = entry(exec.agent);
|
|
131
|
+
if (!row || call.epoch !== row.state.epoch || blocked(exec.agent, exec.name)) return;
|
|
132
|
+
const outcome = classifyToolOutcome(exec, result);
|
|
133
|
+
if (!outcome) { row.strikes.delete(exec.name); return; }
|
|
134
|
+
// Authorization and cancelled actions must never be converted to provider failover, and wrong
|
|
135
|
+
// input says nothing about the tool.
|
|
136
|
+
if (['denied', 'cancelled', 'command', 'input'].includes(outcome.kind)) return;
|
|
137
|
+
if (!IMMEDIATE.has(outcome.kind)) {
|
|
138
|
+
const strikes = (row.strikes.get(exec.name) ?? 0) + 1;
|
|
139
|
+
row.strikes.set(exec.name, strikes);
|
|
140
|
+
if (strikes < QUARANTINE_STRIKES) return;
|
|
141
|
+
}
|
|
142
|
+
const failure = { name: exec.name, provider: call.provider, kind: outcome.kind };
|
|
143
|
+
save(exec.agent, row, { ...row.state, blocked: [...row.state.blocked, failure] });
|
|
144
|
+
row.strikes.delete(exec.name);
|
|
145
|
+
row.selected.delete(exec.name);
|
|
146
|
+
},
|
|
147
|
+
reset(agent) {
|
|
148
|
+
const row = entry(agent);
|
|
149
|
+
if (!row) throw new Error('No conversation is active');
|
|
150
|
+
const count = row.state.blocked.length;
|
|
151
|
+
save(agent, row, { ...blankState(), epoch: row.state.epoch + 1 });
|
|
152
|
+
row.selected.clear();
|
|
153
|
+
row.strikes.clear();
|
|
154
|
+
return count;
|
|
155
|
+
},
|
|
156
|
+
status(agent) { return usableState(agent); },
|
|
157
|
+
sdkDefinitions(agent, toolSet, compact = true) {
|
|
158
|
+
const row = entry(agent);
|
|
159
|
+
const excluded = new Set(usableState(agent).blocked.map(item => item.name));
|
|
160
|
+
return definitions(agent, toolSet).filter(def => !excluded.has(def.name)
|
|
161
|
+
&& (!compact || !external(def) || def.name === DIRECTORY_TOOL || row?.selected.has(def.name) || resident(def)));
|
|
162
|
+
},
|
|
163
|
+
search(agent, args, toolSet) {
|
|
164
|
+
const excluded = new Set(usableState(agent).blocked.map(item => item.name));
|
|
165
|
+
const visible = definitions(agent, toolSet).filter(def => def.name !== DIRECTORY_TOOL && !excluded.has(def.name));
|
|
166
|
+
const externalTools = visible.filter(external);
|
|
167
|
+
const result = searchCatalog(externalTools, args.query, args.offset, args.limit);
|
|
168
|
+
if (result.total) return { layer: 'external', ...result };
|
|
169
|
+
const baseline=searchCatalog(visible.filter(official),args.query,args.offset,args.limit);
|
|
170
|
+
if(baseline.total)return {layer:'official',...baseline};
|
|
171
|
+
return {layer:'unattributed',...searchCatalog(visible.filter(def=>!external(def)&&!official(def)),args.query,args.offset,args.limit)};
|
|
172
|
+
},
|
|
173
|
+
load(agent, names, toolSet) {
|
|
174
|
+
if (!Array.isArray(names) || names.length < 1 || names.length > 6 || names.some(name => !validName(name))) throw new Error('Load 1–6 exact tool names');
|
|
175
|
+
const live = new Map(definitions(agent, toolSet).map(def => [def.name, def]));
|
|
176
|
+
const row = entry(agent);
|
|
177
|
+
if (!row) throw new Error('No conversation is active');
|
|
178
|
+
let budget = 16000;
|
|
179
|
+
const loaded = [], unavailable = [], deferred = [];
|
|
180
|
+
for (const name of new Set(names)) {
|
|
181
|
+
const def = live.get(name);
|
|
182
|
+
if (!def || blocked(agent, name) || name === DIRECTORY_TOOL) { unavailable.push(name); continue; }
|
|
183
|
+
const schema = toolSchema(def);
|
|
184
|
+
const size = Buffer.byteLength(JSON.stringify(schema), 'utf8');
|
|
185
|
+
if (size > budget) { row.selected.add(name); if(row.selected.size>12)row.selected.delete(row.selected.values().next().value); deferred.push(name); continue; }
|
|
186
|
+
budget -= size;
|
|
187
|
+
row.selected.delete(name);
|
|
188
|
+
row.selected.add(name);
|
|
189
|
+
if (row.selected.size > 12) row.selected.delete(row.selected.values().next().value);
|
|
190
|
+
loaded.push(schema);
|
|
191
|
+
}
|
|
192
|
+
return { loaded, unavailable, deferred, nextStep: true, note: 'Deferred names are selected and will appear in full in the next host SDK. Unavailable names are hidden or quarantined. No tool was executed. Use an equivalent or load fewer definitions.' };
|
|
193
|
+
},
|
|
194
|
+
text({ scope: agent, toolSet } = {}) {
|
|
195
|
+
if (!object(agent)) return '';
|
|
196
|
+
const row = entry(agent);
|
|
197
|
+
if (!row) return '';
|
|
198
|
+
const state = usableState(agent);
|
|
199
|
+
const lines = [];
|
|
200
|
+
if (state.blocked.length) {
|
|
201
|
+
lines.push('Quarantined for this conversation; no retries or diagnosis. Finish the task using working equivalents. At completion briefly report these tool/plugin names and a possible compatibility problem:');
|
|
202
|
+
lines.push(JSON.stringify(state.blocked.slice(0, 8).map(({name,provider}) => ({name,provider}))));
|
|
203
|
+
if (state.blocked.length > 8) lines.push(`${state.blocked.length} tools total; the user interface retains the full list.`);
|
|
204
|
+
lines.push('Check only necessary task state before replacing a possibly partial mutation. Reset is a user action.');
|
|
205
|
+
}
|
|
206
|
+
const available = routes.length ? new Set(definitions(agent, toolSet).map(def => def.name)) : new Set();
|
|
207
|
+
for (const route of routes) {
|
|
208
|
+
if (available.has(route.preferred) && !blocked(agent, route.preferred)) lines.push(`Prefer ${JSON.stringify(route.preferred)} when applicable; visible equivalents: ${JSON.stringify(route.fallback.filter(name => available.has(name) && !blocked(agent, name)))}. Read live schemas.`);
|
|
209
|
+
}
|
|
210
|
+
return lines.join('\n');
|
|
211
|
+
},
|
|
212
|
+
dispose() { sessions = new WeakMap(); calls = new WeakMap(); },
|
|
213
|
+
};
|
|
214
|
+
return api;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// A failure in this layer must leave tool calls and prompts as the host would have them.
|
|
218
|
+
export function failOpen(ctx, label, fn, fallback) {
|
|
219
|
+
let warned = false;
|
|
220
|
+
return (...args) => {
|
|
221
|
+
try {
|
|
222
|
+
return fn(...args);
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (!warned) {
|
|
225
|
+
warned = true;
|
|
226
|
+
ctx.logger?.warn?.('Deep PTC: %s failed (%s); continuing without it', label, error?.message);
|
|
227
|
+
}
|
|
228
|
+
return fallback;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function installToolCompatibility(ctx, { enabled = true, preferences = [], storage, directory } = {}) {
|
|
234
|
+
if (!enabled) return;
|
|
235
|
+
const state = createCompatibilityState(ctx.tools, preferences, storage, directory);
|
|
236
|
+
const guard = failOpen(ctx, 'tool quarantine check', exec => state.guard(exec));
|
|
237
|
+
const dispatched = failOpen(ctx, 'tool call tracking', exec => state.dispatched(exec));
|
|
238
|
+
ctx.systemPrompt.section({ name: 'deep-ptc:tool-compatibility', order: 10194, text: compatibilityPolicy });
|
|
239
|
+
ctx.systemPrompt.context({ name: 'deep-ptc:tool-recovery', order: 122, text: failOpen(ctx, 'tool recovery context', context => state.text(context), '') });
|
|
240
|
+
ctx.tools.guard(guard);
|
|
241
|
+
ctx.on('tools/execute', (exec, next) => {
|
|
242
|
+
const reason = guard(exec);
|
|
243
|
+
if (reason) return Promise.resolve({ isError: true, error: { message: reason }, content: [{ type: 'text', text: reason }] });
|
|
244
|
+
dispatched(exec);
|
|
245
|
+
return next();
|
|
246
|
+
});
|
|
247
|
+
ctx.on('tools/result', failOpen(ctx, 'tool result tracking', (exec, result) => state.observe(exec, result)));
|
|
248
|
+
ctx.effect(() => () => state.dispose());
|
|
249
|
+
return state;
|
|
250
|
+
}
|
package/lib/upstream.mjs
CHANGED
|
@@ -5,9 +5,10 @@
|
|
|
5
5
|
// and the plugin only replaces the parts it actually owns (persona, execution
|
|
6
6
|
// environment, reachability guard, job/question wrappers).
|
|
7
7
|
import { createRequire } from 'node:module';
|
|
8
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
10
10
|
import { dirname, join, isAbsolute, resolve } from 'node:path';
|
|
11
|
+
import { CREATIVE_PRESET_ID, selectCreativePreset } from './creative.mjs';
|
|
11
12
|
|
|
12
13
|
export const OFFICIAL_PACKAGE = '@deepseek-ai/dsh-web-app';
|
|
13
14
|
const PACKAGE = OFFICIAL_PACKAGE;
|
|
@@ -196,3 +197,95 @@ export function loadOfficialPreset({ presetPath } = {}) {
|
|
|
196
197
|
const text = readFileSync(fileURLToPath(url), 'utf8');
|
|
197
198
|
return { preset: parseOfficialPreset(text), source: url };
|
|
198
199
|
}
|
|
200
|
+
|
|
201
|
+
function pluginRows(value) {
|
|
202
|
+
return Array.isArray(value) && value.length > 0
|
|
203
|
+
&& value.every(row => row && typeof row === 'object' && typeof row.name === 'string');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A creative-mode composition list, or the creative preset inside a patch document. */
|
|
207
|
+
export function parseCreativeDocument(text) {
|
|
208
|
+
const document = loadYaml().load(text, { schema: presetSchema() });
|
|
209
|
+
if (pluginRows(document)) return document;
|
|
210
|
+
const layers = Array.isArray(document) ? document : [];
|
|
211
|
+
const inserted = [];
|
|
212
|
+
const collect = rows => {
|
|
213
|
+
if (!Array.isArray(rows)) return;
|
|
214
|
+
for (const row of rows) if (row && typeof row === 'object') inserted.push(row);
|
|
215
|
+
};
|
|
216
|
+
collect(layers);
|
|
217
|
+
for (const layer of layers) collect(layer?.insert);
|
|
218
|
+
const presets = inserted.map(row => row.config).filter(config => config && pluginRows(config.plugins));
|
|
219
|
+
const preset = presets.find(config => config.id === CREATIVE_PRESET_ID || config.name === '创造模式');
|
|
220
|
+
if (!preset) throw new Error('installed creative preset has no composition');
|
|
221
|
+
return preset.plugins;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function compositionRoot(path) {
|
|
225
|
+
if (typeof path !== 'string' || path === '') return '';
|
|
226
|
+
try {
|
|
227
|
+
return dirname(path.startsWith('file:') ? fileURLToPath(path) : path);
|
|
228
|
+
} catch {
|
|
229
|
+
return '';
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* File URL of the shipped creative preset.
|
|
235
|
+
* The directory id is the same kind of key as `ptc`. The composition filename is whatever
|
|
236
|
+
* that directory actually contains, so an official rename of the file still resolves.
|
|
237
|
+
*/
|
|
238
|
+
export function creativePresetUrl() {
|
|
239
|
+
const pkg = tryResolve('@deepseek-ai/dsh-agent-presets/package.json');
|
|
240
|
+
if (pkg === undefined) return undefined;
|
|
241
|
+
const dir = join(dirname(fileURLToPath(pkg)), 'presets', CREATIVE_PRESET_ID);
|
|
242
|
+
if (!existsSync(dir)) return undefined;
|
|
243
|
+
let names = [];
|
|
244
|
+
try { names = readdirSync(dir).filter(name => name.endsWith('.yml') || name.endsWith('.yaml')); } catch { return undefined; }
|
|
245
|
+
const named = names.find(name => name.startsWith('agent.')) ?? names[0];
|
|
246
|
+
return named === undefined ? undefined : pathToFileURL(join(dir, named)).href;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Read the creative preset the running host publishes.
|
|
251
|
+
* Module names come from that document. An unreadable preset throws so the caller can keep PTC only.
|
|
252
|
+
*/
|
|
253
|
+
export async function loadCreativePreset(registry) {
|
|
254
|
+
let roster = [];
|
|
255
|
+
if (typeof registry?.list === 'function') {
|
|
256
|
+
try { roster = await registry.list(); } catch { roster = []; }
|
|
257
|
+
}
|
|
258
|
+
const selected = selectCreativePreset(roster);
|
|
259
|
+
if (!process.env[PRESET_PATH_ENV]?.trim() && selected && typeof registry?.readDocument === 'function') {
|
|
260
|
+
const document = await registry.readDocument(selected.id);
|
|
261
|
+
return {
|
|
262
|
+
plugins: parseCreativeDocument(document.content),
|
|
263
|
+
root: compositionRoot(selected.path),
|
|
264
|
+
source: `agentPresets.readDocument(${selected.id})`,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
if (typeof selected?.path === 'string' && selected.path !== '' && existsSync(selected.path.startsWith('file:') ? fileURLToPath(selected.path) : selected.path)) {
|
|
268
|
+
const file = selected.path.startsWith('file:') ? fileURLToPath(selected.path) : selected.path;
|
|
269
|
+
return { plugins: parseCreativeDocument(readFileSync(file, 'utf8')), root: dirname(file), source: file };
|
|
270
|
+
}
|
|
271
|
+
const url = creativePresetUrl();
|
|
272
|
+
if (url === undefined) throw new Error('creative preset is not installed');
|
|
273
|
+
return {
|
|
274
|
+
plugins: parseCreativeDocument(readFileSync(fileURLToPath(url), 'utf8')),
|
|
275
|
+
root: dirname(fileURLToPath(url)),
|
|
276
|
+
source: url,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Prefer the running host's public preset registry, including its live composition. */
|
|
281
|
+
export async function loadCurrentPreset(registry) {
|
|
282
|
+
if (!process.env[PRESET_PATH_ENV]?.trim() && typeof registry?.readDocument === 'function') {
|
|
283
|
+
try {
|
|
284
|
+
const document=await registry.readDocument(OFFICIAL_PRESET_ID);
|
|
285
|
+
const plugins=loadYaml().load(document.content,{schema:presetSchema()});
|
|
286
|
+
if(!Array.isArray(plugins)||plugins.length===0)throw new Error('empty official composition');
|
|
287
|
+
return {preset:{id:OFFICIAL_PRESET_ID,name:document.name,description:document.description,plugins},source:'agentPresets.readDocument(ptc)'};
|
|
288
|
+
} catch { /* Older/initializing registries fall back to installed declaration discovery. */ }
|
|
289
|
+
}
|
|
290
|
+
return loadOfficialPreset();
|
|
291
|
+
}
|