-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathpython.ts
More file actions
2703 lines (2456 loc) · 107 KB
/
python.ts
File metadata and controls
2703 lines (2456 loc) · 107 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.
*--------------------------------------------------------------------------------------------*/
/**
* Python code generator for session-events and RPC types.
*/
import fs from "fs/promises";
import path from "path";
import type { JSONSchema7 } from "json-schema";
import { fileURLToPath } from "url";
import {
cloneSchemaForCodegen,
filterNodeByVisibility,
fixNullableRequiredRefsInApiSchema,
getApiSchemaPath,
getRpcSchemaTypeName,
getSessionEventsSchemaPath,
isObjectSchema,
isVoidSchema,
getNullableInner,
isRpcMethod,
isNodeFullyExperimental,
isNodeFullyDeprecated,
isSchemaDeprecated,
isSchemaExperimental,
postProcessSchema,
stripBooleanLiterals,
writeGeneratedFile,
collectDefinitionCollections,
collectReachableDefinitionNames,
findSharedSchemaDefinitions,
hasSchemaPayload,
parseExternalSchemaRef,
refTypeName,
resolveObjectSchema,
resolveSchema,
rewriteSharedDefinitionReferences,
withSharedDefinitions,
getSessionEventVariantSchemas,
getSharedSessionEventEnvelopeProperties,
type ApiSchema,
type DefinitionCollections,
type RpcMethod,
type SessionEventEnvelopeProperty,
} from "./utils.js";
// ── Utilities ───────────────────────────────────────────────────────────────
const EXTERNAL_SCHEMA_PY_MODULE: Record<string, string> = {
"session-events.schema.json": ".session_events",
};
type PyExperimentalSubject = "type" | "enum" | "event";
function pyExperimentalComment(subject: PyExperimentalSubject, indent = ""): string {
return `${indent}# Experimental: this ${subject} is part of an experimental API and may change or be removed.`;
}
function rewriteExternalRefsForPython(schema: JSONSchema7 & { definitions?: Record<string, JSONSchema7> }): {
placeholderNames: Map<string, string>;
imports: Map<string, Set<string>>;
} {
const placeholderNames = new Map<string, string>();
const imports = new Map<string, Set<string>>();
const placeholderFor = (typeName: string): string => `__ExternalRef_${typeName}`;
const visit = (value: unknown): void => {
if (Array.isArray(value)) {
for (const item of value) visit(item);
return;
}
if (!value || typeof value !== "object") return;
const node = value as Record<string, unknown>;
if (typeof node.$ref === "string" && !node.$ref.startsWith("#")) {
const externalRef = parseExternalSchemaRef(node.$ref);
const module = externalRef ? EXTERNAL_SCHEMA_PY_MODULE[externalRef.schemaFile] : undefined;
if (externalRef && module) {
const placeholder = placeholderFor(externalRef.definitionName);
placeholderNames.set(placeholder, externalRef.definitionName);
let bucket = imports.get(module);
if (!bucket) {
bucket = new Set<string>();
imports.set(module, bucket);
}
bucket.add(externalRef.definitionName);
node.$ref = `#/definitions/${placeholder}`;
}
}
for (const child of Object.values(node)) visit(child);
};
visit(schema);
if (placeholderNames.size > 0) {
if (!schema.definitions) schema.definitions = {};
for (const placeholder of placeholderNames.keys()) {
if (!schema.definitions[placeholder]) {
const markerProperty = `__externalRefMarker_${placeholder}`;
schema.definitions[placeholder] = {
type: "object",
additionalProperties: false,
title: placeholder,
properties: {
[markerProperty]: { type: "string" },
},
required: [markerProperty],
};
}
}
}
return { placeholderNames, imports };
}
function placeholderToQuicktypeIdentifier(placeholder: string): string {
return placeholder
.replace(/^_+/, "")
.split("_")
.map((segment) => (segment ? segment[0].toUpperCase() + segment.slice(1) : ""))
.join("");
}
function postProcessExternalRefsForPython(code: string, placeholderToReal: Map<string, string>): string {
for (const [placeholder, realName] of placeholderToReal) {
const quicktypeName = placeholderToQuicktypeIdentifier(placeholder);
code = code.replace(
new RegExp(
`(?:^|\\n)@dataclass\\r?\\nclass ${quicktypeName}\\b[\\s\\S]*?(?=\\n@dataclass\\b|\\nclass\\s+\\w|\\ndef\\s+\\w|$)`,
"g"
),
"\n"
);
code = code.replace(
new RegExp(
`(?:^|\\n)class ${quicktypeName}\\w*\\(Enum\\):[\\s\\S]*?(?=\\nclass\\s+\\w|\\n@dataclass\\b|\\ndef\\s+\\w|$)`,
"g"
),
"\n"
);
code = code.replace(new RegExp(`\\b${quicktypeName}\\b`, "g"), realName);
}
return code.replace(/\n{3,}/g, "\n\n");
}
function collectExternalUnionAliasesForPython(
definitions: Record<string, JSONSchema7>,
placeholderToReal: Map<string, string>
): Map<string, string[]> {
const aliases = new Map<string, string[]>();
for (const [definitionName, definition] of Object.entries(definitions)) {
const variants = definition.anyOf ?? definition.oneOf;
if (!Array.isArray(variants)) continue;
const realNames: string[] = [];
let allExternal = true;
for (const variant of variants) {
if (!variant || typeof variant !== "object") {
allExternal = false;
break;
}
const ref = (variant as JSONSchema7).$ref;
if (!ref?.startsWith("#/definitions/")) {
allExternal = false;
break;
}
const placeholder = ref.slice("#/definitions/".length);
const realName = placeholderToReal.get(placeholder);
if (!realName) {
allExternal = false;
break;
}
realNames.push(realName);
}
if (allExternal && realNames.length > 0) {
aliases.set(definitionName, realNames);
}
}
return aliases;
}
function postProcessExternalUnionAliasesForPython(code: string, aliases: Map<string, string[]>): string {
for (const [aliasName, realNames] of aliases) {
const aliasLine = `${aliasName} = ${realNames.join(" | ")}`;
const classPattern = new RegExp(
`(?:^|\\n)@dataclass\\r?\\nclass ${aliasName}\\b[\\s\\S]*?(?=\\n@dataclass\\b|\\nclass\\s+\\w|\\ndef\\s+\\w|$)`,
"g"
);
if (classPattern.test(code)) {
code = code.replace(classPattern, `\n${aliasLine}\n`);
} else if (!new RegExp(`^${aliasName}\\s*=`, "m").test(code)) {
code = `${aliasLine}\n\n${code}`;
}
code = code.replace(
new RegExp(`${aliasName}\\.from_dict`, "g"),
`(lambda x: from_union([${realNames.map((name) => `${name}.from_dict`).join(", ")}], x))`
);
code = code.replace(
new RegExp(`to_class\\(${aliasName},\\s*([^)]+)\\)`, "g"),
`from_union([${realNames.map((name) => `lambda x: to_class(${name}, x)`).join(", ")}], $1)`
);
}
return code.replace(/\n{3,}/g, "\n\n");
}
function pushPyExperimentalComment(lines: string[], subject: PyExperimentalSubject, indent = ""): void {
lines.push(pyExperimentalComment(subject, indent));
}
function pushPyExperimentalApiGroupComment(lines: string[]): void {
lines.push("# Experimental: this API group is experimental and may change or be removed.");
}
/**
* Modernize quicktype's Python 3.7 output to Python 3.11+ syntax:
* - Optional[T] → T | None
* - List[T] → list[T]
* - Dict[K, V] → dict[K, V]
* - Type[T] → type[T]
* - Callable from collections.abc instead of typing
* - Clean up unused typing imports
*/
function replaceBalancedBrackets(code: string, prefix: string, replacer: (inner: string) => string): string {
let result = "";
let i = 0;
while (i < code.length) {
const idx = code.indexOf(prefix + "[", i);
if (idx === -1) {
result += code.slice(i);
break;
}
result += code.slice(i, idx);
const start = idx + prefix.length + 1; // after '['
let depth = 1;
let j = start;
while (j < code.length && depth > 0) {
if (code[j] === "[") depth++;
else if (code[j] === "]") depth--;
j++;
}
const inner = code.slice(start, j - 1);
result += replacer(inner);
i = j;
}
return result;
}
/** Split a string by commas, but only at the top bracket depth (ignores commas inside [...]) */
function splitTopLevelCommas(s: string): string[] {
const parts: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "[") depth++;
else if (s[i] === "]") depth--;
else if (s[i] === "," && depth === 0) {
parts.push(s.slice(start, i));
start = i + 1;
}
}
parts.push(s.slice(start));
return parts;
}
function pyDocstringLiteral(text: string): string {
const normalized = text
.split(/\r?\n/)
.map((line) => line.replace(/\s+$/g, ""))
.join("\n");
return JSON.stringify(normalized);
}
function rpcResultDescription(method: RpcMethod, resultSchema: JSONSchema7 | undefined): string | undefined {
if (isVoidSchema(resultSchema)) return undefined;
return method.result?.description ?? resultSchema?.description;
}
function rpcParamsDescription(method: RpcMethod, effectiveParams: JSONSchema7 | undefined): string | undefined {
return method.params?.description ?? effectiveParams?.description;
}
function pushPyRpcMethodDocstring(
lines: string[],
indent: string,
method: RpcMethod,
options: {
paramsName?: string;
paramsDescription?: string;
resultDescription?: string;
deprecated?: boolean;
experimental?: boolean;
internal?: boolean;
} = {}
): void {
const sections: string[] = [method.description ?? `Calls ${method.rpcMethod}.`];
if (options.paramsName && options.paramsDescription) {
sections.push(`Args:\n ${options.paramsName}: ${options.paramsDescription}`);
}
if (options.resultDescription) {
sections.push(`Returns:\n ${options.resultDescription}`);
}
if (options.deprecated) {
sections.push(".. deprecated:: This API is deprecated and will be removed in a future version.");
}
if (options.experimental) {
sections.push(".. warning:: This API is experimental and may change or be removed in future versions.");
}
if (options.internal) {
sections.push(":meta private:\n\nInternal SDK API; not part of the public surface.");
}
lines.push(`${indent}${pyDocstringLiteral(sections.join("\n\n"))}`);
}
function modernizePython(code: string): string {
// Replace Optional[X] with X | None (handles arbitrarily nested brackets)
code = replaceBalancedBrackets(code, "Optional", (inner) => `${inner} | None`);
// Replace Union[X, Y] with X | Y (split only at top-level commas, not inside brackets)
// Run iteratively to handle nested Union inside Dict/List
let prev = "";
while (prev !== code) {
prev = code;
code = replaceBalancedBrackets(code, "Union", (inner) => {
return splitTopLevelCommas(inner).map((s: string) => s.trim()).join(" | ");
});
}
// Replace List[X] with list[X]
code = code.replace(/\bList\[/g, "list[");
// Replace Dict[K, V] with dict[K, V]
code = code.replace(/\bDict\[/g, "dict[");
// Replace Type[T] with type[T]
code = code.replace(/\bType\[/g, "type[");
// Move Callable from typing to collections.abc
code = code.replace(
/from typing import (.*), Callable$/m,
"from typing import $1\nfrom collections.abc import Callable"
);
code = code.replace(
/from typing import Callable, (.*)$/m,
"from typing import $1\nfrom collections.abc import Callable"
);
// Remove now-unused imports from typing (Optional, List, Dict, Type)
code = code.replace(/from typing import (.+)$/m, (_match, imports: string) => {
const items = imports.split(",").map((s: string) => s.trim());
const remove = new Set(["Optional", "List", "Dict", "Type", "Union"]);
const kept = items.filter((i: string) => !remove.has(i));
return `from typing import ${kept.join(", ")}`;
});
return code;
}
/**
* Collapse lambdas that only forward their single argument into another callable.
* This keeps the generated Python readable and avoids CodeQL "unnecessary lambda" findings.
*/
function unwrapRedundantPythonLambdas(code: string): string {
return code.replace(
/lambda\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*((?:[A-Za-z_][A-Za-z0-9_]*)(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\(\1\)/g,
"$2"
);
}
function collapsePlaceholderPythonDataclasses(code: string, knownDefinitionNames?: Set<string>): string {
const classBlockRe = /(@dataclass\r?\nclass\s+(\w+):[\s\S]*?)(?=^@dataclass|^class\s+\w+|^def\s+\w+|\Z)/gm;
const matches = [...code.matchAll(classBlockRe)].map((match) => ({
fullBlock: match[1],
name: match[2],
normalizedBody: normalizePythonDataclassBlock(match[1], match[2]),
}));
const groups = new Map<string, typeof matches>();
for (const match of matches) {
const group = groups.get(match.normalizedBody) ?? [];
group.push(match);
groups.set(match.normalizedBody, group);
}
for (const group of groups.values()) {
if (group.length < 2) continue;
const canonical = chooseCanonicalPlaceholderDuplicate(group.map(({ name }) => name), knownDefinitionNames);
if (!canonical) continue;
for (const duplicate of group) {
if (duplicate.name === canonical) continue;
// Only collapse types that quicktype invented (Class suffix or not
// in the schema's named definitions). Preserve intentionally-named types.
if (!isPlaceholderTypeName(duplicate.name) && knownDefinitionNames?.has(duplicate.name.toLowerCase())) continue;
code = code.replace(duplicate.fullBlock, "");
code = code.replace(new RegExp(`\\b${duplicate.name}\\b`, "g"), canonical);
}
}
return code.replace(/\n{3,}/g, "\n\n");
}
/**
* Reorder Python class/enum definitions so forward references are resolved.
* Quicktype may emit classes in an order where a class references another
* that hasn't been defined yet, causing NameError at import time.
* This performs a topological sort of type definitions while preserving
* the relative position of non-class blocks (functions, standalone code).
*/
function reorderPythonForwardRefs(code: string): string {
// Split code into top-level blocks. Each block starts at an unindented
// line that begins a class, decorated class, enum, or function definition.
const lines = code.split("\n");
interface Block {
name: string;
code: string;
isType: boolean; // true for class/enum definitions
}
const blocks: Block[] = [];
let currentLines: string[] = [];
let currentName: string | null = null;
let isType = false;
function flushBlock() {
if (currentLines.length === 0) return;
const blockCode = currentLines.join("\n");
blocks.push({
name: currentName ?? `__anon_${blocks.length}`,
code: blockCode,
isType,
});
currentLines = [];
currentName = null;
isType = false;
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isTopLevel = line.length > 0 && line[0] !== " " && line[0] !== "\t";
if (isTopLevel) {
const classMatch = line.match(/^class\s+(\w+)/);
const defMatch = line.match(/^def\s+(\w+)/);
const decoratorMatch = line === "@dataclass";
const commentMatch = line.startsWith("# ");
if (classMatch) {
// If previous block was just a decorator waiting for a class, merge
if (currentLines.length > 0 && currentName === null && isType) {
// This is the class line following @dataclass
currentName = classMatch[1];
currentLines.push(line);
continue;
}
flushBlock();
currentLines = [line];
currentName = classMatch[1];
isType = true;
} else if (decoratorMatch) {
flushBlock();
currentLines = [line];
isType = true;
} else if (defMatch) {
flushBlock();
currentLines = [line];
currentName = defMatch[1];
isType = false;
} else if (commentMatch && currentLines.length === 0) {
// Standalone comment — attach to next block
currentLines = [line];
} else {
currentLines.push(line);
}
} else {
currentLines.push(line);
}
}
flushBlock();
if (blocks.length === 0) return code;
// Collect all type names (classes and enums)
const typeNames = new Set(blocks.filter((b) => b.isType).map((b) => b.name));
if (typeNames.size === 0) return code;
// Build dependency graph: for each type block, find references to other type names
const deps = new Map<string, Set<string>>();
for (const block of blocks) {
if (!block.isType) continue;
const blockDeps = new Set<string>();
for (const tn of typeNames) {
if (tn === block.name) continue;
if (new RegExp(`\\b${tn}\\b`).test(block.code)) {
blockDeps.add(tn);
}
}
deps.set(block.name, blockDeps);
}
// Kahn's algorithm for topological sort
const inDegree = new Map<string, number>();
for (const tn of typeNames) inDegree.set(tn, deps.get(tn)?.size ?? 0);
const dependents = new Map<string, string[]>();
for (const tn of typeNames) dependents.set(tn, []);
for (const [name, d] of deps) {
for (const dep of d) {
dependents.get(dep)!.push(name);
}
}
const queue: string[] = [];
for (const [tn, deg] of inDegree) {
if (deg === 0) queue.push(tn);
}
const sorted: string[] = [];
while (queue.length > 0) {
const node = queue.shift()!;
sorted.push(node);
for (const dep of dependents.get(node) ?? []) {
const newDeg = inDegree.get(dep)! - 1;
inDegree.set(dep, newDeg);
if (newDeg === 0) queue.push(dep);
}
}
// If there are cycles, keep remaining nodes in original order
for (const block of blocks) {
if (block.isType && !sorted.includes(block.name)) {
sorted.push(block.name);
}
}
// Rebuild: place type blocks in sorted order at the positions
// where type blocks originally appeared
const typeBlockMap = new Map(blocks.filter((b) => b.isType).map((b) => [b.name, b]));
let sortIdx = 0;
const result: string[] = [];
for (const block of blocks) {
if (block.isType) {
result.push(typeBlockMap.get(sorted[sortIdx])!.code);
sortIdx++;
} else {
result.push(block.code);
}
}
return result.join("\n");
}
function normalizePythonDataclassBlock(block: string, name: string): string {
return block
.replace(/^@dataclass\r?\nclass\s+\w+:/, "@dataclass\nclass:")
.replace(new RegExp(`\\b${name}\\b`, "g"), "SelfType")
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.join("\n");
}
function chooseCanonicalPlaceholderDuplicate(names: string[], knownDefinitionNames?: Set<string>): string | undefined {
// Prefer the name that matches a schema definition — it's intentionally named.
if (knownDefinitionNames) {
const definedName = names.find((name) => knownDefinitionNames.has(name.toLowerCase()));
if (definedName) return definedName;
}
// Fallback for Class-suffix placeholders: pick the non-placeholder name.
const specificNames = names.filter((name) => !isPlaceholderTypeName(name));
if (specificNames.length === 0) return undefined;
return specificNames[0];
}
function isPlaceholderTypeName(name: string): boolean {
return name.endsWith("Class") || name.endsWith("Enum");
}
function toSnakeCase(s: string): string {
return s
.replace(/([a-z])([A-Z])/g, "$1_$2")
.replace(/[._]/g, "_")
.toLowerCase();
}
function toPascalCase(s: string): string {
return s
.split(/[._]/)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join("");
}
function collectRpcMethods(node: Record<string, unknown>): RpcMethod[] {
const results: RpcMethod[] = [];
for (const value of Object.values(node)) {
if (isRpcMethod(value)) {
results.push(value);
} else if (typeof value === "object" && value !== null) {
results.push(...collectRpcMethods(value as Record<string, unknown>));
}
}
return results;
}
let rpcDefinitions: DefinitionCollections = { definitions: {}, $defs: {} };
function withRootTitle(schema: JSONSchema7, title: string): JSONSchema7 {
return { ...schema, title };
}
function pythonRequestFallbackName(method: RpcMethod): string {
return toPascalCase(method.rpcMethod) + "Request";
}
function schemaSourceForNamedDefinition(
schema: JSONSchema7 | null | undefined,
resolvedSchema: JSONSchema7 | undefined
): JSONSchema7 {
if (schema?.$ref && resolvedSchema) {
return resolvedSchema;
}
// When the schema is an anyOf/oneOf wrapper (e.g., Zod optional params producing
// `anyOf: [{ not: {} }, { $ref }]`), use the resolved object schema to avoid
// generating self-referential type aliases that crash quicktype.
if ((schema?.anyOf || schema?.oneOf) && resolvedSchema?.properties) {
return resolvedSchema;
}
return schema ?? resolvedSchema ?? { type: "object" };
}
function isNamedPyObjectSchema(schema: JSONSchema7 | undefined): schema is JSONSchema7 {
return !!schema && schema.type === "object" && (schema.properties !== undefined || schema.additionalProperties === false);
}
function getMethodResultSchema(method: RpcMethod): JSONSchema7 | undefined {
return resolveSchema(method.result, rpcDefinitions) ?? method.result ?? undefined;
}
function isPythonObjectResultSchema(schema: JSONSchema7 | undefined): boolean {
if (!schema) return false;
if (isObjectSchema(schema)) return true;
const variants = schema.anyOf ?? schema.oneOf;
if (!Array.isArray(variants)) return false;
const nonNullVariants = variants
.filter((variant): variant is JSONSchema7 => typeof variant === "object" && variant !== null)
.map((variant) => resolveObjectSchema(variant, rpcDefinitions) ?? resolveSchema(variant, rpcDefinitions) ?? variant)
.filter(
(variant) =>
variant.type !== "null" &&
!(
typeof variant.not === "object" &&
variant.not !== null &&
Object.keys(variant.not).length === 0
)
);
if (nonNullVariants.length === 1) {
return isPythonObjectResultSchema(nonNullVariants[0]);
}
return nonNullVariants.length > 1 && findPyDiscriminator(nonNullVariants) !== null;
}
function getMethodParamsSchema(method: RpcMethod): JSONSchema7 | undefined {
return (
resolveObjectSchema(method.params, rpcDefinitions) ??
resolveSchema(method.params, rpcDefinitions) ??
method.params ??
undefined
);
}
function pythonResultTypeName(method: RpcMethod, schemaOverride?: JSONSchema7): string {
const schema = schemaOverride ?? getMethodResultSchema(method);
// If schema is a $ref, derive the type name from the ref path
if (schema?.$ref) {
const refName = schema.$ref.split("/").pop();
if (refName) return toPascalCase(refName);
}
return getRpcSchemaTypeName(schema, toPascalCase(method.rpcMethod) + "Result");
}
/** Detect the Zod optional params pattern: `anyOf: [{ not: {} }, { $ref }]` */
function isParamsOptional(method: RpcMethod): boolean {
const schema = method.params;
if (!schema?.anyOf) return false;
return schema.anyOf.some(
(item) =>
typeof item === "object" &&
(item as JSONSchema7).not !== undefined &&
typeof (item as JSONSchema7).not === "object" &&
Object.keys((item as JSONSchema7).not as object).length === 0
);
}
function pythonParamsTypeName(method: RpcMethod): string {
const fallback = pythonRequestFallbackName(method);
if (method.rpcMethod.startsWith("session.") && method.params?.$ref) {
return fallback;
}
const schema = getMethodParamsSchema(method);
if (schema?.$ref) return toPascalCase(refTypeName(schema.$ref, rpcDefinitions));
return getRpcSchemaTypeName(schema, fallback);
}
// ── Session Events ──────────────────────────────────────────────────────────
// ── Session Events (custom codegen — dedicated per-event payload types) ─────
interface PyEventVariant {
typeName: string;
dataClassName: string;
dataSchema: JSONSchema7;
dataDescription?: string;
eventExperimental: boolean;
dataExperimental: boolean;
}
interface PyEventEnvelopeProperty extends SessionEventEnvelopeProperty {
jsonName: string;
fieldName: string;
hasDefault: boolean;
resolved: PyResolvedType;
}
interface PyResolvedType {
annotation: string;
fromExpr: (expr: string) => string;
toExpr: (expr: string) => string;
}
interface PyCodegenCtx {
classes: string[];
aliases: string[];
aliasesByName: Set<string>;
enums: string[];
enumsByName: Map<string, string>;
generatedNames: Set<string>;
usesTimedelta: boolean;
usesIntegerTimedelta: boolean;
definitions: DefinitionCollections;
}
function toEnumMemberName(value: string): string {
const cleaned = value
.replace(/([a-z])([A-Z])/g, "$1_$2")
.replace(/[^A-Za-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "")
.toUpperCase();
if (!cleaned) {
return "VALUE";
}
return /^[0-9]/.test(cleaned) ? `VALUE_${cleaned}` : cleaned;
}
function wrapParser(resolved: PyResolvedType, arg = "x"): string {
return `lambda ${arg}: ${resolved.fromExpr(arg)}`;
}
function wrapSerializer(resolved: PyResolvedType, arg = "x"): string {
return `lambda ${arg}: ${resolved.toExpr(arg)}`;
}
const PY_SESSION_EVENT_TYPE_RENAMES: Record<string, string> = {
AssistantMessageDataToolRequestsItem: "AssistantMessageToolRequest",
AssistantMessageDataToolRequestsItemType: "AssistantMessageToolRequestType",
AssistantUsageDataCopilotUsage: "AssistantUsageCopilotUsage",
AssistantUsageDataCopilotUsageTokenDetailsItem: "AssistantUsageCopilotUsageTokenDetail",
AssistantUsageDataQuotaSnapshotsValue: "AssistantUsageQuotaSnapshot",
CapabilitiesChangedDataUi: "CapabilitiesChangedUI",
CommandsChangedDataCommandsItem: "CommandsChangedCommand",
ElicitationCompletedDataAction: "ElicitationCompletedAction",
ElicitationRequestedDataMode: "ElicitationRequestedMode",
ElicitationRequestedDataRequestedSchema: "ElicitationRequestedSchema",
McpOauthRequiredDataStaticClientConfig: "MCPOauthRequiredStaticClientConfig",
PermissionCompletedDataResultKind: "PermissionCompletedKind",
PermissionRequestedDataPermissionRequest: "PermissionRequest",
PermissionRequestedDataPermissionRequestAction: "PermissionRequestMemoryAction",
PermissionRequestedDataPermissionRequestCommandsItem: "PermissionRequestShellCommand",
PermissionRequestedDataPermissionRequestDirection: "PermissionRequestMemoryDirection",
PermissionRequestedDataPermissionRequestPossibleUrlsItem: "PermissionRequestShellPossibleURL",
SessionCompactionCompleteDataCompactionTokensUsed: "CompactionCompleteCompactionTokensUsed",
SessionCustomAgentsUpdatedDataAgentsItem: "CustomAgentsUpdatedAgent",
SessionExtensionsLoadedDataExtensionsItem: "ExtensionsLoadedExtension",
SessionExtensionsLoadedDataExtensionsItemSource: "ExtensionsLoadedExtensionSource",
SessionExtensionsLoadedDataExtensionsItemStatus: "ExtensionsLoadedExtensionStatus",
SessionHandoffDataRepository: "HandoffRepository",
SessionHandoffDataSourceType: "HandoffSourceType",
SessionMcpServersLoadedDataServersItem: "MCPServersLoadedServer",
SessionMcpServersLoadedDataServersItemStatus: "MCPServerStatus",
SessionShutdownDataCodeChanges: "ShutdownCodeChanges",
SessionShutdownDataModelMetricsValue: "ShutdownModelMetric",
SessionShutdownDataModelMetricsValueRequests: "ShutdownModelMetricRequests",
SessionShutdownDataModelMetricsValueUsage: "ShutdownModelMetricUsage",
SessionShutdownDataShutdownType: "ShutdownType",
SessionSkillsLoadedDataSkillsItem: "SkillsLoadedSkill",
UserMessageDataAgentMode: "UserMessageAgentMode",
UserMessageDataAttachmentsItem: "UserMessageAttachment",
UserMessageDataAttachmentsItemLineRange: "UserMessageAttachmentFileLineRange",
UserMessageDataAttachmentsItemReferenceType: "UserMessageAttachmentGithubReferenceType",
UserMessageDataAttachmentsItemSelection: "UserMessageAttachmentSelectionDetails",
UserMessageDataAttachmentsItemSelectionEnd: "UserMessageAttachmentSelectionDetailsEnd",
UserMessageDataAttachmentsItemSelectionStart: "UserMessageAttachmentSelectionDetailsStart",
UserMessageDataAttachmentsItemType: "UserMessageAttachmentType",
};
function postProcessPythonSessionEventCode(code: string): string {
for (const [from, to] of Object.entries(PY_SESSION_EVENT_TYPE_RENAMES).sort(
([left], [right]) => right.length - left.length
)) {
code = code.replace(new RegExp(`\\b${from}\\b`, "g"), to);
}
return unwrapRedundantPythonLambdas(code);
}
function pyPrimitiveResolvedType(annotation: string, fromFn: string, toFn = fromFn): PyResolvedType {
return {
annotation,
fromExpr: (expr) => `${fromFn}(${expr})`,
toExpr: (expr) => `${toFn}(${expr})`,
};
}
function pyOptionalResolvedType(inner: PyResolvedType): PyResolvedType {
return {
annotation: `${inner.annotation} | None`,
fromExpr: (expr) => `from_union([from_none, ${wrapParser(inner)}], ${expr})`,
toExpr: (expr) => `from_union([from_none, ${wrapSerializer(inner)}], ${expr})`,
};
}
function pyAnyResolvedType(): PyResolvedType {
return {
annotation: "Any",
fromExpr: (expr) => expr,
toExpr: (expr) => expr,
};
}
function pyDurationResolvedType(ctx: PyCodegenCtx, isInteger: boolean): PyResolvedType {
ctx.usesTimedelta = true;
if (isInteger) {
ctx.usesIntegerTimedelta = true;
}
return {
annotation: "timedelta",
fromExpr: (expr) => `from_timedelta(${expr})`,
toExpr: (expr) => (isInteger ? `to_timedelta_int(${expr})` : `to_timedelta(${expr})`),
};
}
function isPyBase64StringSchema(schema: JSONSchema7): boolean {
return schema.format === "byte" || (schema as Record<string, unknown>).contentEncoding === "base64";
}
function extractPyEventVariants(schema: JSONSchema7): PyEventVariant[] {
const definitionCollections = collectDefinitionCollections(schema as Record<string, unknown>);
return getSessionEventVariantSchemas(schema, definitionCollections)
.map((variant) => {
const typeSchema = variant.properties!.type as JSONSchema7;
const typeName = typeSchema?.const as string;
if (!typeName) {
throw new Error("Event variant must define type.const");
}
const dataSchema =
resolveObjectSchema(variant.properties!.data as JSONSchema7, definitionCollections) ??
resolveSchema(variant.properties!.data as JSONSchema7, definitionCollections) ??
((variant.properties!.data as JSONSchema7) || {});
return {
typeName,
dataClassName: `${toPascalCase(typeName)}Data`,
dataSchema,
dataDescription: dataSchema.description,
eventExperimental: isSchemaExperimental(variant),
dataExperimental: isSchemaExperimental(dataSchema),
};
});
}
function getPySharedEventEnvelopeProperties(schema: JSONSchema7, ctx: PyCodegenCtx): PyEventEnvelopeProperty[] {
return getSharedSessionEventEnvelopeProperties(schema, ctx.definitions)
.map((property) => {
const { name, schema, required } = property;
const resolved = resolvePyPropertyType(schema, "SessionEvent", name, required, ctx);
return {
...property,
jsonName: name,
fieldName: toSnakeCase(name),
required,
hasDefault: !required || resolved.annotation.includes(" | None"),
resolved,
};
});
}
function findPyDiscriminator(
variants: JSONSchema7[]
): { property: string; mapping: Map<string, JSONSchema7> } | null {
if (variants.length === 0) {
return null;
}
const firstVariant = variants[0];
if (!firstVariant.properties) {
return null;
}
for (const [propName, propSchema] of Object.entries(firstVariant.properties)) {
if (typeof propSchema !== "object") {
continue;
}
if ((propSchema as JSONSchema7).const === undefined) {
continue;
}
const mapping = new Map<string, JSONSchema7>();
let valid = true;
for (const variant of variants) {
if (!variant.properties) {
valid = false;
break;
}
const variantProp = variant.properties[propName];
if (typeof variantProp !== "object" || (variantProp as JSONSchema7).const === undefined) {
valid = false;
break;
}
mapping.set(String((variantProp as JSONSchema7).const), variant);
}
if (valid && mapping.size === variants.length) {
return { property: propName, mapping };
}
}
return null;
}
function isPyNullLikeSchema(schema: JSONSchema7): boolean {
return schema.type === "null" ||
(typeof schema.not === "object" && schema.not !== null && Object.keys(schema.not).length === 0);
}
function getPyNamedSchemaType(
schema: JSONSchema7,
ctx: PyCodegenCtx
): { typeName: string; resolved: PyResolvedType } | undefined {
const resolved = resolveSchema(schema, ctx.definitions) ?? schema;
const typeName = schema.$ref
? toPascalCase(refTypeName(schema.$ref, ctx.definitions))
: typeof resolved.title === "string"
? resolved.title
: undefined;
if (!typeName) {
return undefined;
}
if (resolved.enum && Array.isArray(resolved.enum) && resolved.enum.every((value) => typeof value === "string")) {
const enumType = getOrCreatePyEnum(
typeName,
resolved.enum as string[],
ctx,
resolved.description,
isSchemaDeprecated(resolved),
isSchemaExperimental(resolved)
);
return {
typeName: enumType,
resolved: {
annotation: enumType,
fromExpr: (expr) => `parse_enum(${enumType}, ${expr})`,
toExpr: (expr) => `to_enum(${enumType}, ${expr})`,
},
};
}
const resolvedObject = resolveObjectSchema(schema, ctx.definitions) ?? resolveObjectSchema(resolved, ctx.definitions);
if (isNamedPyObjectSchema(resolvedObject)) {
emitPyClass(typeName, resolvedObject, ctx, resolvedObject.description);
return {
typeName,
resolved: {
annotation: typeName,