-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathfactory.ts
More file actions
472 lines (439 loc) · 16.4 KB
/
Copy pathfactory.ts
File metadata and controls
472 lines (439 loc) · 16.4 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import type {
FactoryGetRunProgressRequest,
FactoryProgressPage,
FactoryRunDetail,
FactoryRunResult,
FactoryRunStatus,
FactoryRunSummary,
} from "./generated/rpc.js";
import type { ContextTier } from "./generated/session-events.js";
import type { CopilotSession } from "./session.js";
import type { FactoryLimits, FactoryMeta } from "./types.js";
export type { FactoryRunResult };
export type {
FactoryAgentSummary,
FactoryPhaseStatus,
FactoryPhaseObservation,
FactoryProgressLine,
FactoryProgressPage,
FactoryRunDetail,
FactoryRunStatus,
FactoryRunSummary,
} from "./generated/rpc.js";
/**
* Run statuses a factory run can no longer move away from.
*
* A run is either still in flight (`pending`, `running`) or settled into one of
* these four. Terminal state is final: once written it is never reopened, so a
* caller that observes one of these can stop watching the run.
*/
const FACTORY_TERMINAL_STATUSES: ReadonlySet<FactoryRunStatus> = new Set([
"completed",
"halted",
"cancelled",
"error",
]);
/**
* Whether a factory run status is terminal.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export function isFactoryRunTerminal(status: FactoryRunStatus): boolean {
return FACTORY_TERMINAL_STATUSES.has(status);
}
declare const factoryHandleBrand: unique symbol;
/** A value that can be represented losslessly on the SDK JSON wire. */
export type JsonValue =
| null
| boolean
| number
| string
| JsonValue[]
| { [key: string]: JsonValue };
/**
* Conservative JSON shape language accepted by the Agent Factories surface, for
* both structured factory agent output and a factory's declared `argsSchema`.
*
* This is a best-effort structural guard — used to decide whether a subagent's
* structured output should be accepted or retried, and whether a caller's
* factory `args` match the declared shape — **not** a full JSON Schema
* validator. Only these keywords are honored: `type`, `required`, `enum`,
* `const`, recursive `properties`/`items`, and `anyOf`/`oneOf`/`allOf`. A `type`
* is one of `null`, `boolean`, `integer`, `number`, `string`, `array`, or
* `object`, or a non-empty array of those (for example `["object", "null"]`).
*
* Everything else is **ignored, not enforced**. In particular, string
* constraints (`pattern`, `minLength`, `maxLength`, `format`), numeric ranges
* (`minimum`, `maximum`), `additionalProperties`, and boolean (`true`/`false`)
* schemas do not reject non-conforming output. `oneOf` is treated like `anyOf`
* (at least one branch must match) rather than strict exactly-one. Author
* schemas within this subset; do not rely on unsupported constraints for
* correctness.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export type FactoryJsonSchema = { [key: string]: JsonValue };
/**
* Options for one factory-scoped subagent call.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface FactoryAgentOptions {
label?: string;
schema?: FactoryJsonSchema;
model?: string;
reasoningEffort?: string;
contextTier?: ContextTier;
agent?: string;
}
export const FACTORY_AGENT_OPTION_KEYS = [
"label",
"schema",
"model",
"reasoningEffort",
"contextTier",
"agent",
] as const;
/**
* Options for a durable factory step.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface FactoryStepOptions {
/** Skip the journal and always invoke the producer. */
volatile?: boolean;
}
/**
* One stage in a per-item factory pipeline.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export type FactoryPipelineStage<TInput = unknown, TResult = unknown> = (
previous: TInput,
item: unknown,
index: number
) => Promise<TResult> | TResult;
/**
* Context passed to an extension-authored factory body.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface FactoryContext<TArgs extends JsonValue = JsonValue> {
/** Stable identifier for the current factory run. */
readonly runId: string;
/** Spawn and await one factory-scoped subagent. */
agent(prompt: string, options?: FactoryAgentOptions): Promise<unknown>;
/** Memoize an arbitrary producer under a stable author-supplied key. */
step(
key: string,
producer: () => Promise<JsonValue> | JsonValue,
options?: FactoryStepOptions
): Promise<JsonValue>;
/**
* Run thunks concurrently and await all of them.
*
* A thunk that throws becomes `null` in the result array, so one failed
* item does not lose the rest. Cancellation and hard runtime failures
* (`ResponseError`, `ConnectionError`) are the exception: those propagate
* and reject the whole call, because they mean the run itself is in
* trouble rather than one item having failed.
*/
parallel<TResult>(
thunks: Array<() => Promise<TResult> | TResult>
): Promise<Array<TResult | null>>;
/**
* Run each item through every stage without barriers between stages.
*
* A stage that throws drops that item to `null` and skips its remaining
* stages. As with {@link FactoryContext.parallel}, cancellation and hard
* runtime failures propagate instead of being recorded per item.
*/
pipeline(items: unknown[], ...stages: FactoryPipelineStage[]): Promise<unknown[]>;
/** Start a named factory progress phase. */
phase(title: string): void;
/** Emit a factory progress line. */
log(message: string): void;
/** Reject because nested factories are not supported. */
factory(name: string, args?: JsonValue): Promise<JsonValue | void>;
/** Caller-supplied input, forwarded verbatim. */
args: TArgs;
/**
* The session instance returned by `joinSession`. It refuses calls that
* start or resume a factory run.
*/
session: CopilotSession;
/** Cooperative cancellation signal for the current factory run. */
signal: AbortSignal;
}
/**
* Definition accepted by {@link defineFactory}.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface FactoryDefinition<
TArgs extends JsonValue = JsonValue,
TResult extends JsonValue | void = JsonValue | void,
> {
meta: FactoryMeta;
run(context: FactoryContext<TArgs>): Promise<TResult>;
}
/**
* A deeply immutable view of a value.
*
* `defineFactory` deep-freezes the metadata it stores, so the handle's view of
* it has to be readonly all the way down or `handle.meta.name = "..."` and
* `handle.meta.phases.push(...)` would compile and then throw at runtime.
*/
type DeepReadonly<T> = T extends (infer U)[]
? readonly DeepReadonly<U>[]
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
/**
* Opaque reusable reference to a defined factory.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface FactoryHandle<
TArgs extends JsonValue = JsonValue,
TResult extends JsonValue | void = JsonValue | void,
> {
readonly meta: DeepReadonly<FactoryMeta>;
readonly [factoryHandleBrand]: {
readonly args: TArgs;
readonly result: TResult;
};
}
/**
* Options for invoking a factory.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface RunOptions<TArgs extends JsonValue = JsonValue> {
/** Input surfaced as `context.args`. */
args?: TArgs;
/** Optional per-invocation resource ceiling overrides. */
limits?: FactoryLimits;
/**
* Prior run whose persisted identity, arguments, journal, and accounting should be resumed.
*
* @deprecated Use {@link SessionFactoryApi.resume} instead.
*/
resumeFromRunId?: string;
}
/**
* Options for resuming a factory run by ID.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface ResumeOptions {
/** Optional per-invocation resource ceiling overrides. */
limits?: FactoryLimits;
}
/**
* Machine-readable pre-execution factory resume failure.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export type FactoryResumeErrorCode =
| "not_found"
| "non_resumable"
| "already_active"
| "factory_already_running"
| "factory_limits_invalid"
| "factory_session_disposed"
| "factory_storage_unavailable"
| "factory_storage_corrupt";
/**
* Friendly factory API exposed on a session.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export interface SessionFactoryApi {
/**
* Run a registered factory and resolve with its run envelope.
*
* The envelope is returned for every outcome, including `error`, `halted`,
* and `cancelled` — inspect `status` and read `result` only when the run
* completed. SDK-initiated runs do not request permission, so they have no
* declined outcome. The model's `run_factory` tool requests permission
* before a durable row exists; declining it creates no run row. Failures
* that occur before a run exists (such as an unknown factory or attempting
* to start a run while the session is at its active top-level run limit)
* still reject.
*/
run(name: string, options?: RunOptions): Promise<FactoryRunResult>;
run<TArgs extends JsonValue>(
factory: FactoryHandle<TArgs, JsonValue | void>,
options?: RunOptions<TArgs>
): Promise<FactoryRunResult>;
/**
* Resume a run from its persisted factory name, arguments, journal, and accounting.
*
* Resolves with the run envelope like {@link SessionFactoryApi.run}.
* SDK-initiated resumes do not request permission. A pre-execution failure
* with a documented resume code rejects with {@link FactoryResumeError}.
*/
resume(runId: string, options?: ResumeOptions): Promise<FactoryRunResult>;
/** Read the latest durable envelope for a factory run. */
getRun(runId: string): Promise<FactoryRunResult>;
/**
* Wait for a run to settle and resolve with its terminal envelope.
*
* Resolves as soon as the run reaches `completed`, `error`, `halted`, or
* `cancelled`, and resolves immediately when it has already settled. A
* terminal envelope is final, so the resolved value never changes
* afterwards.
*
* This watches the run's `factory.run_updated` invalidation events and
* periodically re-reads the durable envelope so a missed event cannot
* leave the wait hanging. Pass a `signal` to stop waiting; aborting rejects
* and has no effect on the run itself, which keeps executing. Use
* {@link SessionFactoryApi.cancel} to actually stop it.
*/
waitForRun(runId: string, options?: { signal?: AbortSignal }): Promise<FactoryRunResult>;
/**
* List the newest default page of this session's durable factory runs.
*/
listRuns(): Promise<FactoryRunSummary[]>;
/** Read durable phases, direct agents, and the latest progress tail for a run. */
getRunDetail(runId: string): Promise<FactoryRunDetail>;
/** Page durable progress forward, backward, or from the latest tail. */
getRunProgress(
runId: string,
options?: Omit<FactoryGetRunProgressRequest, "runId">
): Promise<FactoryProgressPage>;
/** Cancel a factory run and return its terminal envelope. */
cancel(runId: string): Promise<FactoryRunResult>;
}
/**
* Error thrown when a factory cannot be resumed before execution begins.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export class FactoryResumeError extends Error {
constructor(
public readonly code: FactoryResumeErrorCode,
message: string
) {
super(message);
this.name = "FactoryResumeError";
}
}
interface StoredFactory {
meta: FactoryMeta;
run(context: FactoryContext): Promise<JsonValue | void>;
}
const factoryHandles = new WeakMap<object, StoredFactory>();
/** Maximum accepted factory timeout in seconds, derived from Node's maximum timer delay. */
const MAX_FACTORY_TIMEOUT_SECONDS = 2_147_483.647;
const NANO_AIU_PER_AIU = 1_000_000_000;
function deepFreeze<T>(value: T): T {
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
Object.freeze(value);
for (const nested of Object.values(value)) {
deepFreeze(nested);
}
}
return value;
}
function validateLimits(meta: FactoryMeta): void {
const limits = meta.limits;
if (!limits) {
return;
}
for (const field of ["maxConcurrentSubagents", "maxTotalSubagents"] as const) {
const value = limits[field];
if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {
throw new Error(`Factory limit "${field}" must be a positive integer`);
}
}
if (
limits.timeoutSeconds !== undefined &&
(!Number.isFinite(limits.timeoutSeconds) || limits.timeoutSeconds <= 0)
) {
throw new Error(
'Factory limit "timeoutSeconds" must be a positive, finite number of seconds'
);
}
if (
limits.timeoutSeconds !== undefined &&
limits.timeoutSeconds > MAX_FACTORY_TIMEOUT_SECONDS
) {
throw new Error(
`Factory limit "timeoutSeconds" must not exceed ${MAX_FACTORY_TIMEOUT_SECONDS} seconds`
);
}
if (limits.maxAiCredits !== undefined) {
const maxNanoAiu = Math.round(limits.maxAiCredits * NANO_AIU_PER_AIU);
if (
!Number.isFinite(limits.maxAiCredits) ||
limits.maxAiCredits <= 0 ||
!Number.isSafeInteger(maxNanoAiu) ||
maxNanoAiu < 1
) {
throw new Error(
'Factory limit "maxAiCredits" must be a positive, finite number that rounds to a safe positive integer nano-AIU ceiling'
);
}
}
}
function validatePhases(meta: FactoryMeta): void {
const titles = new Set<string>();
for (const phase of meta.phases) {
if (phase.title.trim().length === 0) {
throw new Error("Factory phase titles must not be empty");
}
if (titles.has(phase.title)) {
throw new Error(`Factory phase title "${phase.title}" is declared more than once`);
}
titles.add(phase.title);
}
}
/**
* Defines an extension-authored factory and returns an opaque registration handle.
*
* @experimental Part of the experimental Agent Factories surface and may
* change or be removed in future SDK or CLI releases.
*/
export function defineFactory<
TArgs extends JsonValue = JsonValue,
TResult extends JsonValue | void = JsonValue | void,
>(definition: FactoryDefinition<TArgs, TResult>): FactoryHandle<TArgs, TResult> {
// Snapshot before validating so post-registration mutation of the caller's
// object cannot slip past the authoring-boundary checks.
const meta = deepFreeze(structuredClone(definition.meta));
validateLimits(meta);
validatePhases(meta);
const stored: StoredFactory = {
meta,
run: definition.run,
};
const handle = Object.freeze({ meta }) as unknown as FactoryHandle<TArgs, TResult>;
factoryHandles.set(handle, stored);
return handle;
}
/** @internal */
export function getFactoryDefinition(handle: FactoryHandle): StoredFactory {
const definition = factoryHandles.get(handle);
if (!definition) {
throw new Error("Invalid factory handle");
}
return definition;
}