dsh-awesome-optimizer 0.0.0-stage → 1.7.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.
@@ -0,0 +1,366 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import z from '@deepseek-ai/schemastery';
6
+
7
+ export const name = 'agent-optimizer-custom-prompt';
8
+ export const inject = ['systemPrompt'];
9
+ export const SOURCE = 'optimizer-custom-prompt';
10
+ export const SECTION_NAME = 'optimizer:custom-prompt';
11
+ export const ENVIRONMENT_FACTS_SECTION = 'optimizer:environment-facts';
12
+ export const DEFAULT_SECTION_ORDER = 10300;
13
+
14
+ export const CustomPromptConfig = z.object({
15
+ enabled: z.boolean().default(true),
16
+ globalFile: z.string().default('~/.dsh/SYSTEM.md'),
17
+ workspaceFile: z.string().default('.dsh/SYSTEM.md'),
18
+ placement: z.union(['replace-all', 'suffix']).default('replace-all'),
19
+ sectionOrder: z.number().default(DEFAULT_SECTION_ORDER),
20
+ sectionName: z.string().default(SECTION_NAME),
21
+ mergeStrategy: z.union(['concat', 'workspace-override', 'global-only', 'workspace-only']).default('concat'),
22
+ hotReload: z.boolean().default(true),
23
+ interpolate: z.boolean().default(false),
24
+ injectEnvironmentFacts: z.boolean().default(true)
25
+ });
26
+
27
+ let cachedPython = undefined;
28
+
29
+ export function resetPythonCacheForTesting() {
30
+ cachedPython = undefined;
31
+ }
32
+
33
+ /**
34
+ * Safely detect active Python runtime with one-shot memoization and timeout guards.
35
+ */
36
+ export function detectPythonEnv(spawnSyncFn = spawnSync) {
37
+ if (cachedPython !== undefined) return cachedPython;
38
+ for (const bin of ['python', 'python3']) {
39
+ try {
40
+ const res = spawnSyncFn(bin, ['--version'], { timeout: 600, encoding: 'utf8', windowsHide: true });
41
+ if (res && res.status === 0) {
42
+ const out = (res.stdout || res.stderr || '').trim();
43
+ if (out.startsWith('Python')) {
44
+ cachedPython = { bin, version: out };
45
+ return cachedPython;
46
+ }
47
+ }
48
+ } catch (_err) {}
49
+ }
50
+ cachedPython = null;
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * Generate compact host environment facts to eliminate exploratory probing turns (pwd, ls, node -v).
56
+ */
57
+ export function formatEnvironmentFacts(processRef = process, pythonDetector = detectPythonEnv) {
58
+ const version = processRef?.version || 'unknown';
59
+ const platform = processRef?.platform || 'unknown';
60
+ const arch = processRef?.arch || 'unknown';
61
+ const py = typeof pythonDetector === 'function' ? pythonDetector() : null;
62
+ const pyInfo = py ? `, ${py.version} (${py.bin})` : ' (Python not detected; use Node.js for ad-hoc scripts)';
63
+ return [
64
+ '## Host Environment & Tooling Facts',
65
+ `- Runtime: Node.js ${version}${pyInfo} on ${platform} (${arch}).`,
66
+ '- Standalone CLIs: playwright-cli, gh, ast-grep, and opencli are standalone binaries via bash; NEVER require/import as node modules.',
67
+ '- Browser automation: playwright-cli blocks "file:" URLs; serve static HTML via loopback HTTP (http://127.0.0.1:<port>).',
68
+ '- Zero startup probing: workspace context and host facts are already hydrated. NEVER run exploratory probing (pwd, ls, node -v, which).'
69
+ ].join('\n');
70
+ }
71
+
72
+ /**
73
+ * Resolve `$DSH_HOME` or default `~/.dsh`.
74
+ */
75
+ export function resolveDshHome(env = process.env) {
76
+ const configured = env?.DSH_HOME;
77
+ if (typeof configured === 'string' && configured.length > 0) return configured;
78
+ return path.join(os.homedir(), '.dsh');
79
+ }
80
+
81
+ /**
82
+ * Resolve the global SYSTEM.md path.
83
+ */
84
+ export function resolveGlobalPath(filePath, env = process.env) {
85
+ if (!filePath) return path.join(resolveDshHome(env), 'SYSTEM.md');
86
+ if (filePath.startsWith('~/') || filePath.startsWith('~\\')) {
87
+ return path.join(os.homedir(), filePath.slice(2));
88
+ }
89
+ if (filePath.startsWith('~')) {
90
+ return path.join(os.homedir(), filePath.slice(1));
91
+ }
92
+ return path.resolve(filePath);
93
+ }
94
+
95
+ /**
96
+ * Resolve the workspace SYSTEM.md path.
97
+ * Checks `<workspaceRoot>/.dsh/SYSTEM.md` first, then `<workspaceRoot>/SYSTEM.md`.
98
+ */
99
+ export function resolveWorkspacePath(workspaceRoot, relativeOrPath = '.dsh/SYSTEM.md') {
100
+ if (!workspaceRoot || typeof workspaceRoot !== 'string') return null;
101
+ if (path.isAbsolute(relativeOrPath)) return relativeOrPath;
102
+
103
+ const dotDshPath = path.resolve(workspaceRoot, relativeOrPath);
104
+ if (fs.existsSync(dotDshPath)) return dotDshPath;
105
+
106
+ const rootSystemPath = path.resolve(workspaceRoot, 'SYSTEM.md');
107
+ if (fs.existsSync(rootSystemPath)) return rootSystemPath;
108
+
109
+ return dotDshPath;
110
+ }
111
+
112
+ /**
113
+ * Extract active workspace root from context.
114
+ */
115
+ export function resolveWorkspaceRoot(ctx, context) {
116
+ if (context?.workspaceRoot && typeof context.workspaceRoot === 'string') {
117
+ return context.workspaceRoot;
118
+ }
119
+ const agent = context?.agent || (context?.scope?.session ? context.scope : null);
120
+ const session = agent?.session || context?.session;
121
+ if (session) {
122
+ try {
123
+ const wdService = typeof ctx.get === 'function' ? ctx.get('workingDirectory') : null;
124
+ const cwd = wdService?.get ? wdService.get(session) : null;
125
+ if (cwd) return cwd;
126
+ } catch (_err) {}
127
+ }
128
+ return process.cwd();
129
+ }
130
+
131
+ /**
132
+ * Reactive file-driven manager for custom SYSTEM.md prompts.
133
+ */
134
+ export class CustomPromptManager {
135
+ constructor(options = {}) {
136
+ this.config = CustomPromptConfig(options);
137
+ this.globalFilePath = resolveGlobalPath(this.config.globalFile);
138
+ this.cachedGlobal = null;
139
+ this.cachedWorkspace = new Map();
140
+ this.watchers = new Map();
141
+ this.debounceTimers = new Map();
142
+ this.disposed = false;
143
+
144
+ this.loadGlobal();
145
+ if (this.config.hotReload) {
146
+ this.watchPath(this.globalFilePath, () => this.loadGlobal());
147
+ }
148
+ }
149
+
150
+ loadGlobal() {
151
+ try {
152
+ if (this.globalFilePath && fs.existsSync(this.globalFilePath)) {
153
+ this.cachedGlobal = fs.readFileSync(this.globalFilePath, 'utf8').trim();
154
+ } else {
155
+ this.cachedGlobal = null;
156
+ }
157
+ } catch (_err) {
158
+ this.cachedGlobal = null;
159
+ }
160
+ }
161
+
162
+ loadWorkspace(workspaceRoot) {
163
+ if (!workspaceRoot) return null;
164
+ try {
165
+ const wsPath = resolveWorkspacePath(workspaceRoot, this.config.workspaceFile);
166
+ if (wsPath && fs.existsSync(wsPath)) {
167
+ const content = fs.readFileSync(wsPath, 'utf8').trim();
168
+ this.cachedWorkspace.set(workspaceRoot, content);
169
+ if (this.config.hotReload && !this.watchers.has(wsPath)) {
170
+ this.watchPath(wsPath, () => {
171
+ this.loadWorkspace(workspaceRoot);
172
+ });
173
+ }
174
+ return content;
175
+ }
176
+ this.cachedWorkspace.set(workspaceRoot, null);
177
+ // Even if file doesn't exist yet, watch the directory so creation triggers load
178
+ if (this.config.hotReload && wsPath && !this.watchers.has(wsPath)) {
179
+ this.watchPath(wsPath, () => {
180
+ this.loadWorkspace(workspaceRoot);
181
+ });
182
+ }
183
+ return null;
184
+ } catch (_err) {
185
+ this.cachedWorkspace.set(workspaceRoot, null);
186
+ return null;
187
+ }
188
+ }
189
+
190
+ watchPath(targetPath, onChange) {
191
+ if (!targetPath || this.disposed || this.watchers.has(targetPath)) return;
192
+ try {
193
+ const dir = path.dirname(targetPath);
194
+ const filename = path.basename(targetPath);
195
+ if (!fs.existsSync(dir)) {
196
+ // If directory doesn't exist yet, try to create parent or skip until created
197
+ return;
198
+ }
199
+
200
+ const watcher = fs.watch(dir, { persistent: false }, (_eventType, triggerName) => {
201
+ if (!triggerName || triggerName === filename) {
202
+ const existingTimer = this.debounceTimers.get(targetPath);
203
+ if (existingTimer) clearTimeout(existingTimer);
204
+ this.debounceTimers.set(
205
+ targetPath,
206
+ setTimeout(() => {
207
+ if (this.disposed) return;
208
+ onChange();
209
+ }, 50)
210
+ );
211
+ }
212
+ });
213
+ watcher.on('error', () => {});
214
+ this.watchers.set(targetPath, watcher);
215
+ } catch (_err) {
216
+ // Non-fatal
217
+ }
218
+ }
219
+
220
+ getGlobalPrompt() {
221
+ return this.cachedGlobal || '';
222
+ }
223
+
224
+ getWorkspacePrompt(workspaceRoot) {
225
+ if (!workspaceRoot) return '';
226
+ if (!this.cachedWorkspace.has(workspaceRoot)) {
227
+ this.loadWorkspace(workspaceRoot);
228
+ }
229
+ return this.cachedWorkspace.get(workspaceRoot) || '';
230
+ }
231
+
232
+ getEffectivePrompt(workspaceRoot) {
233
+ const globalText = this.getGlobalPrompt();
234
+ const wsText = this.getWorkspacePrompt(workspaceRoot);
235
+ const strategy = this.config.mergeStrategy;
236
+
237
+ if (strategy === 'global-only') return globalText;
238
+ if (strategy === 'workspace-only') return wsText;
239
+ if (strategy === 'workspace-override') {
240
+ return wsText || globalText;
241
+ }
242
+
243
+ // Default 'concat'
244
+ if (globalText && wsText) {
245
+ return `${globalText}\n\n${wsText}`;
246
+ }
247
+ return wsText || globalText;
248
+ }
249
+
250
+ reload() {
251
+ this.loadGlobal();
252
+ for (const wsRoot of this.cachedWorkspace.keys()) {
253
+ this.loadWorkspace(wsRoot);
254
+ }
255
+ }
256
+
257
+ dispose() {
258
+ this.disposed = true;
259
+ for (const timer of this.debounceTimers.values()) {
260
+ clearTimeout(timer);
261
+ }
262
+ this.debounceTimers.clear();
263
+ for (const watcher of this.watchers.values()) {
264
+ try {
265
+ watcher.close();
266
+ } catch (_err) {}
267
+ }
268
+ this.watchers.clear();
269
+ this.cachedWorkspace.clear();
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Apply custom prompt system into Cordis runtime.
275
+ */
276
+ export function applyCustomPrompt(ctx, rawConfig = {}) {
277
+ const config = CustomPromptConfig(rawConfig);
278
+ if (!config.enabled) return null;
279
+
280
+ const manager = new CustomPromptManager(config);
281
+
282
+ // If placement is 'suffix' or 'section', register section directly with systemPrompt service
283
+ if ((config.placement === 'suffix' || config.placement === 'section') && ctx.systemPrompt?.section) {
284
+ ctx.systemPrompt.section({
285
+ name: config.sectionName,
286
+ order: config.sectionOrder,
287
+ text: (context) => {
288
+ const wsRoot = resolveWorkspaceRoot(ctx, context);
289
+ return manager.getEffectivePrompt(wsRoot);
290
+ },
291
+ interpolate: config.interpolate
292
+ });
293
+ }
294
+
295
+ // Also hook into waterfall 'system-prompt/assemble' for prefix or replace-persona-suffix
296
+ ctx.on('system-prompt/assemble', (assembly, context) => {
297
+ const wsRoot = resolveWorkspaceRoot(ctx, context);
298
+ const customText = manager.getEffectivePrompt(wsRoot);
299
+ if (!customText) return assembly;
300
+
301
+ if (config.placement === 'replace-all') {
302
+ // Retain optimizer's own sections (e.g. convergence guidance) while stripping all official verbose sections
303
+ const optimizerSections = assembly.sections.filter(
304
+ s => typeof s.name === 'string' && s.name.startsWith('optimizer:') && s.name !== config.sectionName && s.name !== ENVIRONMENT_FACTS_SECTION
305
+ );
306
+ const sections = [
307
+ {
308
+ name: config.sectionName,
309
+ text: customText,
310
+ interpolate: config.interpolate
311
+ }
312
+ ];
313
+ if (config.injectEnvironmentFacts) {
314
+ sections.push({
315
+ name: ENVIRONMENT_FACTS_SECTION,
316
+ text: formatEnvironmentFacts(),
317
+ interpolate: false
318
+ });
319
+ }
320
+ sections.push(...optimizerSections);
321
+ return {
322
+ ...assembly,
323
+ sections
324
+ };
325
+ }
326
+
327
+ // For suffix: if ctx.systemPrompt.section was not available, ensure it gets injected
328
+ const sections = [...assembly.sections];
329
+ if (!ctx.systemPrompt?.section) {
330
+ const existingIdx = sections.findIndex(s => s.name === config.sectionName);
331
+ if (existingIdx >= 0) {
332
+ sections[existingIdx] = { ...sections[existingIdx], text: customText };
333
+ } else {
334
+ sections.push({
335
+ name: config.sectionName,
336
+ text: customText,
337
+ interpolate: config.interpolate
338
+ });
339
+ }
340
+ }
341
+ if (config.injectEnvironmentFacts && !sections.some(s => s.name === ENVIRONMENT_FACTS_SECTION)) {
342
+ sections.push({
343
+ name: ENVIRONMENT_FACTS_SECTION,
344
+ text: formatEnvironmentFacts(),
345
+ interpolate: false
346
+ });
347
+ }
348
+ return { ...assembly, sections };
349
+
350
+ return assembly;
351
+ });
352
+
353
+ ctx.on('dispose', () => {
354
+ manager.dispose();
355
+ });
356
+
357
+ return manager;
358
+ }
359
+
360
+ export const Config = CustomPromptConfig;
361
+ export function apply(ctx, config = {}) {
362
+ const service = applyCustomPrompt(ctx, config);
363
+ if (service) ctx.provide('customPrompt', service);
364
+ }
365
+
366
+ export default { name, inject, Config, apply };
@@ -0,0 +1,66 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type z from '@deepseek-ai/schemastery';
3
+
4
+ export interface FailureRecoveryOptions {
5
+ enabled?: boolean;
6
+ maxAttempts?: number;
7
+ }
8
+
9
+ export interface FailureRecoveryStats {
10
+ attempted: number;
11
+ succeeded: number;
12
+ failed: number;
13
+ invalidated: number;
14
+ }
15
+
16
+ export declare const RECOVERY_SOURCE: 'optimizer-write-recovery';
17
+ export declare const RETRY_TOOL: 'retry_failed_write';
18
+ export declare const PAIRING_ERROR: string;
19
+ export declare const FailureRecoveryConfig: z<FailureRecoveryOptions>;
20
+
21
+ export declare class RecoveryRecord {
22
+ readonly owner: unknown;
23
+ readonly callId: string;
24
+ readonly rootCallId: string;
25
+ readonly toolName: string;
26
+ readonly args: { file_path: string; content: string };
27
+ readonly targetPath: string;
28
+ readonly argHash: string;
29
+ readonly definition: unknown;
30
+ readonly turn: number;
31
+ readonly step: number;
32
+ readonly category: string;
33
+ attempts: number;
34
+ readonly maxAttempts: number;
35
+ notified: boolean;
36
+ invalidatedReason: string | null;
37
+ readonly createdAt: number;
38
+ constructor(options: {
39
+ owner: unknown;
40
+ callId: string;
41
+ rootCallId: string;
42
+ toolName?: string;
43
+ args: { file_path: string; content: string };
44
+ definition: unknown;
45
+ turn?: number;
46
+ step?: number;
47
+ category?: string;
48
+ maxAttempts?: number;
49
+ });
50
+ isValid(agent: unknown, currentTurn: number, currentDefinition?: unknown): boolean;
51
+ invalidate(reason: string): void;
52
+ consume(): void;
53
+ }
54
+
55
+ export interface FailureRecoveryService {
56
+ getRecord(session: unknown): RecoveryRecord | undefined;
57
+ getStats(session: unknown): FailureRecoveryStats;
58
+ }
59
+
60
+ export declare function applyFailureRecovery(ctx: Context, options?: FailureRecoveryOptions): FailureRecoveryService | null;
61
+ export declare const name: string;
62
+ export declare const inject: string[];
63
+ export declare const Config: z<FailureRecoveryOptions>;
64
+ export declare function apply(ctx: Context, config?: FailureRecoveryOptions): void;
65
+ declare const plugin: { name: typeof name; inject: typeof inject; Config: typeof Config; apply: typeof apply };
66
+ export default plugin;