Repository navigation
Expand file tree
/
Copy pathbatch.ts
More file actions
387 lines (364 loc) · 12.7 KB
/
Copy pathbatch.ts
File metadata and controls
387 lines (364 loc) · 12.7 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// 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,
namesSessionExplicitly,
} from '@agent-device/kernel/contracts';
import {
AppError,
asAppError,
BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON,
type DaemonError,
} from '@agent-device/kernel/errors';
import { isRecord } from '@agent-device/kernel/record';
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';
import { resolveCommandRecordingEffect } from './registry.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>;
};
/**
* What the batch runner knows about a step's place in its plan. The daemon uses the remaining
* commands to derive platform readiness policy; it never reaches the wire.
*/
export type BatchStepContext = Readonly<{
stepNumber: number;
totalSteps: number;
/** The steps still ahead, in the shape their handlers will read. */
remainingSteps: readonly Readonly<{
command: string;
positionals: readonly string[];
flags: Readonly<Record<string, unknown>>;
input?: Readonly<Record<string, unknown>>;
}>[];
}>;
export type BatchInvoke = (req: BatchRequest, context: BatchStepContext) => 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, {
stepNumber: index + 1,
totalSteps: steps.length,
remainingSteps: steps.slice(index + 1).map((remaining) => ({
command: remaining.command,
positionals: remaining.positionals,
flags: remaining.flags,
...(remaining.input === undefined ? {} : { input: remaining.input }),
})),
});
if (!stepResponse.ok) {
return batchStepFailure(stepResponse, step, {
executedSteps: steps.slice(0, 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);
}
}
type BatchStepFailure = Extract<Awaited<ReturnType<typeof runBatchStep>>, { ok: false }>;
function batchStepFailure(
stepResponse: BatchStepFailure,
step: NormalizedBatchStep,
progress: {
executedSteps: readonly NormalizedBatchStep[];
total: number;
partialResults: BatchStepResult[];
},
): Extract<BatchRunResponse, { ok: false }> {
const { error } = stepResponse;
return {
ok: false,
error: {
code: error.code,
message: `Batch failed at step ${stepResponse.step} (${step.command}): ${error.message}`,
hint: error.hint,
diagnosticId: error.diagnosticId,
logPath: error.logPath,
...(error.retriable === undefined ? {} : { retriable: error.retriable }),
...(error.supportedOn === undefined ? {} : { supportedOn: error.supportedOn }),
details: {
...(error.details ?? {}),
...(progress.executedSteps.some(stepMayMutateApp) &&
!(
error.details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON &&
error.details.dispatched === 'no'
)
? { dispatched: 'unknown' }
: {}),
step: stepResponse.step,
command: step.command,
positionals: step.positionals,
executed: progress.executedSteps.length,
total: progress.total,
partialResults: progress.partialResults,
},
},
};
}
/** A batch reports no only when every executed step is a declared read. */
function stepMayMutateApp(step: NormalizedBatchStep): boolean {
return resolveCommandRecordingEffect(step) !== 'observes-app';
}
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.`);
}
assertNoTextStdinStep(step.flags as Record<string, unknown> | undefined, index + 1);
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;
}
/**
* A batch step has no stdin of its own, and a failed step reports its positionals. The CLI refuses
* `textStdin: true` on a step before reading stdin; this refuses it for every other daemon client.
* `false` is the ordinary argv path, and a value of another type is refused per step by the router.
*/
function assertNoTextStdinStep(
flags: Record<string, unknown> | undefined,
stepNumber: number,
): void {
if (flags?.textStdin !== true) return;
throw new AppError(
'INVALID_ARGS',
`Batch step ${stepNumber}: fill textStdin is not supported because batch steps have no stdin of their own.`,
{ reason: 'fill_text_stdin_in_batch' },
);
}
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,
context: BatchStepContext,
): Promise<
| { ok: true; step: number; result: BatchStepResult }
| {
ok: false;
step: number;
error: DaemonError;
}
> {
const { stepNumber, totalSteps } = context;
const isFinalStep = stepNumber === totalSteps;
const stepStartedAt = Date.now();
const stepFlags = buildBatchStepFlags(req.flags, step.flags);
// The step is already addressed through `session:` below. Stamp the flag only when the caller
// genuinely named a session: an unconditional stamp would make a sessionless batch look
// caller-addressed to the daemon's named-session refusal, which no caller of this surface asked
// for (#3674). A step's own recorded flag always wins, explicit parent or not.
if (stepFlags.session === undefined && namesSessionExplicitly(req)) {
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),
},
context,
);
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 } : {}) },
};
}