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,417 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ import { HarnessError } from '@deepseek-ai/dsh-llm';
3
+ import { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline';
4
+
5
+ export const READ_BATCH_TOOL = 'read_batch';
6
+ export const EDIT_BATCH_TOOL = 'edit_batch';
7
+
8
+ export const CompositeToolsConfig = z.object({
9
+ enabled: z.boolean().default(true),
10
+ readBatch: z.boolean().default(true),
11
+ editBatch: z.boolean().default(true),
12
+ maxBatchFiles: z.number().step(1).min(1).max(25).default(10),
13
+ maxBatchEdits: z.number().step(1).min(1).max(25).default(10),
14
+ defaultLimitPerFile: z.number().step(1).min(1).max(2000).default(400)
15
+ });
16
+
17
+ /**
18
+ * Register safe composite tools that collapse predictable multi-step operations
19
+ * (read_batch for reading, edit_batch for literal revisions) into a single model round-trip
20
+ * while routing every sub-call through ToolExecutionPipeline so all sandbox policies,
21
+ * permissions, and file-observation hooks remain enforced.
22
+ */
23
+ export function applyCompositeTools(ctx, rawConfig = {}) {
24
+ const config = CompositeToolsConfig(rawConfig);
25
+ if (!config.enabled) return null;
26
+
27
+ const pipeline = new ToolExecutionPipeline(ctx);
28
+ const statsBySession = new WeakMap();
29
+
30
+ const stateFor = session => {
31
+ if (!session) return null;
32
+ let state = statsBySession.get(session);
33
+ if (!state) {
34
+ state = {
35
+ batchesExecuted: 0,
36
+ filesRequested: 0,
37
+ filesSucceeded: 0,
38
+ filesFailed: 0,
39
+ editBatchesExecuted: 0,
40
+ editsRequested: 0,
41
+ editsSucceeded: 0,
42
+ editsFailed: 0
43
+ };
44
+ statsBySession.set(session, state);
45
+ }
46
+ return state;
47
+ };
48
+
49
+ ctx.on('session/event', (session, event) => {
50
+ if (event.type === 'turn/start') {
51
+ statsBySession.set(session, {
52
+ batchesExecuted: 0,
53
+ filesRequested: 0,
54
+ filesSucceeded: 0,
55
+ filesFailed: 0,
56
+ editBatchesExecuted: 0,
57
+ editsRequested: 0,
58
+ editsSucceeded: 0,
59
+ editsFailed: 0
60
+ });
61
+ }
62
+ });
63
+
64
+ if (config.readBatch) {
65
+ ctx.tools.register({
66
+ name: READ_BATCH_TOOL,
67
+ description: [
68
+ `Read multiple UTF-8 text files (up to ${config.maxBatchFiles}) in a single tool call to avoid sequential single-file round trips.`,
69
+ 'Each entry dispatches through the native read tool pipeline with full sandbox and policy checks.',
70
+ 'Can be called alongside glob or grep in the same turn.'
71
+ ].join(' '),
72
+ parameters: {
73
+ type: 'object',
74
+ additionalProperties: false,
75
+ required: ['files'],
76
+ properties: {
77
+ files: {
78
+ type: 'array',
79
+ minItems: 1,
80
+ maxItems: config.maxBatchFiles,
81
+ description: `List of file read specifications (1 to ${config.maxBatchFiles} files).`,
82
+ items: {
83
+ type: 'object',
84
+ additionalProperties: false,
85
+ required: ['file_path'],
86
+ properties: {
87
+ file_path: {
88
+ type: 'string',
89
+ description: 'Path to read, resolved by the filesystem backend.'
90
+ },
91
+ offset: {
92
+ type: 'number',
93
+ description: '1-based first line to return. Defaults to 1.'
94
+ },
95
+ limit: {
96
+ type: 'number',
97
+ description: `Maximum number of lines to return. Defaults to ${config.defaultLimitPerFile}.`
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ },
104
+ output: {
105
+ schema: { type: 'string' },
106
+ render: (_args, value) => [{ type: 'text', text: value }]
107
+ },
108
+ isConcurrencySafe: () => true,
109
+ async execute(args, exec) {
110
+ exec.signal.throwIfAborted();
111
+ const files = Array.isArray(args?.files) ? args.files : [];
112
+ if (files.length === 0) {
113
+ throw new HarnessError('read_batch requires at least one file entry in "files".', 'INVALID_READ_BATCH_ARGS');
114
+ }
115
+ if (files.length > config.maxBatchFiles) {
116
+ throw new HarnessError(
117
+ `read_batch received ${files.length} files, exceeding maxBatchFiles (${config.maxBatchFiles}).`,
118
+ 'READ_BATCH_LIMIT_EXCEEDED'
119
+ );
120
+ }
121
+
122
+ const session = exec.agent?.session;
123
+ const state = stateFor(session);
124
+ if (state) {
125
+ state.batchesExecuted++;
126
+ state.filesRequested += files.length;
127
+ }
128
+
129
+ const subResults = await Promise.all(files.map(async (item, index) => {
130
+ exec.signal.throwIfAborted();
131
+ if (!item || typeof item.file_path !== 'string' || !item.file_path.trim()) {
132
+ if (state) state.filesFailed++;
133
+ return {
134
+ filePath: String(item?.file_path ?? `<invalid-${index}>`),
135
+ isError: true,
136
+ text: 'Invalid file_path: must be a non-empty string.'
137
+ };
138
+ }
139
+ const readArgs = {
140
+ file_path: item.file_path,
141
+ ...(typeof item.offset === 'number' ? { offset: item.offset } : {}),
142
+ limit: typeof item.limit === 'number' ? item.limit : config.defaultLimitPerFile
143
+ };
144
+ const subCallId = `${exec.callId}:read-batch-${index}`;
145
+ const log = {
146
+ rootCallId: exec.rootCallId,
147
+ parentCallId: exec.callId,
148
+ subCallId,
149
+ name: 'read',
150
+ arguments: readArgs
151
+ };
152
+ if (session?.append) {
153
+ session.append('tool/ptc-dispatch-start', log);
154
+ }
155
+ const prepared = await pipeline.prepare({
156
+ callId: subCallId,
157
+ rootCallId: exec.rootCallId,
158
+ parent: exec.token,
159
+ name: 'read',
160
+ arguments: readArgs,
161
+ agent: exec.agent,
162
+ toolSet: exec.toolSet,
163
+ signal: exec.signal
164
+ });
165
+ const outcome = prepared.kind === 'dispatch' ? await pipeline.dispatch(prepared.exec) : prepared;
166
+ const result = await pipeline.complete(prepared.exec, outcome);
167
+ if (session?.append) {
168
+ session.append('tool/ptc-dispatch', {
169
+ ...log,
170
+ isError: result.isError,
171
+ content: result.content,
172
+ ...(result.error?.info ? { error: result.error.info } : {}),
173
+ ...(result.meta === undefined ? {} : { meta: result.meta })
174
+ });
175
+ }
176
+ for (const context of result.additionalContexts ?? []) {
177
+ exec.deferContext(context);
178
+ }
179
+ if (result.isError) {
180
+ if (state) state.filesFailed++;
181
+ const msg = result.error?.message
182
+ ?? result.content?.filter(b => b.type === 'text').map(b => b.text).join('\n')
183
+ ?? 'Read failed';
184
+ return {
185
+ filePath: item.file_path,
186
+ isError: true,
187
+ text: `[ERROR] ${msg}`
188
+ };
189
+ }
190
+ if (state) state.filesSucceeded++;
191
+ const text = (result.content ?? [])
192
+ .filter(block => block.type === 'text')
193
+ .map(block => block.text)
194
+ .join('\n');
195
+ return {
196
+ filePath: item.file_path,
197
+ isError: false,
198
+ text
199
+ };
200
+ }));
201
+
202
+ const allFailed = subResults.every(entry => entry.isError);
203
+ const rendered = subResults
204
+ .map(entry => `=== [${entry.isError ? 'ERROR' : 'FILE'}] ${entry.filePath} ===\n${entry.text}`)
205
+ .join('\n\n');
206
+
207
+ if (allFailed) {
208
+ throw new HarnessError(rendered, 'READ_BATCH_ALL_FAILED');
209
+ }
210
+ return rendered;
211
+ }
212
+ }, { when: ({ agent }) => ctx.tools.get('read', agent) !== undefined });
213
+ }
214
+
215
+ if (config.editBatch) {
216
+ ctx.tools.register({
217
+ name: EDIT_BATCH_TOOL,
218
+ description: [
219
+ `Apply multiple targeted literal text edits (up to ${config.maxBatchEdits}) in a single file or across multiple files in a single tool call.`,
220
+ 'Edits execute sequentially through the native edit tool pipeline with full sandbox, observation policy, and mutation checks.',
221
+ 'Useful for multi-file refactoring or multi-location revisions without sequential single-edit round trips.'
222
+ ].join(' '),
223
+ parameters: {
224
+ type: 'object',
225
+ additionalProperties: false,
226
+ required: ['edits'],
227
+ properties: {
228
+ edits: {
229
+ type: 'array',
230
+ minItems: 1,
231
+ maxItems: config.maxBatchEdits,
232
+ description: `List of literal text edits (1 to ${config.maxBatchEdits} edits) to apply sequentially in a single file or across multiple files.`,
233
+ items: {
234
+ type: 'object',
235
+ additionalProperties: false,
236
+ required: ['file_path', 'old_string', 'new_string'],
237
+ properties: {
238
+ file_path: {
239
+ type: 'string',
240
+ description: 'Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments.'
241
+ },
242
+ old_string: {
243
+ type: 'string',
244
+ description: 'Literal text to replace.'
245
+ },
246
+ new_string: {
247
+ type: 'string',
248
+ description: 'Literal replacement text. Use an empty string to delete the match.'
249
+ },
250
+ replace_all: {
251
+ type: 'boolean',
252
+ description: 'Replace all matches. Defaults to false; when false, old_string must appear exactly once.'
253
+ },
254
+ justification: {
255
+ type: 'string',
256
+ description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact edit needs the wider access.'
257
+ },
258
+ sandbox_permissions: {
259
+ type: 'string',
260
+ enum: ['workspace-write', 'danger-full-access'],
261
+ description: 'The narrowest wider sandbox mode for a one-shot retry of the exact edit the sandbox just denied.'
262
+ }
263
+ }
264
+ }
265
+ }
266
+ }
267
+ },
268
+ output: {
269
+ schema: { type: 'string' },
270
+ render: (_args, value) => [{ type: 'text', text: value }]
271
+ },
272
+ async execute(args, exec) {
273
+ exec.signal.throwIfAborted();
274
+ const edits = Array.isArray(args?.edits) ? args.edits : [];
275
+ if (edits.length === 0) {
276
+ throw new HarnessError('edit_batch requires at least one edit entry in "edits".', 'INVALID_EDIT_BATCH_ARGS');
277
+ }
278
+ if (edits.length > config.maxBatchEdits) {
279
+ throw new HarnessError(
280
+ `edit_batch received ${edits.length} edits, exceeding maxBatchEdits (${config.maxBatchEdits}).`,
281
+ 'EDIT_BATCH_LIMIT_EXCEEDED'
282
+ );
283
+ }
284
+
285
+ const session = exec.agent?.session;
286
+ const state = stateFor(session);
287
+ if (state) {
288
+ state.editBatchesExecuted++;
289
+ state.editsRequested += edits.length;
290
+ }
291
+
292
+ const subResults = [];
293
+ for (let index = 0; index < edits.length; index++) {
294
+ exec.signal.throwIfAborted();
295
+ const item = edits[index];
296
+ if (!item || typeof item.file_path !== 'string' || !item.file_path.trim() || typeof item.old_string !== 'string' || typeof item.new_string !== 'string') {
297
+ if (state) state.editsFailed++;
298
+ subResults.push({
299
+ filePath: String(item?.file_path ?? `<invalid-${index}>`),
300
+ isError: true,
301
+ text: 'Invalid edit entry: file_path, old_string, and new_string must be strings.'
302
+ });
303
+ continue;
304
+ }
305
+
306
+ const editArgs = {
307
+ file_path: item.file_path,
308
+ old_string: item.old_string,
309
+ new_string: item.new_string,
310
+ ...(typeof item.replace_all === 'boolean' ? { replace_all: item.replace_all } : {}),
311
+ ...(typeof item.justification === 'string' ? { justification: item.justification } : {}),
312
+ ...(typeof item.sandbox_permissions === 'string' ? { sandbox_permissions: item.sandbox_permissions } : {})
313
+ };
314
+
315
+ const subCallId = `${exec.callId}:edit-batch-${index}`;
316
+ const log = {
317
+ rootCallId: exec.rootCallId,
318
+ parentCallId: exec.callId,
319
+ subCallId,
320
+ name: 'edit',
321
+ arguments: editArgs
322
+ };
323
+ if (session?.append) {
324
+ session.append('tool/ptc-dispatch-start', log);
325
+ }
326
+
327
+ const prepared = await pipeline.prepare({
328
+ callId: subCallId,
329
+ rootCallId: exec.rootCallId,
330
+ parent: exec.token,
331
+ name: 'edit',
332
+ arguments: editArgs,
333
+ agent: exec.agent,
334
+ toolSet: exec.toolSet,
335
+ signal: exec.signal
336
+ });
337
+ const outcome = prepared.kind === 'dispatch' ? await pipeline.dispatch(prepared.exec) : prepared;
338
+ const result = await pipeline.complete(prepared.exec, outcome);
339
+
340
+ if (session?.append) {
341
+ session.append('tool/ptc-dispatch', {
342
+ ...log,
343
+ isError: result.isError,
344
+ content: result.content,
345
+ ...(result.error?.info ? { error: result.error.info } : {}),
346
+ ...(result.meta === undefined ? {} : { meta: result.meta })
347
+ });
348
+ }
349
+
350
+ for (const context of result.additionalContexts ?? []) {
351
+ exec.deferContext(context);
352
+ }
353
+
354
+ if (result.isError) {
355
+ if (state) state.editsFailed++;
356
+ const msg = result.error?.message
357
+ ?? result.content?.filter(b => b.type === 'text').map(b => b.text).join('\n')
358
+ ?? 'Edit failed';
359
+ subResults.push({
360
+ filePath: item.file_path,
361
+ isError: true,
362
+ text: `[ERROR] ${msg}`
363
+ });
364
+ } else {
365
+ if (state) state.editsSucceeded++;
366
+ const text = (result.content ?? [])
367
+ .filter(block => block.type === 'text')
368
+ .map(block => block.text)
369
+ .join('\n') || `Edited ${item.file_path}`;
370
+ subResults.push({
371
+ filePath: item.file_path,
372
+ isError: false,
373
+ text
374
+ });
375
+ }
376
+ }
377
+
378
+ const allFailed = subResults.every(entry => entry.isError);
379
+ const rendered = subResults
380
+ .map(entry => `=== [${entry.isError ? 'ERROR' : 'EDIT'}] ${entry.filePath} ===\n${entry.text}`)
381
+ .join('\n\n');
382
+
383
+ if (allFailed) {
384
+ throw new HarnessError(rendered, 'EDIT_BATCH_ALL_FAILED');
385
+ }
386
+ return rendered;
387
+ }
388
+ }, { when: ({ agent }) => ctx.tools.get('edit', agent) !== undefined });
389
+ }
390
+
391
+ return {
392
+ getStats(session) {
393
+ const s = session ? statsBySession.get(session) : null;
394
+ return s
395
+ ? { ...s }
396
+ : {
397
+ batchesExecuted: 0,
398
+ filesRequested: 0,
399
+ filesSucceeded: 0,
400
+ filesFailed: 0,
401
+ editBatchesExecuted: 0,
402
+ editsRequested: 0,
403
+ editsSucceeded: 0,
404
+ editsFailed: 0
405
+ };
406
+ }
407
+ };
408
+ }
409
+
410
+ export const name = 'agent-optimizer-composite-tools';
411
+ export const inject = ['tools'];
412
+ export const Config = CompositeToolsConfig;
413
+ export function apply(ctx, config = {}) {
414
+ const service = applyCompositeTools(ctx, config);
415
+ if (service) ctx.provide('compositeTools', service);
416
+ }
417
+ export default { name, inject, Config, apply };
@@ -0,0 +1,33 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type z from '@deepseek-ai/schemastery';
3
+
4
+ export interface ConvergenceOptions {
5
+ enabled?: boolean;
6
+ injectGuidance?: boolean;
7
+ stepInterval?: number;
8
+ maxRemindersPerTurn?: number;
9
+ softStepBudget?: number;
10
+ }
11
+
12
+ export interface ConvergenceSummary {
13
+ steps: number;
14
+ reminded: boolean;
15
+ remindersSent: number;
16
+ reminderCharsAdded: number;
17
+ }
18
+
19
+ export interface ConvergenceService {
20
+ getSummary(session: unknown, turn?: number): ConvergenceSummary;
21
+ }
22
+
23
+ export declare const name: string;
24
+ export declare const inject: string[];
25
+ export declare const SOURCE: 'optimizer-convergence';
26
+ export declare const GUIDANCE: string;
27
+ export declare const REMINDER: string;
28
+ export declare const ConvergenceConfig: z<ConvergenceOptions>;
29
+ export declare const Config: z<ConvergenceOptions>;
30
+ export declare function applyConvergence(ctx: Context, raw?: ConvergenceOptions): ConvergenceService | null;
31
+ export declare function apply(ctx: Context, config?: ConvergenceOptions): void;
32
+ declare const plugin: { name: typeof name; inject: typeof inject; Config: typeof Config; apply: typeof apply };
33
+ export default plugin;
@@ -0,0 +1,173 @@
1
+ import z from '@deepseek-ai/schemastery';
2
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
3
+
4
+ export const name = 'agent-optimizer-convergence';
5
+ export const inject = ['systemPrompt', 'tools'];
6
+ export const SOURCE = 'optimizer-convergence';
7
+
8
+ export const GUIDANCE = [
9
+ "Work toward the user's completion criteria with as few model round trips as practical.",
10
+ 'Batch independent reads, searches, and checks in a single response when their inputs are known (or use read_batch for multi-file reads); preserve dependencies and exclusive tool barriers.',
11
+ 'Command chaining: Prioritize chaining local non-blocking operations via && (git add ... && git commit ... && npm test) to eliminate round-trip latency. Keep network- or credential-bound commands (npm publish, remote fetch) separate to prevent Windows process handle hanging and timeouts.',
12
+ 'Before emitting a large payload, produce deliverables or reusable scripts to disk using native write and execute by file path. NEVER embed complete files or large scripts in shell arguments (node -e, python -c, pwsh -Command).',
13
+ 'For localized revisions on existing files, reuse context already in the conversation and prefer native edit (or edit_batch for multi-file/multi-location revisions) with an unambiguous match over rewriting the entire file.',
14
+ 'After receiving tool results, make the next complete useful decision without repeating equivalent searches or checks unless new evidence justifies them.',
15
+ 'This efficiency guidance NEVER overrides the user, correctness, permission checks, required verification, or cancellation.'
16
+ ].join('\n');
17
+
18
+ export const REMINDER = 'Accelerate execution: batch remaining actions and conclude if criteria are met; NEVER omit verification.';
19
+
20
+ export const ConvergenceConfig = z.object({
21
+ enabled: z.boolean().default(true),
22
+ injectGuidance: z.boolean().default(true),
23
+ stepInterval: z.number().step(1).min(1).max(10000).default(8),
24
+ maxRemindersPerTurn: z.number().step(1).min(1).max(100).default(4),
25
+ softStepBudget: z.number().step(1).min(1).max(10000)
26
+ });
27
+
28
+ /**
29
+ * Add lightweight convergence guidance and periodic soft acceleration notices
30
+ * without taking over the official loop's control flow or termination semantics.
31
+ */
32
+ export function applyConvergence(ctx, raw = {}) {
33
+ const effectiveInterval = (raw.softStepBudget !== undefined && (raw.stepInterval === undefined || raw.stepInterval === 8))
34
+ ? raw.softStepBudget
35
+ : (raw.stepInterval ?? raw.softStepBudget ?? 8);
36
+ const config = ConvergenceConfig({
37
+ ...raw,
38
+ stepInterval: effectiveInterval
39
+ });
40
+ if (!config.enabled) return null;
41
+
42
+ const states = new WeakMap();
43
+ const stateFor = (session, turn) => {
44
+ if (!session) return null;
45
+ let state = states.get(session);
46
+ if (!state || state.turn !== turn) {
47
+ state = {
48
+ turn,
49
+ steps: 0,
50
+ reminded: false,
51
+ remindersSent: 0,
52
+ reminderCharsAdded: 0,
53
+ toolResults: 0,
54
+ concluded: false,
55
+ stepHasError: false,
56
+ lastStepHadError: false
57
+ };
58
+ if (typeof session.snapshotEvents === 'function') {
59
+ for (const event of session.snapshotEvents()) {
60
+ if (event.type === 'step/start' && event.data.turn === turn) state.steps++;
61
+ if (event.type === 'turn/start' && event.data.turn === turn) state.startSeq = event.seq;
62
+ if (event.type === 'user/message' && event.data.source?.kind === SOURCE && event.seq > (state.startSeq ?? Infinity)) {
63
+ state.reminded = true;
64
+ state.remindersSent++;
65
+ state.reminderCharsAdded += REMINDER.length;
66
+ }
67
+ }
68
+ }
69
+ states.set(session, state);
70
+ }
71
+ return state;
72
+ };
73
+
74
+ if (config.injectGuidance && ctx.systemPrompt?.section) {
75
+ ctx.systemPrompt.section({
76
+ name: 'optimizer:convergence',
77
+ order: 650,
78
+ text: GUIDANCE,
79
+ interpolate: false
80
+ });
81
+ }
82
+
83
+ ctx.on('session/event', (session, event) => {
84
+ if (event.type === 'turn/start') {
85
+ states.set(session, {
86
+ turn: event.data.turn,
87
+ steps: 0,
88
+ reminded: false,
89
+ remindersSent: 0,
90
+ reminderCharsAdded: 0,
91
+ startSeq: event.seq,
92
+ toolResults: 0,
93
+ concluded: false,
94
+ stepHasError: false,
95
+ lastStepHadError: false
96
+ });
97
+ return;
98
+ }
99
+ const state = states.get(session);
100
+ if (!state) return;
101
+ if (event.type === 'step/start' && event.data.turn === state.turn) {
102
+ state.steps++;
103
+ state.toolResults = 0;
104
+ state.concluded = false;
105
+ state.lastStepHadError = state.stepHasError;
106
+ state.stepHasError = false;
107
+ }
108
+ if (event.type === 'user/message' && event.data.source?.kind === SOURCE) {
109
+ state.reminded = true;
110
+ state.remindersSent++;
111
+ state.reminderCharsAdded += REMINDER.length;
112
+ }
113
+ });
114
+
115
+ ctx.on('tools/result', (exec, result) => {
116
+ if (!exec.agent) return;
117
+ const state = states.get(exec.agent.session);
118
+ if (!state) return;
119
+ state.toolResults++;
120
+ if (result?.isError || result?.error) {
121
+ state.stepHasError = true;
122
+ state.lastStepHadError = true;
123
+ }
124
+ state.concluded ||= result.concludesTurn === true;
125
+ });
126
+
127
+ ctx.on('agent/pre-step', async ({ agent, turn, step, signal, messages }, next) => {
128
+ const decision = await next();
129
+ if (decision.kind !== 'enter' || signal.aborted) return decision;
130
+ if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision;
131
+ const state = stateFor(agent.session, turn);
132
+ if (!state) return decision;
133
+
134
+ const interval = config.stepInterval ?? 8;
135
+ const maxReminders = config.maxRemindersPerTurn ?? 4;
136
+ const currentStep = step ?? (state.steps + 1);
137
+ const nextDueStep = (state.remindersSent + 1) * interval;
138
+
139
+ if (state.remindersSent >= maxReminders) return decision;
140
+ if (currentStep < nextDueStep) return decision;
141
+ if (state.lastStepHadError || state.stepHasError) return decision;
142
+ if (decision.messages.length === 0 && (state.toolResults === 0 || state.concluded)) return decision;
143
+
144
+ const reminder = createUserMessage({
145
+ content: [{ type: 'text', text: REMINDER }],
146
+ source: {
147
+ kind: SOURCE,
148
+ form: 'notice',
149
+ summary: 'Accelerate execution and conclude when criteria are met.'
150
+ }
151
+ });
152
+ return { ...decision, messages: [...decision.messages, reminder] };
153
+ }, { prepend: true });
154
+
155
+ return {
156
+ getSummary(session, turn) {
157
+ const state = session ? (turn !== undefined ? stateFor(session, turn) : states.get(session)) : null;
158
+ return {
159
+ steps: state?.steps ?? 0,
160
+ reminded: Boolean(state?.reminded),
161
+ remindersSent: state?.remindersSent ?? 0,
162
+ reminderCharsAdded: state?.reminderCharsAdded ?? 0
163
+ };
164
+ }
165
+ };
166
+ }
167
+
168
+ export const Config = ConvergenceConfig;
169
+ export function apply(ctx, config = {}) {
170
+ const service = applyConvergence(ctx, config);
171
+ if (service) ctx.provide('convergenceGuidance', service);
172
+ }
173
+ export default { name, inject, Config, apply };
@@ -0,0 +1,67 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import z from '@deepseek-ai/schemastery';
3
+
4
+ export declare const name: 'agent-optimizer-custom-prompt';
5
+ export declare const inject: ['systemPrompt'];
6
+ export declare const SOURCE: 'optimizer-custom-prompt';
7
+ export declare const SECTION_NAME: 'optimizer:custom-prompt';
8
+ export declare const ENVIRONMENT_FACTS_SECTION: 'optimizer:environment-facts';
9
+ export declare const DEFAULT_SECTION_ORDER = 10300;
10
+
11
+ export type MergeStrategy = 'concat' | 'workspace-override' | 'global-only' | 'workspace-only';
12
+ export type PlacementMode = 'replace-all' | 'suffix';
13
+
14
+ export interface CustomPromptOptions {
15
+ enabled?: boolean;
16
+ globalFile?: string;
17
+ workspaceFile?: string;
18
+ placement?: PlacementMode;
19
+ sectionOrder?: number;
20
+ sectionName?: string;
21
+ mergeStrategy?: MergeStrategy;
22
+ hotReload?: boolean;
23
+ interpolate?: boolean;
24
+ injectEnvironmentFacts?: boolean;
25
+ }
26
+
27
+ export interface PythonEnvInfo {
28
+ bin: string;
29
+ version: string;
30
+ }
31
+
32
+ export declare const CustomPromptConfig: z<CustomPromptOptions>;
33
+
34
+ export declare function detectPythonEnv(spawnSyncFn?: any): PythonEnvInfo | null;
35
+ export declare function resetPythonCacheForTesting(): void;
36
+ export declare function formatEnvironmentFacts(processRef?: any, pythonDetector?: () => PythonEnvInfo | null): string;
37
+
38
+ export declare function resolveDshHome(env?: NodeJS.ProcessEnv): string;
39
+ export declare function resolveGlobalPath(filePath?: string, env?: NodeJS.ProcessEnv): string;
40
+ export declare function resolveWorkspacePath(workspaceRoot?: string | null, relativeOrPath?: string): string | null;
41
+ export declare function resolveWorkspaceRoot(ctx: Context, context?: any): string;
42
+
43
+ export declare class CustomPromptManager {
44
+ readonly config: CustomPromptOptions;
45
+ readonly globalFilePath: string;
46
+ constructor(options?: CustomPromptOptions);
47
+ loadGlobal(): void;
48
+ loadWorkspace(workspaceRoot?: string | null): string | null;
49
+ getGlobalPrompt(): string;
50
+ getWorkspacePrompt(workspaceRoot?: string | null): string;
51
+ getEffectivePrompt(workspaceRoot?: string | null): string;
52
+ reload(): void;
53
+ dispose(): void;
54
+ }
55
+
56
+ export declare function applyCustomPrompt(ctx: Context, rawConfig?: CustomPromptOptions): CustomPromptManager | null;
57
+
58
+ export declare const Config: typeof CustomPromptConfig;
59
+ export declare function apply(ctx: Context, config?: CustomPromptOptions): void;
60
+
61
+ declare const _default: {
62
+ name: typeof name;
63
+ inject: typeof inject;
64
+ Config: typeof Config;
65
+ apply: typeof apply;
66
+ };
67
+ export default _default;