forked from github/copilot-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.test.ts
More file actions
2425 lines (2243 loc) · 94.6 KB
/
Copy pathfactory.test.ts
File metadata and controls
2425 lines (2243 loc) · 94.6 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import { readFileSync } from "node:fs";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { ResponseError } from "vscode-jsonrpc/node.js";
import { CopilotClient } from "../src/client.js";
import { joinSession } from "../src/extension.js";
import { CopilotSession } from "../src/session.js";
import {
defineFactory,
FactoryResumeError,
isFactoryRunTerminal,
type FactoryAgentOptions,
type FactoryContext,
type FactoryDefinition,
type FactoryJsonSchema,
type JsonValue,
} from "../src/factory.js";
/** Builds a `factory.run_updated` invalidation event for a run. */
function runUpdatedEvent(runId: string, revision: number): Record<string, unknown> {
return {
type: "factory.run_updated",
id: `event-${runId}-${revision}`,
parentId: null,
timestamp: new Date().toISOString(),
ephemeral: true,
data: { runId, revision },
};
}
async function stopClient(client: CopilotClient): Promise<void> {
await client.stop();
}
describe("factories", () => {
const originalSessionId = process.env.SESSION_ID;
afterEach(() => {
if (originalSessionId === undefined) {
delete process.env.SESSION_ID;
} else {
process.env.SESSION_ID = originalSessionId;
}
vi.restoreAllMocks();
});
it("defines a stable handle and accepts omitted limits", async () => {
const meta = {
name: "no-limits",
description: "A factory without resource limits",
phases: [],
};
const run = vi.fn(async ({ args }: { args: unknown }) => args);
const handle = defineFactory({ meta, run });
expect(handle.meta).toEqual(meta);
expect(handle.meta).not.toBe(meta);
expect(Object.isFrozen(handle)).toBe(true);
expect(Object.isFrozen(handle.meta)).toBe(true);
// The handle holds a snapshot, so mutating the caller's object after
// registration cannot desynchronize the advertised metadata.
meta.name = "mutated";
(meta.phases as string[]).push("late");
expect(handle.meta.name).toBe("no-limits");
expect(handle.meta.phases).toEqual([]);
meta.name = "no-limits";
meta.phases.length = 0;
// The stored metadata is deep-frozen, so the handle's view of it must be
// readonly all the way down. Assert both halves: the mutation is a type
// error, and it also throws at runtime.
expect(() => {
// @ts-expect-error handle.meta is deeply readonly.
handle.meta.name = "mutated";
}).toThrow(TypeError);
expect(() => {
// @ts-expect-error handle.meta.phases is a readonly array.
handle.meta.phases.push({ title: "late" });
}).toThrow(TypeError);
const session = new CopilotSession("session-1", {} as never);
session.registerFactories([handle]);
const result = await session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: meta.name,
runId: "run-1",
executionToken: "execution-token",
args: { value: 42 },
});
expect(run).toHaveBeenCalledOnce();
expect(result).toEqual({ result: { value: 42 } });
});
it.each([
[[{ title: "" }], "must not be empty"],
[[{ title: "Inspect" }, { title: "Inspect" }], "declared more than once"],
])("rejects invalid declared phase titles", (phases, message) => {
expect(() =>
defineFactory({
meta: {
name: "invalid-phases",
description: "Invalid phase metadata",
phases,
},
run: async () => {},
})
).toThrow(message);
});
it("returns an absent execute result for a void factory", async () => {
const factory = defineFactory({
meta: {
name: "void-result",
description: "Returns no result",
phases: [],
},
run: async () => {},
});
const session = new CopilotSession("session-void-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "void-result",
runId: "run-void-result",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({});
});
it.each<JsonValue>([42, "factory-result", [1, "two", false]])(
"returns non-object JSON factory result %j",
async (factoryResult) => {
const factory = defineFactory({
meta: {
name: "json-result",
description: "Returns any JSON value",
phases: [],
},
run: async () => factoryResult,
});
const session = new CopilotSession("session-json-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "json-result",
runId: "run-json-result",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({ result: factoryResult });
}
);
it.each([
["function", { nested: () => undefined }, "$.nested"],
["symbol", [Symbol("invalid")], "$[0]"],
["BigInt", { nested: 1n }, "$.nested"],
])("rejects a %s anywhere in a factory result", async (_label, factoryResult, expectedPath) => {
const factory = defineFactory({
meta: {
name: "unsupported-result",
description: "Returns an unsupported value",
phases: [],
},
run: async () => factoryResult as never,
});
const session = new CopilotSession("session-unsupported-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "unsupported-result",
runId: "run-unsupported-result",
executionToken: "execution-token",
args: {},
})
).rejects.toMatchObject({
message: `Factory result contains a function, symbol, or BigInt at ${expectedPath}`,
data: {
code: "factory_result_not_json",
category: "unsupported_type",
},
});
});
it.each([
["NaN", Number.NaN],
["Infinity", Number.POSITIVE_INFINITY],
])("rejects the non-finite number %s in a factory result", async (_label, value) => {
const factory = defineFactory({
meta: {
name: "non-finite-result",
description: "Returns a non-finite number",
phases: [],
},
run: async () => ({ value }) as never,
});
const session = new CopilotSession("session-non-finite-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "non-finite-result",
runId: "run-non-finite-result",
executionToken: "execution-token",
args: {},
})
).rejects.toMatchObject({
message: "Factory result contains a non-finite number at $.value",
data: {
code: "factory_result_not_json",
category: "non_finite_number",
},
});
});
it("rejects a cyclic factory result", async () => {
const factoryResult: Record<string, unknown> = {};
factoryResult.self = factoryResult;
const factory = defineFactory({
meta: {
name: "cyclic-result",
description: "Returns a cycle",
phases: [],
},
run: async () => factoryResult as never,
});
const session = new CopilotSession("session-cyclic-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "cyclic-result",
runId: "run-cyclic-result",
executionToken: "execution-token",
args: {},
})
).rejects.toMatchObject({
message: "Factory result contains a cyclic reference at $.self",
data: {
code: "factory_result_not_json",
category: "cyclic_value",
},
});
});
it.each([
["object", { nested: undefined }, "$.nested"],
["array", [undefined], "$[0]"],
])(
"rejects nested undefined in a factory result %s",
async (_label, factoryResult, expectedPath) => {
const factory = defineFactory({
meta: {
name: "nested-undefined-result",
description: "Returns nested undefined",
phases: [],
},
run: async () => factoryResult as never,
});
const session = new CopilotSession("session-nested-undefined-result", {} as never);
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "nested-undefined-result",
runId: "run-nested-undefined-result",
executionToken: "execution-token",
args: {},
})
).rejects.toMatchObject({
message: `Factory result contains nested undefined at ${expectedPath}`,
data: {
code: "factory_result_not_json",
category: "nested_undefined",
},
});
}
);
it("rejects duplicate factory names within a single registration", () => {
const run = async () => null;
const first = defineFactory({
meta: { name: "dup", description: "first", phases: [] },
run,
});
const second = defineFactory({
meta: { name: "dup", description: "second", phases: [] },
run,
});
const session = new CopilotSession("session-dup", {} as never);
expect(() => session.registerFactories([first, second])).toThrow(
/Duplicate factory name "dup"/
);
});
it.each([
["maxConcurrentSubagents", 0],
["maxConcurrentSubagents", 1.5],
["maxTotalSubagents", -1],
["maxTotalSubagents", Number.POSITIVE_INFINITY],
["timeoutSeconds", 0],
["timeoutSeconds", Number.NaN],
["timeoutSeconds", Number.POSITIVE_INFINITY],
["maxAiCredits", 0],
["maxAiCredits", Number.NaN],
["maxAiCredits", Number.POSITIVE_INFINITY],
["maxAiCredits", 0.000_000_000_4],
["maxAiCredits", (Number.MAX_SAFE_INTEGER + 2) / 1_000_000_000],
] as const)("rejects invalid %s limit %s", (field, value) => {
const definition = {
meta: {
name: `invalid-${field}-${String(value)}`,
description: "Invalid factory",
phases: [],
limits: { [field]: value },
},
run: async () => null,
} as FactoryDefinition;
expect(() => defineFactory(definition)).toThrow(/must be a positive/);
});
it("accepts positive fractional timeoutSeconds through the Node timer ceiling", () => {
for (const timeoutSeconds of [0.001, 1.5, 2_147_483.647]) {
expect(() =>
defineFactory({
meta: {
name: `accepted-timeout-${timeoutSeconds}`,
description: "Factory with an accepted active-execution timeout",
phases: [],
limits: { timeoutSeconds },
},
run: async () => null,
})
).not.toThrow();
}
});
it("accepts AI-credit ceilings that round to a positive safe nano-AIU integer", () => {
for (const maxAiCredits of [
0.000_000_000_5,
1.25,
Number.MAX_SAFE_INTEGER / 1_000_000_000,
]) {
expect(() =>
defineFactory({
meta: {
name: `accepted-credits-${maxAiCredits}`,
description: "Factory with an accepted AI-credit ceiling",
phases: [],
limits: { maxAiCredits },
},
run: async () => null,
})
).not.toThrow();
}
});
it("rejects timeoutSeconds above the Node setTimeout ceiling", () => {
const definition = {
meta: {
name: "oversized-timeout",
description: "Factory with an out-of-range timeout",
phases: [],
limits: { timeoutSeconds: 2_147_483.648 },
},
run: async () => null,
} as FactoryDefinition;
expect(() => defineFactory(definition)).toThrow(
'Factory limit "timeoutSeconds" must not exceed 2147483.647 seconds'
);
});
it("documents timeoutSeconds as accumulated active-execution time in public and generated types", () => {
const publicTypes = readFileSync(new URL("../src/types.ts", import.meta.url), "utf8");
const generatedRpc = readFileSync(
new URL("../src/generated/rpc.ts", import.meta.url),
"utf8"
);
expect(publicTypes).toContain("Maximum accumulated active-execution time, in seconds.");
expect(publicTypes).toContain("subprocess waits, queued-agent waits, and sleeps");
expect(publicTypes).toContain("timeoutSeconds?: number;");
expect(generatedRpc).toContain("Maximum accumulated active-execution time in seconds.");
expect(generatedRpc).toContain("subprocess waits, queued-agent waits, and sleeps");
expect(generatedRpc).toContain("timeoutSeconds?: number;");
});
// A guessed ceiling does not make a run safer: it stops a healthy run partway
// with `factory_limit_reached`, after that run has already taken the user's
// approval and spent credits. Both documents are handed to the model verbatim
// by the `factories_manage` guide, so neither may read as an invitation to
// invent one.
it("documents limits as opt-in rather than inviting an invented ceiling", () => {
const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8");
const patterns = readFileSync(
new URL("../docs/factory-patterns.md", import.meta.url),
"utf8"
);
expect(guide).toContain(
"Set a ceiling only from real knowledge of what the factory costs, or because the user named one"
);
expect(guide).toContain("no basis for estimating a number");
// The opening `defineFactory` sample is the shape an author copies. Filling
// all four ceilings in there taught the numbers as much as the syntax.
const openingSample = guide.slice(0, guide.indexOf("## Declaring an argument shape"));
expect(openingSample).not.toContain("limits: {");
// The Scaling section used to answer "there is no built-in concurrency cap"
// with "so declare one before fanning out widely".
expect(patterns).not.toContain("declare one before fanning out widely");
expect(patterns).toContain("bound a wide fan-out with the factory's own counters");
});
it("documents factory invocation and list paging behavior accurately", () => {
const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8");
const publicApi = readFileSync(new URL("../src/factory.ts", import.meta.url), "utf8");
const listRunsPagingWording = "newest default page of this session's durable factory runs";
const resumeCodes = [
"not_found",
"non_resumable",
"already_active",
"factory_already_running",
"factory_limits_invalid",
"factory_session_disposed",
"factory_storage_unavailable",
"factory_storage_corrupt",
];
const normalizeJSDoc = (document: string) =>
document.replace(/\r?\n\s*\* ?/g, " ").replace(/\s+/g, " ");
const normalizedGuide = normalizeJSDoc(guide);
const normalizedPublicApi = normalizeJSDoc(publicApi);
for (const document of [guide, publicApi]) {
expect(document).not.toContain("reapproval_declined");
expect(document).not.toContain("no_approval_provider");
expect(document).not.toMatch(/declined fresh run[\s\S]*terminal `cancelled` envelope/i);
}
for (const document of [normalizedGuide, normalizedPublicApi]) {
expect(document).toContain(listRunsPagingWording);
}
expect(normalizedGuide).toContain(
"SDK-initiated `run` and `resume` do not request permission"
);
expect(normalizedGuide).toContain(
"`run_factory` tool requests permission before the durable row exists"
);
expect(normalizedGuide).toContain("declining it creates no run row");
expect(normalizedGuide).toContain("its maximum number of active top-level runs");
for (const code of resumeCodes) {
expect(guide).toContain(`\`${code}\``);
}
expect(guide).toContain(
"Options are exactly `label`, `schema`, `model`, `agent`, `reasoningEffort`, and `contextTier`"
);
expect(normalizedGuide).toContain(
"session returned by `joinSession`. It refuses calls that start or resume a factory run"
);
expect(normalizedPublicApi).toContain("SDK-initiated runs do not request permission");
expect(normalizedPublicApi).toContain("declining it creates no run row");
expect(normalizedPublicApi).toContain(
"while the session is at its active top-level run limit"
);
expect(normalizedPublicApi).toContain("SDK-initiated resumes do not request permission");
expect(normalizedPublicApi).toContain("with a documented resume code rejects with");
expect(normalizedPublicApi).toContain(
"session instance returned by `joinSession`. It refuses calls that start or resume a factory run"
);
});
it("carries a declared argsSchema through defineFactory into the registration payload", async () => {
const client = new CopilotClient();
await client.start();
onTestFinished(() => stopClient(client));
const argsSchema = {
type: "object",
required: ["repoPath"],
properties: {
repoPath: { type: "string" },
depth: { type: ["integer", "null"] },
mode: { enum: ["fast", "thorough"] },
},
} satisfies FactoryJsonSchema;
const meta = {
name: "declares-args",
description: "Declares the argument shape it expects",
phases: [],
argsSchema,
};
const factory = defineFactory({ meta, run: async () => ({ ok: true }) });
// The declaration is snapshotted and deep-frozen like the rest of the
// metadata, so it cannot be mutated after registration.
expect(factory.meta.argsSchema).toEqual(argsSchema);
expect(factory.meta.argsSchema).not.toBe(argsSchema);
expect(Object.isFrozen(factory.meta.argsSchema)).toBe(true);
expect(() => {
// @ts-expect-error handle.meta.argsSchema is deeply readonly.
factory.meta.argsSchema!.type = "array";
}).toThrow(TypeError);
const omitted = defineFactory({
meta: { name: "omits-args", description: "Declares nothing", phases: [] },
run: async () => ({ ok: true }),
});
expect(omitted.meta.argsSchema).toBeUndefined();
expect("argsSchema" in omitted.meta).toBe(false);
const sendRequest = vi
.spyOn(
(client as never as { connection: { sendRequest: Function } }).connection,
"sendRequest"
)
.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === "session.resume") {
return { sessionId: params.sessionId };
}
throw new Error(`Unexpected method: ${method}`);
});
await client.resumeSessionForExtension(
"session-args-schema",
{ onPermissionRequest: () => ({ kind: "approved" }) },
[factory, omitted]
);
const payload = sendRequest.mock.calls.find(
([method]) => method === "session.resume"
)![1] as { factories: Array<Record<string, unknown>> };
// The schema has to survive JSON serialization to reach the runtime, which
// validates `args` against it before a run row exists.
expect(JSON.parse(JSON.stringify(payload.factories))[0].argsSchema).toEqual(argsSchema);
expect(payload.factories[1]).not.toHaveProperty("argsSchema");
});
it("documents argsSchema consistently with the runtime's enforced subset", () => {
const publicTypes = readFileSync(new URL("../src/types.ts", import.meta.url), "utf8");
const publicApi = readFileSync(new URL("../src/factory.ts", import.meta.url), "utf8");
const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8");
const normalizeJSDoc = (document: string) =>
document.replace(/\r?\n\s*\* ?/g, " ").replace(/\s+/g, " ");
expect(publicTypes).toContain("argsSchema?: FactoryJsonSchema;");
// The `run_factory` tool tells the model exactly this. The two surfaces
// have to agree about what a declaration does and does not enforce.
for (const document of [normalizeJSDoc(publicTypes), guide]) {
expect(document).toContain("types, required properties, and enum");
expect(document).toMatch(
/`minLength`, `pattern`,? (?:and|or) `additionalProperties` are recorded/
);
}
expect(normalizeJSDoc(publicTypes)).toContain("before** the run starts");
// Enforcement is tool-path only: `toolRunFactoryValidateArgs` is called from
// the runtime's runFactoryTool, and never from `session.factory.run`. Both
// surfaces must keep saying so, or authors will assume their own SDK-initiated
// runs are checked.
expect(normalizeJSDoc(publicTypes)).toContain(
"`session.factory.run(...)` is not validated against the declaration"
);
expect(guide).toContain("Validation covers the model's `run_factory` path only");
expect(normalizeJSDoc(publicApi)).toContain(
"`null`, `boolean`, `integer`, `number`, `string`, `array`, or `object`"
);
expect(guide).toContain("no run row, permission prompt, or credit spend happens");
});
it("serializes only factory metadata in the extension resume payload", async () => {
const client = new CopilotClient();
await client.start();
onTestFinished(() => stopClient(client));
const run = vi.fn(async () => ({ ok: true }));
const factory = defineFactory({
meta: {
name: "registered",
description: "Registration test",
phases: [{ title: "Run" }],
limits: { maxTotalSubagents: 2 },
},
run,
});
const sendRequest = vi
.spyOn(
(client as never as { connection: { sendRequest: Function } }).connection,
"sendRequest"
)
.mockImplementation(async (method: string, params: Record<string, unknown>) => {
if (method === "session.resume") {
const sessions = (client as never as { sessions: Map<string, CopilotSession> })
.sessions;
expect(
sessions.get(params.sessionId as string)?.clientSessionApis.factory
).toBeDefined();
return { sessionId: params.sessionId };
}
throw new Error(`Unexpected method: ${method}`);
});
await client.resumeSessionForExtension(
"session-registration",
{ onPermissionRequest: () => ({ kind: "approved" }) },
[factory]
);
const payload = sendRequest.mock.calls.find(
([method]) => method === "session.resume"
)![1] as {
factories: unknown[];
};
expect(payload.factories).toEqual([factory.meta]);
expect(payload.factories[0]).not.toHaveProperty("run");
expect(JSON.stringify(payload.factories)).not.toContain("async");
});
it("passes factories only through the extension join path", async () => {
process.env.SESSION_ID = "session-extension";
const factory = defineFactory({
meta: {
name: "extension-only",
description: "Extension-only registration",
phases: [],
},
run: async () => ({ ok: true }),
});
const resumeSessionForExtension = vi
.spyOn(CopilotClient.prototype, "resumeSessionForExtension")
.mockResolvedValue({} as CopilotSession);
await joinSession({ factories: [factory] });
expect(resumeSessionForExtension).toHaveBeenCalledWith(
"session-extension",
expect.objectContaining({ suppressResumeEvent: true }),
[factory],
undefined
);
});
it("builds the factory context with the unrestricted joined session identity", async () => {
process.env.SESSION_ID = "session-context";
const sendRequest = vi.fn(async (method: string) => {
if (method === "session.factory.log") {
return {};
}
if (method === "session.tasks.list") {
return { tasks: [] };
}
throw new Error(`Unexpected method: ${method}`);
});
const joinedSession = new CopilotSession("session-context", { sendRequest } as never);
const contextSeen = Promise.withResolvers<{
runId: string;
args: unknown;
session: CopilotSession;
signal: AbortSignal;
}>();
const factory = defineFactory({
meta: {
name: "context",
description: "Context test",
phases: [],
},
run: async (context) => {
contextSeen.resolve(context);
context.phase("A");
context.log("hi");
const tasks = await context.session.rpc.tasks.list();
return { ok: true, taskCount: tasks.tasks.length };
},
});
vi.spyOn(CopilotClient.prototype, "resumeSessionForExtension").mockImplementation(
async (_sessionId, _config, factories) => {
joinedSession.registerFactories(factories);
return joinedSession;
}
);
const joinSessionResult = await joinSession({ factories: [factory] });
const executeResult = await joinSessionResult.clientSessionApis.factory!.execute({
sessionId: joinSessionResult.sessionId,
name: "context",
runId: "run-context",
executionToken: "execution-token",
args: { value: 42 },
});
const context = await contextSeen.promise;
expect(context.runId).toBe("run-context");
expect(context.args).toEqual({ value: 42 });
expect(context.session).toBe(joinSessionResult);
expect(context.session.rpc).toBe(joinSessionResult.rpc);
expect(context.signal).toBeInstanceOf(AbortSignal);
expect(executeResult).toEqual({ result: { ok: true, taskCount: 0 } });
expect(sendRequest).toHaveBeenCalledWith("session.tasks.list", {
sessionId: joinSessionResult.sessionId,
});
expect(sendRequest).toHaveBeenCalledWith("session.factory.log", {
sessionId: joinSessionResult.sessionId,
runId: "run-context",
executionToken: "execution-token",
lines: [
{ seq: 0, kind: "phase", text: "A" },
{ seq: 1, kind: "log", text: "hi" },
],
});
});
it("rejects nested factories without forwarding a runNested request", async () => {
const sendRequest = vi.fn(async () => {
throw new Error("Unexpected forward request");
});
const session = new CopilotSession("session-no-nesting", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "no-nesting",
description: "Nested factory rejection test",
phases: [],
},
run: async (context) => context.factory("nested", { value: 42 }),
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "no-nesting",
runId: "run-no-nesting",
executionToken: "execution-token",
args: {},
})
).rejects.toThrow("nested factories are not supported");
expect(sendRequest).not.toHaveBeenCalled();
});
it("keeps factory reads and cancellation available inside a factory body", async () => {
const sendRequest = vi.fn(async (method: string) => {
switch (method) {
case "session.factory.getRun":
return { runId: "other-run", status: "completed" };
case "session.factory.listRuns":
return { runs: [] };
case "session.factory.cancel":
return {};
default:
throw new Error(`Unexpected method: ${method}`);
}
});
const session = new CopilotSession("session-factory-reads", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "factory-reads",
description: "Read factory state from a factory body",
phases: [],
},
run: async ({ session: contextSession }) => {
const [run, runs] = await Promise.all([
contextSession.factory.getRun("other-run"),
contextSession.factory.listRuns(),
contextSession.factory.cancel("other-run"),
]);
return { runId: run.runId, runCount: runs.length };
},
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "factory-reads",
runId: "run-factory-reads",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({ result: { runId: "other-run", runCount: 0 } });
expect(sendRequest).toHaveBeenCalledWith("session.factory.getRun", {
sessionId: session.sessionId,
runId: "other-run",
});
expect(sendRequest).toHaveBeenCalledWith("session.factory.listRuns", {
sessionId: session.sessionId,
});
expect(sendRequest).toHaveBeenCalledWith("session.factory.cancel", {
sessionId: session.sessionId,
runId: "other-run",
});
});
it("allows factory.run after a factory body returns", async () => {
const sendRequest = vi.fn(async (method: string) => {
if (method === "session.factory.run") {
return { runId: "run-after-body", status: "completed", result: "started" };
}
throw new Error(`Unexpected method: ${method}`);
});
const session = new CopilotSession("session-after-body", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "returns",
description: "Return before a separate factory run",
phases: [],
},
run: async () => "finished",
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "returns",
runId: "run-returns",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({ result: "finished" });
await expect(session.factory.run("after-body")).resolves.toMatchObject({
status: "completed",
result: "started",
});
});
it("allows a factory-body timer to start a factory after the body settles", async () => {
const delayedRun = Promise.withResolvers<unknown>();
const sendRequest = vi.fn(async (method: string) => {
if (method === "session.factory.run") {
return { runId: "run-from-timer", status: "completed", result: "started" };
}
throw new Error(`Unexpected method: ${method}`);
});
const session = new CopilotSession("session-timer", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "timer",
description: "Start a factory from an unawaited timer",
phases: [],
},
run: async () => {
setTimeout(() => {
void session.factory
.run("from-timer")
.then(delayedRun.resolve, delayedRun.reject);
}, 0);
return "finished";
},
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "timer",
runId: "run-timer",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({ result: "finished" });
await expect(delayedRun.promise).resolves.toMatchObject({
status: "completed",
result: "started",
});
});
it("flushes progress incrementally while a factory body is awaiting", async () => {
const sendRequest = vi.fn(async () => ({}));
const session = new CopilotSession("session-live-progress", { sendRequest } as never);
const body = Promise.withResolvers<void>();
const factory = defineFactory({
meta: {
name: "live-progress",
description: "Incremental progress test",
phases: [],
},
run: async ({ log }) => {
log("before await");
await body.promise;
return "done";
},
});
session.registerFactories([factory]);
const execution = session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "live-progress",
runId: "run-live-progress",
executionToken: "execution-token",
args: {},
});
await vi.waitFor(() => {
expect(sendRequest).toHaveBeenCalledWith("session.factory.log", {
sessionId: session.sessionId,
runId: "run-live-progress",
executionToken: "execution-token",
lines: [{ seq: 0, kind: "log", text: "before await" }],
});
});
body.resolve();
await expect(execution).resolves.toEqual({ result: "done" });
});
it("calls factory.agent with the current run id and returns its text", async () => {
const sendRequest = vi.fn(async (method: string) => {
if (method === "session.factory.agent") {
return { result: "pong" };
}
throw new Error(`Unexpected method: ${method}`);
});
const session = new CopilotSession("session-agent", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "agent",
description: "Agent context test",
phases: [],
},
run: async ({ agent }) =>
agent("Reply with pong", {
label: "Pong helper",
model: "gpt-test",
schema: { type: "string" },
effort: "high",
} as FactoryAgentOptions),
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "agent",
runId: "run-agent",
executionToken: "execution-token",
args: {},
})
).resolves.toEqual({ result: "pong" });
expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", {
sessionId: session.sessionId,
factoryRunId: "run-agent",
executionToken: "execution-token",
prompt: "Reply with pong",
opts: {
label: "Pong helper",
model: "gpt-test",
schema: { type: "string" },
},
});
});
it("forwards every declared factory.agent option", async () => {
const sendRequest = vi.fn(async (method: string) => {
if (method === "session.factory.agent") {
return { result: "pong" };
}
throw new Error(`Unexpected method: ${method}`);
});
const session = new CopilotSession("session-agent-options", { sendRequest } as never);
const factory = defineFactory({
meta: {
name: "agent-options",
description: "Agent option forwarding test",
phases: [],
},
run: async ({ agent }) =>
agent("Reply with pong", {
label: "Pong helper",
model: "gpt-test",
schema: { type: "string" },
agent: "reviewer",
reasoningEffort: "high",
contextTier: "long_context",
}),
});
session.registerFactories([factory]);
await expect(
session.clientSessionApis.factory!.execute({
sessionId: session.sessionId,
name: "agent-options",
runId: "run-agent-options",