dsh-awesome-optimizer 0.0.0-stage → 1.5.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/LICENSE +21 -0
- package/README.md +217 -2
- package/README.zh.md +218 -0
- package/cordis.patch.yml +42 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +112 -4
- package/scripts/benchmark.mjs +113 -0
- package/scripts/typecheck.mjs +57 -0
- package/src/composite-tools.d.ts +37 -0
- package/src/composite-tools.js +417 -0
- package/src/convergence.d.ts +33 -0
- package/src/convergence.js +173 -0
- package/src/custom-prompt.d.ts +56 -0
- package/src/custom-prompt.js +303 -0
- package/src/failure-recovery.d.ts +66 -0
- package/src/failure-recovery.js +289 -0
- package/src/file-mutation-policy.d.ts +44 -0
- package/src/file-mutation-policy.js +298 -0
- package/src/index.d.ts +97 -0
- package/src/index.js +95 -0
- package/src/prompt-linter.d.ts +43 -0
- package/src/prompt-linter.js +310 -0
- package/src/runtime-policy.d.ts +72 -0
- package/src/runtime-policy.js +494 -0
- package/src/telemetry.d.ts +79 -0
- package/src/telemetry.js +333 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createTestRuntime, call } from '../test/support/runtime.js';
|
|
3
|
+
import { compareTurnSummaries, PAIRING_ERROR } from '../src/index.js';
|
|
4
|
+
|
|
5
|
+
// Run deterministic A/B verification scenarios over the unchanged official @deepseek-ai/dsh-agent-loop.
|
|
6
|
+
async function runBatchReadScenario() {
|
|
7
|
+
const files = {
|
|
8
|
+
'a.txt': 'Alpha content line 1\nAlpha content line 2',
|
|
9
|
+
'b.txt': 'Beta content line 1\nBeta content line 2',
|
|
10
|
+
'c.txt': 'Gamma content line 1\nGamma content line 2'
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// Baseline: sequential single-file reads across 3 steps + final answer (4 model requests)
|
|
14
|
+
const baselineHost = await createTestRuntime({
|
|
15
|
+
optimizerEnabled: true,
|
|
16
|
+
optimizerConfig: {
|
|
17
|
+
compositeTools: { enabled: false },
|
|
18
|
+
convergence: { enabled: false }
|
|
19
|
+
},
|
|
20
|
+
files,
|
|
21
|
+
script: [
|
|
22
|
+
[call('r1', 'read', { file_path: 'a.txt' })],
|
|
23
|
+
[call('r2', 'read', { file_path: 'b.txt' })],
|
|
24
|
+
[call('r3', 'read', { file_path: 'c.txt' })],
|
|
25
|
+
[{ type: 'text', text: 'Synthesized alpha, beta, gamma.' }]
|
|
26
|
+
]
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// Candidate: read_batch collapses 3 file reads into 1 round-trip + final answer (2 model requests)
|
|
30
|
+
const candidateHost = await createTestRuntime({
|
|
31
|
+
optimizerEnabled: true,
|
|
32
|
+
files,
|
|
33
|
+
script: [
|
|
34
|
+
[call('rb1', 'read_batch', {
|
|
35
|
+
files: [
|
|
36
|
+
{ file_path: 'a.txt' },
|
|
37
|
+
{ file_path: 'b.txt' },
|
|
38
|
+
{ file_path: 'c.txt' }
|
|
39
|
+
]
|
|
40
|
+
})],
|
|
41
|
+
[{ type: 'text', text: 'Synthesized alpha, beta, gamma.' }]
|
|
42
|
+
]
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
await baselineHost.run('Read a.txt, b.txt, and c.txt and summarize.');
|
|
47
|
+
await candidateHost.run('Read a.txt, b.txt, and c.txt and summarize.');
|
|
48
|
+
|
|
49
|
+
const baseSummary = baselineHost.telemetry.getSummary(baselineHost.agent.session);
|
|
50
|
+
const candSummary = candidateHost.telemetry.getSummary(candidateHost.agent.session);
|
|
51
|
+
const comparison = compareTurnSummaries(baseSummary, candSummary);
|
|
52
|
+
|
|
53
|
+
assert.equal(baseSummary.modelRequests, 4);
|
|
54
|
+
assert.equal(candSummary.modelRequests, 2);
|
|
55
|
+
assert.equal(candSummary.ptcSubCalls, 3);
|
|
56
|
+
assert.equal(comparison.modelRequests.delta, -2);
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
scenario: 'multi-file-read-collapse',
|
|
60
|
+
baseline: baseSummary,
|
|
61
|
+
candidate: candSummary,
|
|
62
|
+
comparison
|
|
63
|
+
};
|
|
64
|
+
} finally {
|
|
65
|
+
await baselineHost.dispose();
|
|
66
|
+
await candidateHost.dispose();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function runWriteRecoveryScenario() {
|
|
71
|
+
const largePayload = 'x'.repeat(9000);
|
|
72
|
+
const host = await createTestRuntime({
|
|
73
|
+
optimizerEnabled: true,
|
|
74
|
+
script: [
|
|
75
|
+
[call('w1', 'write', {
|
|
76
|
+
file_path: 'deliverable.txt',
|
|
77
|
+
content: largePayload,
|
|
78
|
+
justification: 'Unpaired justification rejected when approval prompts are disabled'
|
|
79
|
+
})],
|
|
80
|
+
[call('rw1', 'retry_failed_write', { call_id: 'w1' })],
|
|
81
|
+
[{ type: 'text', text: 'Recovered large write without regenerating 9KB content.' }]
|
|
82
|
+
],
|
|
83
|
+
writeHandler(args) {
|
|
84
|
+
if (args.justification && !args.sandbox_permissions) {
|
|
85
|
+
throw new Error(PAIRING_ERROR);
|
|
86
|
+
}
|
|
87
|
+
return `Wrote ${args.file_path} (${args.content.length} bytes)`;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
await host.run('Write deliverable.txt.');
|
|
93
|
+
const summary = host.telemetry.getSummary(host.agent.session);
|
|
94
|
+
assert.equal(summary.failureRecovery?.succeeded, 1);
|
|
95
|
+
return {
|
|
96
|
+
scenario: 'failed-large-write-recovery',
|
|
97
|
+
summary
|
|
98
|
+
};
|
|
99
|
+
} finally {
|
|
100
|
+
await host.dispose();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const batchScenario = await runBatchReadScenario();
|
|
105
|
+
const recoveryScenario = await runWriteRecoveryScenario();
|
|
106
|
+
|
|
107
|
+
console.log(JSON.stringify({
|
|
108
|
+
mode: 'official-loop-ab-verification',
|
|
109
|
+
officialLoopReplaced: false,
|
|
110
|
+
networkRequests: 0,
|
|
111
|
+
note: 'Offline scripted verification proves mechanism and telemetry fidelity. Run identical live tasks to evaluate model-specific round-trip reductions.',
|
|
112
|
+
scenarios: [batchScenario, recoveryScenario]
|
|
113
|
+
}, null, 2));
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
|
|
10
|
+
function findTsc() {
|
|
11
|
+
const searchBases = [
|
|
12
|
+
root,
|
|
13
|
+
path.resolve(root, '../Awesome-Canvas/web'),
|
|
14
|
+
path.resolve(root, '../threejs-projects'),
|
|
15
|
+
'D:/nodejs/node_global/node_modules/@deepseek-ai/dsh',
|
|
16
|
+
'D:/nodejs/node_global'
|
|
17
|
+
];
|
|
18
|
+
for (const base of searchBases) {
|
|
19
|
+
try {
|
|
20
|
+
const baseReq = createRequire(path.join(base, 'package.json'));
|
|
21
|
+
const pkgFile = baseReq.resolve('typescript/package.json');
|
|
22
|
+
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
23
|
+
const binRel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.tsc;
|
|
24
|
+
if (binRel) {
|
|
25
|
+
return path.resolve(path.dirname(pkgFile), binRel);
|
|
26
|
+
}
|
|
27
|
+
} catch {
|
|
28
|
+
// Try next candidate
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const tscBin = findTsc();
|
|
35
|
+
if (tscBin) {
|
|
36
|
+
const res = spawnSync(process.execPath, [tscBin, '--project', path.join(root, 'tsconfig.json'), '--noEmit'], {
|
|
37
|
+
cwd: root,
|
|
38
|
+
stdio: 'inherit'
|
|
39
|
+
});
|
|
40
|
+
if (res.error) throw res.error;
|
|
41
|
+
process.exitCode = res.status ?? 1;
|
|
42
|
+
} else {
|
|
43
|
+
// Verify all declared .d.ts files exist and match package.json exports
|
|
44
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
|
45
|
+
for (const [subpath, entry] of Object.entries(pkg.exports)) {
|
|
46
|
+
if (typeof entry === 'object' && entry !== null && entry.types) {
|
|
47
|
+
const resolved = path.resolve(root, entry.types);
|
|
48
|
+
if (!fs.existsSync(resolved)) {
|
|
49
|
+
console.error(`Missing declaration file for export "${subpath}": ${entry.types}`);
|
|
50
|
+
process.exitCode = 1;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (!process.exitCode) {
|
|
55
|
+
console.log('Verified all package.json TypeScript declaration entrypoints exist.');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type z from '@deepseek-ai/schemastery';
|
|
3
|
+
|
|
4
|
+
export interface CompositeToolsOptions {
|
|
5
|
+
enabled?: boolean;
|
|
6
|
+
readBatch?: boolean;
|
|
7
|
+
editBatch?: boolean;
|
|
8
|
+
maxBatchFiles?: number;
|
|
9
|
+
maxBatchEdits?: number;
|
|
10
|
+
defaultLimitPerFile?: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface CompositeToolsStats {
|
|
14
|
+
batchesExecuted: number;
|
|
15
|
+
filesRequested: number;
|
|
16
|
+
filesSucceeded: number;
|
|
17
|
+
filesFailed: number;
|
|
18
|
+
editBatchesExecuted: number;
|
|
19
|
+
editsRequested: number;
|
|
20
|
+
editsSucceeded: number;
|
|
21
|
+
editsFailed: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface CompositeToolsService {
|
|
25
|
+
getStats(session: unknown): CompositeToolsStats;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export declare const READ_BATCH_TOOL: 'read_batch';
|
|
29
|
+
export declare const EDIT_BATCH_TOOL: 'edit_batch';
|
|
30
|
+
export declare const CompositeToolsConfig: z<CompositeToolsOptions>;
|
|
31
|
+
export declare function applyCompositeTools(ctx: Context, rawConfig?: CompositeToolsOptions): CompositeToolsService | null;
|
|
32
|
+
export declare const name: string;
|
|
33
|
+
export declare const inject: string[];
|
|
34
|
+
export declare const Config: z<CompositeToolsOptions>;
|
|
35
|
+
export declare function apply(ctx: Context, config?: CompositeToolsOptions): void;
|
|
36
|
+
declare const plugin: { name: typeof name; inject: typeof inject; Config: typeof Config; apply: typeof apply };
|
|
37
|
+
export default plugin;
|
|
@@ -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}) across one or more 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 across one or more 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;
|