-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathbatch.ts
More file actions
310 lines (292 loc) · 9.63 KB
/
Copy pathbatch.ts
File metadata and controls
310 lines (292 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// The step SHAPE lives in contracts/ so the public API vocabulary can be stated in terms of it
// without depending on core/; re-exported here for this module's existing consumers.
import type { DaemonBatchStep } from '@agent-device/contracts/command';
import {
type DaemonRequest,
type DaemonResponse,
type ResponseLevel,
isNonDefaultResponseLevel,
} from '@agent-device/kernel/contracts';
import { AppError, asAppError } from '@agent-device/kernel/errors';
import { isRecord } from '../utils/parsing.ts';
import {
DEFAULT_BATCH_MAX_STEPS,
assertBatchStepCount,
isValidBatchMaxSteps,
parseBatchStepRuntime,
} from '@agent-device/contracts/command';
import {
BATCH_DAEMON_STEP_KEYS,
INHERITED_PARENT_FLAG_KEYS,
assertBatchRuntimeCommandAllowed,
normalizeBatchCommandName,
} from './batch-policy.ts';
const batchAllowedStepKeys = new Set<string>(BATCH_DAEMON_STEP_KEYS);
export type BatchFlags = Record<string, unknown> & {
batchOnError?: 'stop';
batchMaxSteps?: number;
batchSteps?: DaemonBatchStep[];
};
export type BatchRequest = Omit<DaemonRequest, 'flags'> & {
flags?: BatchFlags | Record<string, unknown>;
};
export type BatchInvoke = (req: BatchRequest) => Promise<DaemonResponse>;
export type NormalizedBatchStep = {
command: string;
positionals: string[];
input?: Record<string, unknown>;
flags: Record<string, unknown>;
runtime?: DaemonRequest['runtime'];
};
export type BatchStepResult = {
step: number;
command: string;
ok: true;
data: Record<string, unknown>;
durationMs: number;
};
export type BatchRunResult = Record<string, unknown> & {
total: number;
executed: number;
totalDurationMs: number;
results: BatchStepResult[];
};
export type BatchRunResponse =
| {
ok: true;
data: BatchRunResult;
}
| Extract<DaemonResponse, { ok: false }>;
export async function runBatch(
req: BatchRequest,
sessionName: string,
invoke: BatchInvoke,
): Promise<BatchRunResponse> {
const flags = readBatchFlags(req.flags);
const batchOnError = flags?.batchOnError ?? 'stop';
if (batchOnError !== 'stop') {
return batchErrorResponse('INVALID_ARGS', `Unsupported batch on-error mode: ${batchOnError}.`);
}
const batchMaxSteps = flags?.batchMaxSteps ?? DEFAULT_BATCH_MAX_STEPS;
if (!isValidBatchMaxSteps(batchMaxSteps)) {
return batchErrorResponse(
'INVALID_ARGS',
`Invalid batch max-steps: ${String(flags?.batchMaxSteps)}`,
);
}
try {
const steps = validateAndNormalizeBatchSteps(flags?.batchSteps, batchMaxSteps);
const startedAt = Date.now();
const partialResults: BatchStepResult[] = [];
for (const [index, step] of steps.entries()) {
const stepResponse = await runBatchStep(
req,
sessionName,
step,
invoke,
index + 1,
index === steps.length - 1,
);
if (!stepResponse.ok) {
return {
ok: false,
error: {
code: stepResponse.error.code,
message: `Batch failed at step ${stepResponse.step} (${step.command}): ${stepResponse.error.message}`,
hint: stepResponse.error.hint,
diagnosticId: stepResponse.error.diagnosticId,
logPath: stepResponse.error.logPath,
details: {
...(stepResponse.error.details ?? {}),
step: stepResponse.step,
command: step.command,
positionals: step.positionals,
executed: index,
total: steps.length,
partialResults,
},
},
};
}
partialResults.push(stepResponse.result);
}
const data: BatchRunResult = {
total: steps.length,
executed: steps.length,
totalDurationMs: Date.now() - startedAt,
results: partialResults,
};
return {
ok: true,
data,
};
} catch (error) {
const appErr = asAppError(error);
return batchErrorResponse(appErr.code, appErr.message, appErr.details);
}
}
export function validateAndNormalizeBatchSteps(
steps: unknown,
maxSteps: number,
): NormalizedBatchStep[] {
if (!Array.isArray(steps) || steps.length === 0) {
throw new AppError('INVALID_ARGS', 'batch requires a non-empty batchSteps array.');
}
assertBatchStepCount(steps.length, maxSteps);
const normalized: NormalizedBatchStep[] = [];
for (let index = 0; index < steps.length; index += 1) {
const step = steps[index];
if (!isRecord(step)) {
throw new AppError('INVALID_ARGS', `Invalid batch step at index ${index}.`);
}
const unknownKeys = Object.keys(step).filter((key) => !batchAllowedStepKeys.has(key));
if (unknownKeys.length > 0) {
const fields = unknownKeys.map((key) => `"${key}"`).join(', ');
throw new AppError(
'INVALID_ARGS',
`Batch step ${index + 1} has unknown field(s): ${fields}. Allowed fields: command, positionals, input, flags, runtime.`,
);
}
const command = normalizeBatchCommandName(step.command);
if (!command) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} requires command.`);
}
assertBatchRuntimeCommandAllowed(command, index + 1);
if (step.positionals !== undefined && !Array.isArray(step.positionals)) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} positionals must be an array.`);
}
const positionals = (step.positionals ?? []) as unknown[];
if (positionals.some((value) => typeof value !== 'string')) {
throw new AppError(
'INVALID_ARGS',
`Batch step ${index + 1} positionals must contain only strings.`,
);
}
if (step.flags !== undefined && !isRecord(step.flags)) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} flags must be an object.`);
}
if (step.input !== undefined && !isRecord(step.input)) {
throw new AppError('INVALID_ARGS', `Batch step ${index + 1} input must be an object.`);
}
normalized.push({
command,
positionals: positionals as string[],
input: step.input as Record<string, unknown> | undefined,
flags: (step.flags ?? {}) as Record<string, unknown>,
runtime: parseBatchStepRuntime(step.runtime, index + 1),
});
}
return normalized;
}
function buildBatchStepFlags(
parentFlags: BatchFlags | Record<string, unknown> | undefined,
stepFlags: DaemonBatchStep['flags'] | Record<string, unknown> | undefined,
): BatchFlags {
const {
batchSteps: _batchSteps,
batchOnError: _batchOnError,
batchMaxSteps: _batchMaxSteps,
...merged
} = stepFlags ?? {};
return mergeParentFlags(readBatchFlags(parentFlags), merged as BatchFlags);
}
export function mergeParentFlags<TFlags extends Record<string, unknown>>(
parentFlags: BatchFlags | Record<string, unknown> | undefined,
childFlags: TFlags,
): TFlags {
const parentRecord = readBatchFlags(parentFlags) ?? {};
const childRecord = childFlags as Record<string, unknown>;
for (const key of INHERITED_PARENT_FLAG_KEYS) {
if (childRecord[key] === undefined && parentRecord[key] !== undefined) {
childRecord[key] = parentRecord[key];
}
}
return childFlags;
}
// Phase 4 (agent-cost) batch-step elision. When a non-default response level is
// requested for the whole batch, INTERMEDIATE steps are forced to `digest` so a
// multi-step run collapses tokens, while the FINAL step keeps the requested
// level. With no responseLevel (or `default`) this is a no-op, so the per-step
// meta is passed through unchanged — byte-identical to today (Maestro `.ad`
// recompare safe).
function batchStepResponseLevel(
requested: ResponseLevel | undefined,
isFinalStep: boolean,
): ResponseLevel | undefined {
if (!isNonDefaultResponseLevel(requested)) return requested;
return isFinalStep ? requested : 'digest';
}
function batchStepMeta(meta: BatchRequest['meta'], isFinalStep: boolean): BatchRequest['meta'] {
const requested = meta?.responseLevel;
const stepLevel = batchStepResponseLevel(requested, isFinalStep);
if (stepLevel === requested) return meta;
return { ...meta, responseLevel: stepLevel };
}
async function runBatchStep(
req: BatchRequest,
sessionName: string,
step: NormalizedBatchStep,
invoke: BatchInvoke,
stepNumber: number,
isFinalStep: boolean,
): Promise<
| { ok: true; step: number; result: BatchStepResult }
| {
ok: false;
step: number;
error: {
code: string;
message: string;
hint?: string;
diagnosticId?: string;
logPath?: string;
details?: Record<string, unknown>;
};
}
> {
const stepStartedAt = Date.now();
const stepFlags = buildBatchStepFlags(req.flags, step.flags);
if (stepFlags.session === undefined) {
stepFlags.session = sessionName;
}
const response = await invoke({
token: req.token,
session: sessionName,
command: step.command,
positionals: step.positionals,
input: step.input,
flags: stepFlags,
runtime: step.runtime === undefined ? req.runtime : step.runtime,
meta: batchStepMeta(req.meta, isFinalStep),
});
const durationMs = Date.now() - stepStartedAt;
if (!response.ok) {
return { ok: false, step: stepNumber, error: response.error };
}
return {
ok: true,
step: stepNumber,
result: {
step: stepNumber,
command: step.command,
ok: true,
data: response.data ?? {},
durationMs,
},
};
}
function readBatchFlags(
flags: BatchFlags | Record<string, unknown> | undefined,
): BatchFlags | undefined {
return flags as BatchFlags | undefined;
}
function batchErrorResponse(
code: string,
message: string,
details?: Record<string, unknown>,
): Extract<DaemonResponse, { ok: false }> {
return {
ok: false,
error: { code, message, ...(details ? { details } : {}) },
};
}