dsh-procedures 0.0.0-stage → 1.0.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 +46 -0
- package/LICENSE +21 -0
- package/PRO.md +47 -0
- package/README.en.md +90 -0
- package/README.md +353 -2
- package/bench/search.mjs +74 -0
- package/bin/hint.mjs +115 -0
- package/bin/procedures.mjs +295 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +10 -0
- package/index.js +374 -0
- package/lib/cards.mjs +619 -0
- package/lib/hint.mjs +17 -0
- package/lib/hook-text.mjs +26 -0
- package/lib/llm.mjs +243 -0
- package/lib/stats.mjs +103 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +55 -4
- package/portable/AGENTS-snippet.md +17 -0
- package/portable/README.md +121 -0
- package/portable/setup.mjs +115 -0
- package/portable/templates/INDEX.md +9 -0
- package/portable/templates/_inbox.md +5 -0
- package/portable/templates/_/346/250/241/346/235/277-spell.md +38 -0
- package/portable/templates/_/346/250/241/346/235/277.md +43 -0
package/index.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { appendInbox, searchCards } from './lib/cards.mjs';
|
|
7
|
+
import { HOOK_TEXT, globalHookText } from './lib/hook-text.mjs';
|
|
8
|
+
import { buildHint } from './lib/hint.mjs';
|
|
9
|
+
import { recordHitAt, recordOutcomeAt, statsPath } from './lib/stats.mjs';
|
|
10
|
+
|
|
11
|
+
export { buildHint };
|
|
12
|
+
|
|
13
|
+
let createUserMessage;
|
|
14
|
+
try {
|
|
15
|
+
const llm = await import('@deepseek-ai/dsh-llm');
|
|
16
|
+
createUserMessage = llm.createUserMessage;
|
|
17
|
+
} catch {
|
|
18
|
+
createUserMessage = undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const name = 'dsh-procedures';
|
|
22
|
+
export const inject = ['systemPrompt', 'workingDirectory', 'agents'];
|
|
23
|
+
|
|
24
|
+
const DEFAULTS = {
|
|
25
|
+
dir: 'procedures',
|
|
26
|
+
autoInbox: true,
|
|
27
|
+
hintOnError: true,
|
|
28
|
+
maxCards: 3,
|
|
29
|
+
maxHintsPerSession: 5,
|
|
30
|
+
minErrorChars: 8,
|
|
31
|
+
sectionOrder: 800,
|
|
32
|
+
ignoreTools: [],
|
|
33
|
+
hookText: '',
|
|
34
|
+
debug: false,
|
|
35
|
+
stats: true,
|
|
36
|
+
globalDir: '',
|
|
37
|
+
globalPenalty: 1,
|
|
38
|
+
globalStats: true,
|
|
39
|
+
globalStatsFile: '',
|
|
40
|
+
resolutionWindow: 5,
|
|
41
|
+
resolutionSeconds: 120,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
function positive(value, fallback) {
|
|
45
|
+
const parsed = Number.parseInt(String(value ?? ''), 10);
|
|
46
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function normalizeConfig(raw) {
|
|
50
|
+
const source = raw && typeof raw === 'object' ? raw : {};
|
|
51
|
+
const ignore = Array.isArray(source.ignoreTools)
|
|
52
|
+
? source.ignoreTools
|
|
53
|
+
: typeof source.ignoreTools === 'string'
|
|
54
|
+
? source.ignoreTools.split(',')
|
|
55
|
+
: [];
|
|
56
|
+
return {
|
|
57
|
+
...DEFAULTS,
|
|
58
|
+
dir: typeof source.dir === 'string' && source.dir.trim() ? source.dir.trim() : DEFAULTS.dir,
|
|
59
|
+
autoInbox: source.autoInbox !== false,
|
|
60
|
+
hintOnError: source.hintOnError !== false,
|
|
61
|
+
maxCards: positive(source.maxCards, DEFAULTS.maxCards),
|
|
62
|
+
maxHintsPerSession: positive(source.maxHintsPerSession, DEFAULTS.maxHintsPerSession),
|
|
63
|
+
minErrorChars: positive(source.minErrorChars, DEFAULTS.minErrorChars),
|
|
64
|
+
sectionOrder: Number.isFinite(Number(source.sectionOrder))
|
|
65
|
+
? Number(source.sectionOrder)
|
|
66
|
+
: DEFAULTS.sectionOrder,
|
|
67
|
+
ignoreTools: ignore.map((item) => String(item).trim()).filter(Boolean),
|
|
68
|
+
hookText: typeof source.hookText === 'string' && source.hookText.trim() ? source.hookText : '',
|
|
69
|
+
debug: source.debug === true,
|
|
70
|
+
stats: source.stats !== false,
|
|
71
|
+
globalDir: typeof source.globalDir === 'string' ? source.globalDir.trim() : '',
|
|
72
|
+
globalPenalty: Number.isFinite(Number(source.globalPenalty)) && Number(source.globalPenalty) >= 0
|
|
73
|
+
? Number(source.globalPenalty)
|
|
74
|
+
: DEFAULTS.globalPenalty,
|
|
75
|
+
globalStats: source.globalStats !== false,
|
|
76
|
+
globalStatsFile: typeof source.globalStatsFile === 'string' ? source.globalStatsFile.trim() : '',
|
|
77
|
+
resolutionWindow: positive(source.resolutionWindow, DEFAULTS.resolutionWindow),
|
|
78
|
+
resolutionSeconds: positive(source.resolutionSeconds, DEFAULTS.resolutionSeconds),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function warn(ctx, message) {
|
|
83
|
+
const logger = ctx?.logger;
|
|
84
|
+
if (logger && typeof logger.warn === 'function') logger.warn(`[procedures] ${message}`);
|
|
85
|
+
else if (typeof console !== 'undefined') console.warn(`[procedures] ${message}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function isInside(parent, child) {
|
|
89
|
+
const rel = relative(resolve(parent), resolve(child));
|
|
90
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function configuredDir(cwd, value) {
|
|
94
|
+
const raw = String(value ?? '').trim();
|
|
95
|
+
if (!raw) return undefined;
|
|
96
|
+
const expanded = raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')
|
|
97
|
+
? join(homedir(), raw.slice(1))
|
|
98
|
+
: raw;
|
|
99
|
+
return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function globalStatsPath(cwd, value) {
|
|
103
|
+
const raw = String(value ?? '').trim();
|
|
104
|
+
const expanded = raw
|
|
105
|
+
? (raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\')
|
|
106
|
+
? join(homedir(), raw.slice(1))
|
|
107
|
+
: raw)
|
|
108
|
+
: join(homedir(), '.dsh', 'procedures', 'global-stats.json');
|
|
109
|
+
return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function resolveAttach(cwd, cfg) {
|
|
113
|
+
const localDir = resolve(cwd, cfg.dir);
|
|
114
|
+
const hasLocal = isInside(cwd, localDir) && existsSync(localDir);
|
|
115
|
+
const globalDir = configuredDir(cwd, cfg.globalDir);
|
|
116
|
+
const hasGlobal = Boolean(globalDir && existsSync(globalDir));
|
|
117
|
+
const mode = hasLocal ? (hasGlobal ? 'both' : 'local') : hasGlobal ? 'global' : 'none';
|
|
118
|
+
return {
|
|
119
|
+
localDir,
|
|
120
|
+
hasLocal,
|
|
121
|
+
globalDir,
|
|
122
|
+
hasGlobal,
|
|
123
|
+
mode,
|
|
124
|
+
globalStatsFile: globalStatsPath(cwd, cfg.globalStatsFile),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function errorText(result) {
|
|
129
|
+
const parts = [];
|
|
130
|
+
const push = (value) => {
|
|
131
|
+
const text = String(value ?? '').trim();
|
|
132
|
+
if (!text) return;
|
|
133
|
+
const duplicate = parts.some(
|
|
134
|
+
(part) => part === text || part.includes(text) || text.includes(part),
|
|
135
|
+
);
|
|
136
|
+
if (!duplicate) parts.push(text);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const failure = result?.error;
|
|
140
|
+
if (failure && typeof failure === 'object') {
|
|
141
|
+
if (typeof failure.message === 'string') push(failure.message);
|
|
142
|
+
const info = failure.info;
|
|
143
|
+
if (info && typeof info === 'object') {
|
|
144
|
+
if (info.name) push(String(info.name));
|
|
145
|
+
if (info.code) push(String(info.code));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for (const block of Array.isArray(result?.content) ? result.content : []) {
|
|
149
|
+
if (block && block.type === 'text' && typeof block.text === 'string') push(block.text);
|
|
150
|
+
}
|
|
151
|
+
return parts.join(' | ').slice(0, 800);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function injectText(ctx, agent, text) {
|
|
155
|
+
try {
|
|
156
|
+
if (typeof agent.inject !== 'function') return;
|
|
157
|
+
const message = typeof createUserMessage === 'function'
|
|
158
|
+
? createUserMessage({
|
|
159
|
+
content: [{ type: 'text', text }],
|
|
160
|
+
source: { kind: 'cordis-host-runner' },
|
|
161
|
+
})
|
|
162
|
+
: {
|
|
163
|
+
id: randomUUID(),
|
|
164
|
+
role: 'user',
|
|
165
|
+
time: Date.now(),
|
|
166
|
+
content: [{ type: 'text', text }],
|
|
167
|
+
source: { kind: 'cordis-host-runner' },
|
|
168
|
+
};
|
|
169
|
+
agent.inject(message);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
warn(ctx, `inject failed: ${String(error)}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function shouldCapture(cfg, hits, text) {
|
|
176
|
+
return cfg.autoInbox === true && hits.length === 0 && text.length >= cfg.minErrorChars;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function settlePending(state, hits, now, cfg) {
|
|
180
|
+
const pending = state.pending;
|
|
181
|
+
if (!pending) return null;
|
|
182
|
+
pending.remaining -= 1;
|
|
183
|
+
const repeated = Array.isArray(hits) && hits.some((hit) => hit.id === pending.cardId);
|
|
184
|
+
const elapsed = now - pending.at >= Number(cfg.resolutionSeconds) * 1000;
|
|
185
|
+
if (repeated) {
|
|
186
|
+
state.pending = null;
|
|
187
|
+
return { ...pending, outcome: 'repeated' };
|
|
188
|
+
}
|
|
189
|
+
if (pending.remaining <= 0 || elapsed) {
|
|
190
|
+
state.pending = null;
|
|
191
|
+
return { ...pending, outcome: 'no_repeat' };
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function statsFileForHit(hit, cfg, dataDir, hasLocal, globalStatsFile) {
|
|
197
|
+
if (hit.scope === 'global') return cfg.globalStats ? globalStatsFile : null;
|
|
198
|
+
return hasLocal && cfg.stats ? statsPath(dataDir) : null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function onToolResult(ctx, cfg, agent, cwd, dataDir, state, exec, result, globalDir, hasLocal, globalStatsFile) {
|
|
202
|
+
if (!result) return;
|
|
203
|
+
const now = Date.now();
|
|
204
|
+
const isError = result.isError === true;
|
|
205
|
+
const tool = typeof exec?.name === 'string' && exec.name ? exec.name : 'tool';
|
|
206
|
+
let text = '';
|
|
207
|
+
let hits = [];
|
|
208
|
+
|
|
209
|
+
if (isError && !cfg.ignoreTools.includes(tool)) {
|
|
210
|
+
text = errorText(result);
|
|
211
|
+
if (text.length >= cfg.minErrorChars) {
|
|
212
|
+
hits = searchCards(dataDir, `${tool}\n${text}`, {
|
|
213
|
+
max: cfg.maxCards,
|
|
214
|
+
strict: true,
|
|
215
|
+
globalDir,
|
|
216
|
+
globalPenalty: cfg.globalPenalty,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (state.pending) {
|
|
222
|
+
const settled = settlePending(state, hits, now, cfg);
|
|
223
|
+
if (settled) {
|
|
224
|
+
try {
|
|
225
|
+
recordOutcomeAt(settled.statsFile, { id: settled.cardId }, settled.outcome, {
|
|
226
|
+
now: new Date(now),
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
warn(ctx, `resolution update failed: ${String(error)}`);
|
|
230
|
+
}
|
|
231
|
+
if (cfg.debug) warn(ctx, `resolution ${settled.outcome} for ${settled.cardId}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (!isError || cfg.ignoreTools.includes(tool) || text.length < cfg.minErrorChars) return;
|
|
236
|
+
|
|
237
|
+
if (hits.length > 0) {
|
|
238
|
+
if (!cfg.hintOnError) return;
|
|
239
|
+
const hit = hits[0];
|
|
240
|
+
if (state.cards.has(hit.id) || state.hints >= cfg.maxHintsPerSession) return;
|
|
241
|
+
state.cards.add(hit.id);
|
|
242
|
+
state.hints += 1;
|
|
243
|
+
injectText(ctx, agent, buildHint(hit, cwd));
|
|
244
|
+
|
|
245
|
+
const file = statsFileForHit(hit, cfg, dataDir, hasLocal, globalStatsFile);
|
|
246
|
+
if (file) {
|
|
247
|
+
try {
|
|
248
|
+
if (state.pending) {
|
|
249
|
+
recordOutcomeAt(state.pending.statsFile, { id: state.pending.cardId }, 'no_repeat', {
|
|
250
|
+
now: new Date(now),
|
|
251
|
+
});
|
|
252
|
+
state.pending = null;
|
|
253
|
+
}
|
|
254
|
+
recordHitAt(file, hit, { sessionId: agent.id });
|
|
255
|
+
state.pending = {
|
|
256
|
+
cardId: hit.id,
|
|
257
|
+
at: now,
|
|
258
|
+
remaining: cfg.resolutionWindow,
|
|
259
|
+
statsFile: file,
|
|
260
|
+
};
|
|
261
|
+
} catch (error) {
|
|
262
|
+
warn(ctx, `stats update failed: ${String(error)}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (cfg.debug) warn(ctx, `hint ${hit.id} for ${agent.id}`);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (!hasLocal) return;
|
|
270
|
+
if (!shouldCapture(cfg, hits, text)) return;
|
|
271
|
+
const signature = `${tool}|${text.replace(/\s+/g, ' ').slice(0, 120)}`;
|
|
272
|
+
if (state.signatures.has(signature)) return;
|
|
273
|
+
state.signatures.add(signature);
|
|
274
|
+
const appended = appendInbox(dataDir, { tool, message: text });
|
|
275
|
+
if (cfg.debug && appended.added) warn(ctx, `inbox captured ${tool} for ${agent.id}`);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function apply(ctx, rawConfig) {
|
|
279
|
+
const cfg = normalizeConfig(rawConfig);
|
|
280
|
+
const attached = new Map();
|
|
281
|
+
|
|
282
|
+
const detach = (id) => {
|
|
283
|
+
const state = attached.get(id);
|
|
284
|
+
if (!state) return;
|
|
285
|
+
attached.delete(id);
|
|
286
|
+
for (const dispose of state.registrations.reverse()) {
|
|
287
|
+
try {
|
|
288
|
+
dispose?.();
|
|
289
|
+
} catch {
|
|
290
|
+
// The agent context may already be disposed; nothing left to release.
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
const attach = (agent) => {
|
|
296
|
+
if (!agent || attached.has(agent.id)) return;
|
|
297
|
+
let cwd;
|
|
298
|
+
try {
|
|
299
|
+
cwd = ctx.workingDirectory.get(agent.session);
|
|
300
|
+
} catch {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return;
|
|
304
|
+
|
|
305
|
+
const plan = resolveAttach(cwd, cfg);
|
|
306
|
+
if (plan.mode === 'none') return;
|
|
307
|
+
const dataDir = plan.localDir;
|
|
308
|
+
const globalDir = plan.globalDir;
|
|
309
|
+
const hasLocal = plan.hasLocal;
|
|
310
|
+
|
|
311
|
+
const state = {
|
|
312
|
+
registrations: [],
|
|
313
|
+
cards: new Set(),
|
|
314
|
+
hints: 0,
|
|
315
|
+
signatures: new Set(),
|
|
316
|
+
pending: null,
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
const hook = cfg.hookText || (hasLocal
|
|
321
|
+
? (plan.hasGlobal
|
|
322
|
+
? `${HOOK_TEXT}\n- 也配置了只读全局库;命中全局卡时提示会写 global:<文件名>。`
|
|
323
|
+
: HOOK_TEXT)
|
|
324
|
+
: globalHookText(globalDir));
|
|
325
|
+
state.registrations.push(agent.ctx.systemPrompt.section({
|
|
326
|
+
name: 'procedures',
|
|
327
|
+
order: cfg.sectionOrder,
|
|
328
|
+
text: hook,
|
|
329
|
+
}));
|
|
330
|
+
} catch (error) {
|
|
331
|
+
warn(ctx, `section registration failed for ${agent.id}: ${String(error)}`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
try {
|
|
335
|
+
state.registrations.push(agent.ctx.on('tools/result', (exec, result) => {
|
|
336
|
+
try {
|
|
337
|
+
onToolResult(ctx, cfg, agent, cwd, dataDir, state, exec, result, globalDir, hasLocal, plan.globalStatsFile);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
warn(ctx, `result handler failed: ${String(error)}`);
|
|
340
|
+
}
|
|
341
|
+
}));
|
|
342
|
+
} catch (error) {
|
|
343
|
+
warn(ctx, `tools/result registration failed: ${String(error)}`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
attached.set(agent.id, state);
|
|
347
|
+
if (cfg.debug) warn(ctx, `attached ${agent.id} (${plan.mode}: ${hasLocal ? dataDir : globalDir})`);
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
ctx.effect(() => {
|
|
351
|
+
for (const agent of ctx.agents.list()) {
|
|
352
|
+
try {
|
|
353
|
+
attach(agent);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
warn(ctx, `attach failed: ${String(error)}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const offCreated = ctx.on('agent/created', ({ agent }) => {
|
|
360
|
+
try {
|
|
361
|
+
attach(agent);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
warn(ctx, `attach on created failed: ${String(error)}`);
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
const offDisposed = ctx.on('agent/disposed', ({ agent }) => detach(agent.id));
|
|
367
|
+
|
|
368
|
+
return () => {
|
|
369
|
+
offCreated();
|
|
370
|
+
offDisposed();
|
|
371
|
+
for (const id of [...attached.keys()]) detach(id);
|
|
372
|
+
};
|
|
373
|
+
});
|
|
374
|
+
}
|