-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.js
More file actions
6930 lines (6383 loc) · 331 KB
/
Copy pathai.js
File metadata and controls
6930 lines (6383 loc) · 331 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
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { basename, join } from "node:path";
import { fileURLToPath } from "node:url";
import Groq from "groq-sdk";
const DEFAULT_CODE_GENERATION_MODEL = "openai/gpt-oss-120b";
const DEFAULT_STRONG_TEXT_MODEL = "llama-3.3-70b-versatile";
const DEFAULT_FAST_MODEL = "llama-3.1-8b-instant";
const CODE_GENERATION_MODEL = process.env.GROQ_GENERATION_MODEL
|| process.env.GROQ_CODE_MODEL
|| DEFAULT_CODE_GENERATION_MODEL;
const TEXT_MODEL = process.env.GROQ_MODEL || DEFAULT_STRONG_TEXT_MODEL;
const FAST_MODEL = process.env.GROQ_FAST_MODEL || DEFAULT_FAST_MODEL;
const COMPLEX_MODEL = process.env.GROQ_COMPLEX_MODEL || CODE_GENERATION_MODEL;
const DIM_MODEL = process.env.GROQ_DIM_MODEL || COMPLEX_MODEL;
const FALLBACK_MODEL = process.env.GROQ_FALLBACK_MODEL || DEFAULT_STRONG_TEXT_MODEL;
const VISION_MODEL = process.env.GROQ_VISION_MODEL || "meta-llama/llama-4-scout-17b-16e-instruct";
const GENERATION_STRATEGY = String(process.env.CAD_GENERATION_MODE || "ai_first").toLowerCase();
// The live generation path uses a strict validated FeatureScript skeleton by default.
// Set USE_VALIDATED_TEMPLATES=false only when intentionally testing free-form prompting.
const USE_VALIDATED_TEMPLATES = String(process.env.USE_VALIDATED_TEMPLATES || "true").toLowerCase() !== "false";
const ALLOW_TEMPLATE_FALLBACK = String(process.env.ALLOW_TEMPLATE_FALLBACK || "false").toLowerCase() === "true";
const ENABLE_OPERATION_COMPILER_FALLBACK = String(process.env.CAD_ENABLE_OPERATION_COMPILER_FALLBACK || "false").toLowerCase() === "true";
// ------------------------------
// Model configuration
// ------------------------------
const GROQ_TIMEOUT_MS = Number(process.env.GROQ_TIMEOUT_MS || 120000);
const RAW_GROQ_MAX_COMPLETION_TOKENS = Number(process.env.GROQ_MAX_COMPLETION_TOKENS || 8192);
const GROQ_MAX_COMPLETION_TOKENS = Number.isFinite(RAW_GROQ_MAX_COMPLETION_TOKENS) ? RAW_GROQ_MAX_COMPLETION_TOKENS : 8192;
const RAW_GROQ_CODE_MAX_COMPLETION_TOKENS = Number(process.env.GROQ_CODE_MAX_COMPLETION_TOKENS || process.env.GROQ_GENERATION_MAX_COMPLETION_TOKENS || GROQ_MAX_COMPLETION_TOKENS || 8192);
const GROQ_CODE_MAX_COMPLETION_TOKENS = Math.max(
4096,
Number.isFinite(RAW_GROQ_CODE_MAX_COMPLETION_TOKENS) ? RAW_GROQ_CODE_MAX_COMPLETION_TOKENS : GROQ_MAX_COMPLETION_TOKENS
);
const GROQ_MAX_PROMPT_CHARS = Number(process.env.GROQ_MAX_PROMPT_CHARS || 160000);
const GROQ_TEMPERATURE = Number(process.env.GROQ_TEMPERATURE || 0.2);
const VISION_TIMEOUT_MS = Number(process.env.VISION_TIMEOUT_MS || 12000);
const VISION_MAX_TOKENS = Number(process.env.GROQ_VISION_MAX_TOKENS || 800);
const CAD_CANDIDATE_COUNT = Math.max(1, Math.min(9, Number(process.env.CAD_CANDIDATE_COUNT || 3)));
const CAD_REPAIR_ATTEMPTS = Math.max(1, Math.min(3, Number(process.env.CAD_REPAIR_ATTEMPTS || 1)));
const CAD_RETRIEVAL_WORKERS = Math.max(1, Math.min(6, Number(process.env.CAD_RETRIEVAL_WORKERS || 3)));
const MULTI_KEY_ENABLED = String(process.env.GROQ_MULTI_KEY_ENABLED || "true").toLowerCase() !== "false";
const MAX_RETRIEVED_SNIPPETS = Math.max(1, Math.min(6, Number(process.env.CAD_MAX_RETRIEVED_SNIPPETS || 6)));
const MAX_RETRIEVED_SNIPPET_CHARS = Math.max(400, Math.min(4000, Number(process.env.CAD_MAX_RETRIEVED_SNIPPET_CHARS || 2200)));
const MAX_OMNI_SUMMARY_CHARS = Math.max(400, Math.min(2400, Number(process.env.CAD_MAX_OMNI_SUMMARY_CHARS || 1100)));
export const STRICT_FEATURESCRIPT_TEMPLATE = `FeatureScript 2931;
import(path : "onshape/std/geometry.fs", version : "2931.0");
annotation { "Feature Type Name" : "Template Driven Part" }
export const templateDrivenPart = defineFeature(function(context is Context, id is Id, definition is map)
precondition
{
annotation { "Name" : "Plane", "Filter" : GeometryType.PLANE, "MaxNumberOfPicks" : 1 }
definition.location is Query;
annotation { "Name" : "Width" }
isLength(definition.width, { (inch) : [0.1, 2.0, 24.0] } as LengthBoundSpec);
annotation { "Name" : "Height" }
isLength(definition.height, { (inch) : [0.1, 1.5, 24.0] } as LengthBoundSpec);
annotation { "Name" : "Depth" }
isLength(definition.depth, { (inch) : [0.05, 0.5, 12.0] } as LengthBoundSpec);
}
{
var skPlane = isQueryEmpty(context, definition.location)
? plane(WORLD_ORIGIN, Z_DIRECTION)
: evPlane(context, { "face" : definition.location });
var halfWidth = definition.width / 2;
var halfHeight = definition.height / 2;
var profileSketch = newSketchOnPlane(context, id + "profileSketch", { "sketchPlane" : skPlane });
skRectangle(profileSketch, "profile", {
"firstCorner" : vector((-halfWidth) / inch, (-halfHeight) / inch) * inch,
"secondCorner" : vector(halfWidth / inch, halfHeight / inch) * inch
});
skSolve(profileSketch);
opExtrude(context, id + "body", {
"entities" : qSketchRegion(id + "profileSketch"),
"direction" : skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.depth
});
});`;
export const FS_COMPILER_AGENT_CONTRACT = `FEATURESCRIPT 2931 COMPILER-AGENT CONTRACT
Output policy:
- Return JSON only with featureName, featureLabel, reasoning, and code.
- The code field must be one complete FeatureScript 2931 file with exactly one exported defineFeature.
- Preserve the app response contract outside the model, but candidates themselves use only the strict JSON schema.
- Do not truncate the code. Output the COMPLETE FeatureScript from start to finish.
- Never use placeholders or comments like "// rest of code here", "// TODO", "...", or omitted sections.
Required structural template:
You MUST follow this template's exact module structure: FeatureScript version, geometry import, annotation block, one export const defineFeature, precondition block, and feature body block.
You may rename the feature, labels, parameters, and internal operation logic to match the user request, but do not invent a different top-level structure.
${STRICT_FEATURESCRIPT_TEMPLATE}
Template discipline:
- Keep the annotation { "Feature Type Name" : "..." } block directly above the exported feature.
- Keep all user parameters in precondition. Put executable code only in the second body block.
- Keep exactly one exported defineFeature.
- Before responding, self-check that the file begins with FeatureScript 2931; and ends with the closing "});".
Hard FeatureScript syntax rules:
1. const is allowed only at module top level, or for helper lambda assignments at the direct top level of the feature body. Inside if/else/for/while blocks, use var.
2. Helper lambdas inside the feature body must be untyped and must end with a semicolon: const helper = function(x, y) { ... };
3. FeatureScript has no ++ or -- operators. Use += 1 or -= 1.
4. FeatureScript arrays do not have .length. Use size(array) or track a counter.
5. Numeric preconditions never use a "Default" annotation key. Defaults belong in the bounds triple.
6. Length bounds use explicit LengthBoundSpec, for example isLength(definition.width, { (inch) : [0.1, 1.0, 10.0] } as LengthBoundSpec);
7. Integer and degree-like bounds use IntegerBoundSpec, for example isInteger(definition.numTeeth, { (unitless) : [6, 20, 200] } as IntegerBoundSpec);
8. The precondition block contains declarations only. No var declarations, sketches, loops, conditionals, operation calls, or plane evaluation.
9. Every sketch with entities must call skSolve(sketchVar) before opExtrude, opRevolve, opLoft, or opSweep consumes it.
10. qSketchRegion must receive the sketch id expression, such as qSketchRegion(id + "sk1"), never the sketch variable.
11. isLength parameters already carry Length units. Do not multiply definition.lengthParam by * inch in the body; divide by inch only when a unitless vector coordinate is needed.`;
const PROJECT_ROOT = fileURLToPath(new URL(".", import.meta.url));
const FS_EXAMPLES_DIR = join(PROJECT_ROOT, "data", "fs_examples");
const SOURCE_KNOWLEDGE_PATH = join(PROJECT_ROOT, "data", "sourceKnowledge.new.json");
const DATASET_SUMMARY_PATH = join(PROJECT_ROOT, "data", "cadDatasetSummaries.json");
const CAPTION_PAIRS_PATH = join(PROJECT_ROOT, "data", "captionGeometryPairs.json");
const LOCAL_OMNI_SUMMARY_PATHS = [
join(PROJECT_ROOT, "docs", "research_summaries", "cad_mllm_and_omni_cad.md"),
join(PROJECT_ROOT, "docs", "research_summaries", "local_omni_cad_dataset.md"),
join(PROJECT_ROOT, "docs", "research_summaries", "deepcad.md"),
join(PROJECT_ROOT, "docs", "research_summaries", "cambridge_text_to_design.md"),
];
const NUMBERED_SHARED_GROQ_KEYS = [
"GROQ_API_KEY",
"GROQ_API_KEY2",
"GROQ_API_KEY3",
"GROQ_API_KEY4",
"GROQ_API_KEY5",
"GROQ_API_KEY6",
"GROQ_API_KEY7",
"GROQ_API_KEY8",
"GROQ_API_KEY9",
];
const FIXED_KEY_SLOT_SEQUENCE = ["k1", "k2", "k3", "k4", "k5", "k6", "k7", "k8", "k9"];
const STAGE_API_KEY_ENV = {
shared: ["GROQ_API_KEYS", ...NUMBERED_SHARED_GROQ_KEYS],
dimensions: ["GROQ_DIM_API_KEYS", "GROQ_DIM_API_KEY"],
planning: ["GROQ_PLAN_API_KEYS", "GROQ_PLAN_API_KEY"],
retrieval: ["GROQ_RETRIEVAL_API_KEYS", "GROQ_RETRIEVAL_API_KEY"],
generation: ["GROQ_GENERATION_API_KEYS", "GROQ_GENERATION_API_KEY"],
repair: ["GROQ_REPAIR_API_KEYS", "GROQ_REPAIR_API_KEY"],
validation: ["GROQ_VALIDATION_API_KEYS", "GROQ_VALIDATION_API_KEY"],
vision: ["GROQ_VISION_API_KEYS", "GROQ_VISION_API_KEY"],
};
const groqClientCache = new Map();
const stageCursor = new Map();
let cachedFsExampleLibrary = null;
let cachedOmniSummaryText = null;
let cachedSourceKnowledgeRows = null;
let cachedDatasetSummaryRows = null;
let cachedCaptionPairRows = null;
function splitEnvList(rawValue) {
return String(rawValue || "")
.split(/[\r\n,;]+/)
.map(value => value.trim())
.filter(Boolean);
}
function uniqueStrings(values) {
return [...new Set(values.filter(Boolean))];
}
function selectCodeGenerationModel() {
return CODE_GENERATION_MODEL;
}
function codeGenerationFallbackModels(primaryModel = CODE_GENERATION_MODEL) {
return uniqueStrings([
COMPLEX_MODEL,
DEFAULT_CODE_GENERATION_MODEL,
FALLBACK_MODEL,
TEXT_MODEL,
]).filter(candidate => candidate && candidate !== primaryModel);
}
function loadStageKeys(stage) {
const sharedKeys = uniqueStrings(
(STAGE_API_KEY_ENV.shared || []).flatMap(name => splitEnvList(process.env[name]))
);
const stageKeys = uniqueStrings(
(STAGE_API_KEY_ENV[stage] || []).flatMap(name => splitEnvList(process.env[name]))
);
return uniqueStrings(stageKeys.length ? stageKeys : sharedKeys);
}
function getStageKeyPool(stage = "generation") {
const requestedStage = Object.prototype.hasOwnProperty.call(STAGE_API_KEY_ENV, stage) ? stage : "generation";
const pool = loadStageKeys(requestedStage);
if (!pool.length) {
throw new Error("Missing Groq API key configuration. Set GROQ_API_KEY or GROQ_API_KEYS.");
}
return MULTI_KEY_ENABLED ? pool : [pool[0]];
}
function stableHash(input) {
let hash = 0;
const text = String(input || "");
for (let index = 0; index < text.length; index += 1) {
hash = ((hash << 5) - hash) + text.charCodeAt(index);
hash |= 0;
}
return Math.abs(hash);
}
function pickStageCredential(stage = "generation", affinity = "", keySlot = null) {
const pool = getStageKeyPool(stage);
let slotIndex = 0;
const requestedSlot = keySlot;
if (requestedSlot && /^k\d+$/i.test(String(requestedSlot))) {
const explicitIndex = Math.max(0, Number(String(requestedSlot).slice(1)) - 1);
slotIndex = explicitIndex % pool.length;
} else if (affinity) {
slotIndex = stableHash(`${stage}:${affinity}`) % pool.length;
} else {
const current = stageCursor.get(stage) || 0;
slotIndex = current % pool.length;
stageCursor.set(stage, current + 1);
}
return {
apiKey: pool[slotIndex],
slotIndex,
slotLabel: requestedSlot && /^k\d+$/i.test(String(requestedSlot))
? String(requestedSlot).toLowerCase()
: `${stage}-slot-${slotIndex + 1}`,
poolSize: pool.length,
};
}
function getGroqClient(apiKey, timeout) {
const cacheKey = `${timeout}:${apiKey}`;
if (!groqClientCache.has(cacheKey)) {
groqClientCache.set(cacheKey, new Groq({
apiKey,
timeout,
maxRetries: 0,
}));
}
return groqClientCache.get(cacheKey);
}
function loadFsExampleLibrary() {
if (cachedFsExampleLibrary) return cachedFsExampleLibrary;
if (!existsSync(FS_EXAMPLES_DIR)) {
cachedFsExampleLibrary = [];
return cachedFsExampleLibrary;
}
const manifest = {};
const manifestPath = join(FS_EXAMPLES_DIR, "manifest.json");
if (existsSync(manifestPath)) {
try {
for (const entry of JSON.parse(readFileSync(manifestPath, "utf8")).examples || []) {
if (entry?.file) manifest[entry.file] = entry;
}
} catch (err) {
console.warn(`[AI] Could not parse fs_examples manifest: ${err.message}`);
}
}
cachedFsExampleLibrary = readdirSync(FS_EXAMPLES_DIR)
.filter(fileName => fileName.endsWith(".fs"))
.map(fileName => {
const fullPath = join(FS_EXAMPLES_DIR, fileName);
const meta = manifest[fileName] || {};
return {
id: basename(fileName, ".fs"),
fileName,
title: meta.title || basename(fileName, ".fs"),
keywords: Array.isArray(meta.keywords) && meta.keywords.length
? meta.keywords.map(keyword => String(keyword).toLowerCase())
: basename(fileName, ".fs").split(/[_-]+/),
lesson: meta.lesson || "",
content: readFileSync(fullPath, "utf8"),
};
});
return cachedFsExampleLibrary;
}
// Pick the compile-verified example(s) whose keywords best match the prompt.
// These are injected as few-shot grounding so the model sees real, validated
// FeatureScript for the requested kind of geometry, not just prose rules.
function selectFsExamplesForPrompt(prompt = "", dims = {}, limit = 1) {
// Words the user actually typed outweigh words derived from the inferred
// shape, so "create a pen" picks the pen example over a generic cylinder.
const promptText = String(prompt || "").toLowerCase();
const shapeText = String(dims.shape || "").toLowerCase().replace(/_/g, " ");
const scored = loadFsExampleLibrary()
.map(example => {
let score = 0;
for (const keyword of example.keywords) {
if (!keyword) continue;
if (keyword.includes(" ")) {
if (promptText.includes(keyword)) score += 4;
else if (shapeText.includes(keyword)) score += 1;
continue;
}
const wordPattern = new RegExp(`\\b${keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
if (wordPattern.test(promptText)) score += 2;
else if (wordPattern.test(shapeText)) score += 1;
}
return { example, score };
})
.filter(entry => entry.score >= 1)
.sort((a, b) => b.score - a.score);
return scored.slice(0, Math.max(1, limit)).map(entry => entry.example);
}
function buildFsExamplePromptBlock(prompt, dims, { limit = 1, maxChars = 2800 } = {}) {
if (dims?.shape === "GEAR_SPUR") return ""; // gears carry their own validated template
const examples = selectFsExamplesForPrompt(prompt, dims, limit);
if (!examples.length) return "";
return examples.map(example => [
`COMPILE_VERIFIED_EXAMPLE (${example.title})${example.lesson ? ` — ${example.lesson}` : ""}:`,
compactFeaturePattern(example.content, maxChars),
"Adapt this example's structure, API usage, and operation order to the user request. Do not copy it verbatim — rename the feature, adjust parameters, and build the geometry the user asked for.",
].join("\n")).join("\n\n");
}
function loadLocalOmniSummaryText() {
if (cachedOmniSummaryText !== null) return cachedOmniSummaryText;
cachedOmniSummaryText = LOCAL_OMNI_SUMMARY_PATHS
.filter(filePath => existsSync(filePath))
.map(filePath => readFileSync(filePath, "utf8"))
.join("\n");
return cachedOmniSummaryText;
}
function loadJsonRows(filePath, cacheKey) {
if (cacheKey === "source" && cachedSourceKnowledgeRows) return cachedSourceKnowledgeRows;
if (cacheKey === "dataset" && cachedDatasetSummaryRows) return cachedDatasetSummaryRows;
if (cacheKey === "captionPairs" && cachedCaptionPairRows) return cachedCaptionPairRows;
const setCache = rows => {
if (cacheKey === "source") cachedSourceKnowledgeRows = rows;
if (cacheKey === "dataset") cachedDatasetSummaryRows = rows;
if (cacheKey === "captionPairs") cachedCaptionPairRows = rows;
return rows;
};
if (!existsSync(filePath)) return setCache([]);
try {
const parsed = JSON.parse(readFileSync(filePath, "utf8"));
const rows = Array.isArray(parsed)
? parsed
: Array.isArray(parsed?.rows)
? parsed.rows
: [];
return setCache(rows);
} catch (err) {
console.warn(`[AI] Could not read ${cacheKey} rows from ${filePath}: ${err.message}`);
return setCache([]);
}
}
function loadSourceKnowledgeRows() {
return loadJsonRows(SOURCE_KNOWLEDGE_PATH, "source");
}
function loadDatasetSummaryRows() {
return loadJsonRows(DATASET_SUMMARY_PATH, "dataset");
}
function loadCaptionPairRows() {
return loadJsonRows(CAPTION_PAIRS_PATH, "captionPairs");
}
export function getModelConfig() {
const sharedKeyCount = loadStageKeys("shared").length;
return {
provider: "groq",
text: TEXT_MODEL,
fast: FAST_MODEL,
generation: CODE_GENERATION_MODEL,
complex: COMPLEX_MODEL,
dimensions: DIM_MODEL,
fallback: FALLBACK_MODEL,
validatedTemplates: USE_VALIDATED_TEMPLATES,
allowTemplateFallback: ALLOW_TEMPLATE_FALLBACK,
vision: VISION_MODEL,
maxCompletionTokens: GROQ_MAX_COMPLETION_TOKENS,
codeMaxCompletionTokens: GROQ_CODE_MAX_COMPLETION_TOKENS,
multiKeyEnabled: MULTI_KEY_ENABLED,
candidateCount: CAD_CANDIDATE_COUNT,
retrievalWorkers: CAD_RETRIEVAL_WORKERS,
sharedKeyCount,
stageKeyCounts: {
dimensions: safeStageKeyCount("dimensions"),
planning: safeStageKeyCount("planning"),
retrieval: safeStageKeyCount("retrieval"),
generation: safeStageKeyCount("generation"),
repair: safeStageKeyCount("repair"),
validation: safeStageKeyCount("validation"),
vision: safeStageKeyCount("vision"),
},
};
}
function truncateForLog(text, max = 800) {
const normalized = typeof text === "string" ? text : JSON.stringify(text);
return normalized.length > max ? `${normalized.slice(0, max)}...<truncated>` : normalized;
}
async function parseJsonResponse(response, label) {
const rawText = await response.text();
let data;
try {
data = rawText ? JSON.parse(rawText) : {};
} catch (err) {
const error = new Error(`${label} returned invalid JSON (status ${response.status})`);
error.cause = err;
error.details = {
status: response.status,
statusText: response.statusText,
body: truncateForLog(rawText),
};
throw error;
}
if (!response.ok) {
const error = new Error(`${label} request failed with status ${response.status}`);
error.details = {
status: response.status,
statusText: response.statusText,
body: truncateForLog(rawText),
data,
};
throw error;
}
return data;
}
function logFetchError(label, err, extra = {}) {
console.error(`[${label}] request failed`, {
message: err?.message || String(err),
name: err?.name,
cause: err?.cause?.message,
stack: err?.stack,
details: err?.details || null,
...extra,
});
}
function normalizeMessageContent(content) {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content
.map(part => {
if (typeof part === "string") return part;
if (part?.type === "text") return part.text || "";
return "";
})
.filter(Boolean)
.join("\n")
.trim();
}
return "";
}
async function callGroqVisionLLM(messages, model = VISION_MODEL, options = {}) {
const credential = pickStageCredential("vision", options.affinity, options.keySlot);
const client = getGroqClient(credential.apiKey, VISION_TIMEOUT_MS);
try {
const completion = await client.chat.completions.create({
model,
messages,
max_completion_tokens: VISION_MAX_TOKENS,
});
const content = normalizeMessageContent(completion?.choices?.[0]?.message?.content);
if (!content) {
const error = new Error("Invalid Groq response");
error.details = { body: truncateForLog(completion) };
throw error;
}
return content;
} catch (err) {
console.error("[Groq Vision] request failed", {
message: err?.message || String(err),
name: err?.name,
status: err?.status,
cause: err?.cause?.message,
stack: err?.stack,
model,
slot: credential.slotLabel,
poolSize: credential.poolSize,
});
throw err;
}
}
// ------------------------------
// 1. Text LLM via Groq
// ------------------------------
async function callGroqTextLLM(messagesOrPrompt, model = TEXT_MODEL, options = {}) {
const stage = options.stage || "generation";
const credential = pickStageCredential(stage, options.affinity, options.keySlot);
const defaultCompletionTokens = options.fullCode ? GROQ_CODE_MAX_COMPLETION_TOKENS : GROQ_MAX_COMPLETION_TOKENS;
const requestedCompletionTokens = Number(options.maxCompletionTokens || defaultCompletionTokens);
const hardCompletionCeiling = Math.max(GROQ_MAX_COMPLETION_TOKENS, defaultCompletionTokens);
// Respect an explicitly smaller request (used when shrinking to fit a TPM limit),
// but never go below 1024 for full-code calls.
const completionFloor = options.fullCode
? Math.max(1024, Math.min(4096, Number.isFinite(requestedCompletionTokens) ? requestedCompletionTokens : 4096))
: 256;
const maxCompletionTokens = Math.max(
completionFloor,
Math.min(
Number.isFinite(requestedCompletionTokens) ? requestedCompletionTokens : defaultCompletionTokens,
hardCompletionCeiling
)
);
const messages = Array.isArray(messagesOrPrompt)
? messagesOrPrompt
: [{ role: "user", content: String(messagesOrPrompt) }];
const requestBody = {
model,
messages,
// Groq's current chat-completions field is max_completion_tokens.
// max_tokens is still accepted but deprecated in groq-sdk.
max_completion_tokens: maxCompletionTokens,
temperature: GROQ_TEMPERATURE,
};
const client = getGroqClient(credential.apiKey, options.timeoutMs || GROQ_TIMEOUT_MS);
const startedAt = Date.now();
try {
console.log(`[Groq Text] stage=${stage} model=${model} timeoutMs=${options.timeoutMs || GROQ_TIMEOUT_MS} slot=${credential.slotLabel}/${credential.poolSize}`);
console.log(`[Groq Text] outgoing=${truncateForLog(requestBody, 800)}`);
const completion = await client.chat.completions.create(requestBody);
const content = normalizeMessageContent(completion?.choices?.[0]?.message?.content);
if (!content) {
const error = new Error("Invalid Groq text response");
error.details = { body: truncateForLog(completion, 1200) };
throw error;
}
console.log(`[Groq Text] success stage=${stage} model=${model} durationMs=${Date.now() - startedAt} slot=${credential.slotLabel}`);
return content;
} catch (err) {
logFetchError("Groq Text", err, {
model,
stage,
slot: credential.slotLabel,
poolSize: credential.poolSize,
durationMs: Date.now() - startedAt,
timeoutMs: options.timeoutMs || GROQ_TIMEOUT_MS,
});
throw err;
}
}
// ------------------------------
// 2. Universal LLM router
// ------------------------------
/**
* callLLM accepts either a plain string or a messages array and always routes
* text generation through Groq.
*/
export async function callLLM(promptOrMessages, model = TEXT_MODEL, options = {}) {
console.log(`[LLM Router] stage=${options.stage || "generation"} model=${model} render=${Boolean(process.env.RENDER)}`);
return await callGroqTextLLM(promptOrMessages, model, options);
}
export const CAD_MLLM_PLAN_PROMPT = `CAD-MLLM planning pass:
1. Classify the requested shape and extract editable parameters.
2. Decompose the model into revolve, loft, sweep, extrude, shell, boolean, fillet, chamfer, or pattern subtasks.
3. Retrieve matching cad_knowledge, cad_pruning_table, cad_memory, dataset examples, and FeatureScript snippets for each subtask.
4. Prefer command-sequence style construction: solved sketch/profile first, then a downstream solid operation.
5. Emit a short ordered plan with operation, parameters, validation rules, and fallback template for each subtask.`;
export const CAD_MLLM_EXECUTE_PROMPT = `CAD-MLLM execution pass:
Use retrieved examples and pruning rules to write one complete FeatureScript 2931 file.
Expose all user-editable dimensions in precondition, call skSolve before downstream operations, use real Line axes for revolves, use profileSubqueries for opLoft, use connected edge paths for opSweep, validate the static rules, repair once if needed, then return compile-safe FeatureScript only.`;
function extractFirstJsonObject(text = "") {
const source = String(text || "");
let start = -1;
let depth = 0;
let inString = false;
let escaped = false;
for (let index = 0; index < source.length; index += 1) {
const ch = source[index];
if (escaped) {
escaped = false;
continue;
}
if (ch === "\\") {
escaped = inString;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (ch === "{") {
if (depth === 0) start = index;
depth += 1;
} else if (ch === "}") {
depth -= 1;
if (depth === 0 && start !== -1) return source.slice(start, index + 1);
}
}
return "";
}
function stripJson(text) {
const raw = String(text || "");
const m = raw.match(/```(?:json|javascript)?\s*([\s\S]*?)```/i);
const candidate = (m ? m[1] : raw).trim();
return extractFirstJsonObject(candidate) || candidate || "{}";
}
function promptRequestsAxialHole(prompt = "") {
return /\b(bore|through hole|center hole|centre hole|axial hole|hole down the center|hole down the centre|hollow|inner diameter|\bid\b|hole on (the )?top|hole in the top|top hole)\b/i.test(prompt);
}
function promptRequestsBlindTopHole(prompt = "") {
const mentionsTopHole = /\b(hole on (the )?top|hole in the top|top hole|blind hole|blind bore|counterbore)\b/i.test(prompt);
const mentionsThroughHole = /\b(through hole|bore through|pass through|through bore|hollow|inner diameter)\b/i.test(prompt);
return mentionsTopHole && !mentionsThroughHole;
}
function inferShapeFromPrompt(prompt = "") {
const text = normalizeText(prompt).toLowerCase();
const shapeHints = [
["ROBOT_MECH", /\b(robot|robotic|mech|mecha|android|humanoid)\b/],
["GEAR_SPUR", /\b(gear|spur|pinion|teeth|tooth|diametral pitch|pressure angle|involute)\b/],
["FLANGE", /\b(flange|bolt circle|bolt hole|hub|mount|coupling flange)\b/],
["LINKAGE", /\b(linkage|linkage arm|connecting rod|coupler|arm|lever|clevis|tie rod|rod end)\b/],
["WASHER", /\b(washer|ring magnet|ring|shim|spacer disk)\b/],
["CYLINDER", /\b(wheel|roller|cylinder|rod|shaft|pipe|tube|dowel|pin|post|standoff|magnet|pen|pencil|marker|stylus)\b/],
["BOX", /\b(box|block|cube|rectangular|bar magnet)\b/],
["CONE", /\b(carrot|cone|frustum|tapered|nozzle|funnel)\b/],
["POLYGON", /\b(hex|hexagon|triangle|polygon|octagon|pentagon|n-sided)\b/],
];
return shapeHints.find(([, pattern]) => pattern.test(text))?.[0] || null;
}
function promptNeedsHighFidelityModel(prompt = "") {
return /\b(organic|realistic|carrot|freeform|smooth|curved|spline|loft|sweep|sculpt|detailed|gear|involute|helical|complex)\b/i.test(prompt);
}
function contentPartToText(part) {
if (typeof part === "string") return part;
if (!part || typeof part !== "object") return String(part ?? "");
if (part.type === "text") return part.text || "";
if (part.type === "image_url") return `[image: ${part.image_url?.url ? "attached" : "missing"}]`;
return JSON.stringify(part);
}
function messagesToPrompt(messages = []) {
return messages.map(message => {
const role = String(message?.role || "user").toUpperCase();
const content = Array.isArray(message?.content)
? message.content.map(contentPartToText).join("\n")
: contentPartToText(message?.content);
return `${role}:\n${content}`;
}).join("\n\n");
}
function nextKeySlot(slot) {
const match = /^k(\d+)$/i.exec(String(slot || ""));
if (!match) return null;
const index = Number(match[1]);
return `k${(index % FIXED_KEY_SLOT_SEQUENCE.length) + 1}`;
}
async function chat(messages, model = TEXT_MODEL, fallbackModels = null, options = {}) {
const fallbackList = Array.isArray(fallbackModels)
? fallbackModels
: (model === TEXT_MODEL ? [FALLBACK_MODEL] : []);
const modelsToTry = [model, ...fallbackList.filter(candidate => candidate && candidate !== model)];
const ATTEMPTS_PER_MODEL = 2;
let lastError = null;
for (const candidate of modelsToTry) {
let attemptOptions = { ...options };
for (let attempt = 0; attempt < ATTEMPTS_PER_MODEL; attempt += 1) {
try {
const text = await callLLM(messages, candidate, attemptOptions);
if (candidate !== model) console.warn(`[AI] Used fallback model ${candidate} for stage=${options.stage || "generation"}`);
return text;
} catch (err) {
lastError = err;
const message = String(err?.message || "");
const tooLarge = /request too large|reduce your message size/i.test(message);
const rateLimited = /rate limit|tokens per minute|tpm|429|rate_limit_exceeded/i.test(message);
if (tooLarge) {
// Groq counts prompt + max_completion_tokens against the TPM limit.
// Shrink the completion budget so the request fits instead of abandoning the model.
const limit = Number(message.match(/Limit\s+(\d+)/i)?.[1] || 0);
const requested = Number(message.match(/Requested\s+(\d+)/i)?.[1] || 0);
const currentCompletion = Number(attemptOptions.maxCompletionTokens
|| (attemptOptions.fullCode ? GROQ_CODE_MAX_COMPLETION_TOKENS : GROQ_MAX_COMPLETION_TOKENS));
const promptTokens = Math.max(0, requested - currentCompletion);
const shrunkCompletion = limit - promptTokens - 256;
if (limit && requested && shrunkCompletion >= 1024 && shrunkCompletion < currentCompletion) {
console.warn(`[AI] Request too large for ${candidate}; shrinking completion tokens ${currentCompletion} -> ${shrunkCompletion} and retrying.`);
attemptOptions = { ...attemptOptions, maxCompletionTokens: shrunkCompletion };
continue;
}
console.warn(`[AI] Request cannot fit ${candidate} TPM limit even after shrinking; trying next fallback model.`);
break;
}
if (rateLimited && options.retryOnRateLimit !== false) {
const retrySeconds = Number(message.match(/try again in\s+([\d.]+)s/i)?.[1] || 0);
const waitMs = Number(options.rateLimitBackoffMs || Math.max(1200, Math.ceil(retrySeconds * 1000) + 500));
const rotatedSlot = nextKeySlot(attemptOptions.keySlot);
if (rotatedSlot) {
console.warn(`[AI] Rate limit on stage=${options.stage || "generation"} model=${candidate}; rotating key ${attemptOptions.keySlot} -> ${rotatedSlot}, retrying after ${waitMs}ms.`);
attemptOptions = { ...attemptOptions, keySlot: rotatedSlot };
} else {
console.warn(`[AI] Rate limit on stage=${options.stage || "generation"} model=${candidate}; retrying after ${waitMs}ms.`);
}
await new Promise(resolve => setTimeout(resolve, waitMs));
continue;
}
break;
}
}
}
throw lastError || new Error("All Groq model calls failed.");
}
// ─── FeatureScript building blocks ───────────────────────────────────────────
//
// Key FeatureScript rules baked in here, not left to the AI:
// - isLength(definition.foo, { (inch) : [min, default, max] } as LengthBoundSpec)
// in precondition gives the user an editable slider without numeric Default annotations
// - definition.foo in body already has Length type — do NOT multiply by * inch
// - sketch circles + extrude are the most reliable path for cylinders with bores
// - fCylinder takes: context, id, { bottomCenter, topCenter, radius }
// - newSketchOnPlane for user-selected planes, not newSketch
// - skSolve() after all sketch entities, before any opExtrude
function n(x) { return parseFloat(Number(x).toFixed(6)).toString(); }
function preconditionPlane() {
return ` annotation { "Name" : "Plane", "Filter" : GeometryType.PLANE, "MaxNumberOfPicks" : 1 }
definition.location is Query;`;
}
function preconditionLength(paramName, label, min, def, max) {
const safeMin = Number.isFinite(Number(min)) ? Number(min) : 0.01;
const safeMax = Math.max(safeMin, Number.isFinite(Number(max)) ? Number(max) : safeMin * 10);
const rawDefault = Number.isFinite(Number(def)) ? Number(def) : safeMin;
const defaultValue = Math.min(Math.max(rawDefault, safeMin), safeMax);
return ` annotation { "Name" : "${label}" }
isLength(definition.${paramName}, { (inch) : [${n(safeMin)}, ${n(defaultValue)}, ${n(safeMax)}] } as LengthBoundSpec);`;
}
function preconditionInteger(paramName, label, min, def, max) {
const defaultValue = Math.min(Math.max(Math.round(def || min), min), max);
return ` annotation { "Name" : "${label}" }
isInteger(definition.${paramName}, { (unitless) : [${min}, ${defaultValue}, ${max}] } as IntegerBoundSpec);`;
}
function preconditionDegrees(paramName, label, min, def, max) {
return preconditionInteger(paramName, label, min, Math.round(Number(def) || min), max);
}
function planeVar() {
return ` var skPlane = isQueryEmpty(context, definition.location)
? plane(WORLD_ORIGIN, Z_DIRECTION)
: evPlane(context, { "face" : definition.location });`;
}
function fsPoint(xExpr, yExpr, zExpr = null) {
if (zExpr === null) {
return `vector((${xExpr}) / inch, (${yExpr}) / inch) * inch`;
}
return `vector((${xExpr}) / inch, (${yExpr}) / inch, (${zExpr}) / inch) * inch`;
}
/*
This part is all the pre made template that is soon to be removed or jnust added to the database
_____________________________________________________________________________________________________________________
*/
function tRobotMech(d) {
return {
precondition: [
preconditionPlane(),
preconditionLength("width", "Overall Width", 1, d.widthInches || 12, 96),
preconditionLength("height", "Overall Height", 1, d.heightInches || 12, 96),
preconditionLength("depth", "Block Depth", 0.1, d.depthInches || 6, 48),
d.filletRadiusInches > 0
? preconditionLength("fillet", "Fillet Radius", 0, d.filletRadiusInches, 4)
: "",
].filter(Boolean).join("\n"),
body: `${planeVar()}
var sketch1 = newSketchOnPlane(context, id + "sketch1", { "sketchPlane" : skPlane });
// Blocky mech silhouette: head, torso, arms, legs, and feet as separate cuboid regions.
skRectangle(sketch1, "head", {
"firstCorner" : ${fsPoint("-definition.width * 0.14", "definition.height * 0.30")},
"secondCorner" : ${fsPoint(" definition.width * 0.14", "definition.height * 0.50")}
});
skRectangle(sketch1, "torso", {
"firstCorner" : ${fsPoint("-definition.width * 0.22", "-definition.height * 0.08")},
"secondCorner" : ${fsPoint(" definition.width * 0.22", " definition.height * 0.28")}
});
skRectangle(sketch1, "leftUpperArm", {
"firstCorner" : ${fsPoint("-definition.width * 0.44", " definition.height * 0.04")},
"secondCorner" : ${fsPoint("-definition.width * 0.26", " definition.height * 0.24")}
});
skRectangle(sketch1, "rightUpperArm", {
"firstCorner" : ${fsPoint("definition.width * 0.26", " definition.height * 0.04")},
"secondCorner" : ${fsPoint("definition.width * 0.44", " definition.height * 0.24")}
});
skRectangle(sketch1, "leftForearm", {
"firstCorner" : ${fsPoint("-definition.width * 0.50", "-definition.height * 0.18")},
"secondCorner" : ${fsPoint("-definition.width * 0.32", " definition.height * 0.02")}
});
skRectangle(sketch1, "rightForearm", {
"firstCorner" : ${fsPoint("definition.width * 0.32", "-definition.height * 0.18")},
"secondCorner" : ${fsPoint("definition.width * 0.50", " definition.height * 0.02")}
});
skRectangle(sketch1, "leftLeg", {
"firstCorner" : ${fsPoint("-definition.width * 0.18", "-definition.height * 0.44")},
"secondCorner" : ${fsPoint("-definition.width * 0.04", "-definition.height * 0.10")}
});
skRectangle(sketch1, "rightLeg", {
"firstCorner" : ${fsPoint("definition.width * 0.04", "-definition.height * 0.44")},
"secondCorner" : ${fsPoint("definition.width * 0.18", "-definition.height * 0.10")}
});
skRectangle(sketch1, "leftFoot", {
"firstCorner" : ${fsPoint("-definition.width * 0.28", "-definition.height * 0.50")},
"secondCorner" : ${fsPoint("-definition.width * 0.02", "-definition.height * 0.42")}
});
skRectangle(sketch1, "rightFoot", {
"firstCorner" : ${fsPoint("definition.width * 0.02", "-definition.height * 0.50")},
"secondCorner" : ${fsPoint("definition.width * 0.28", "-definition.height * 0.42")}
});
skSolve(sketch1);
opExtrude(context, id + "extrudeBlocks", {
"entities" : qSketchRegion(id + "sketch1"),
"direction" : skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.depth
});${d.filletRadiusInches > 0 ? `
opFillet(context, id + "filletBlocks", {
"entities" : qEdgeTopologyFilter(qOwnedByBody(qCreatedBy(id + "extrudeBlocks", EntityType.BODY), EntityType.EDGE), EdgeTopology.TWO_SIDED),
"radius" : definition.fillet
});` : ""}`,
};
}
function tBox(d) {
return {
precondition: [
preconditionPlane(),
preconditionLength("width", "Width", 0.01, d.widthInches, 48),
preconditionLength("height", "Height", 0.01, d.heightInches, 48),
preconditionLength("depth", "Depth", 0.01, d.depthInches, 48),
d.filletRadiusInches > 0
? preconditionLength("fillet", "Fillet Radius", 0, d.filletRadiusInches, 4)
: "",
].filter(Boolean).join("\n"),
body: `${planeVar()}
var sketch1 = newSketchOnPlane(context, id + "sketch1", { "sketchPlane" : skPlane });
skRectangle(sketch1, "rect1", {
"firstCorner" : vector(-definition.width / (2 * inch), -definition.height / (2 * inch)) * inch,
"secondCorner" : vector( definition.width / (2 * inch), definition.height / (2 * inch)) * inch
});
skSolve(sketch1);
opExtrude(context, id + "extrude1", {
"entities" : qSketchRegion(id + "sketch1"),
"direction" : skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.depth
});${d.filletRadiusInches > 0 ? `
opFillet(context, id + "fillet1", {
"entities" : qEdgeTopologyFilter(qOwnedByBody(qCreatedBy(id + "extrude1", EntityType.BODY), EntityType.EDGE), EdgeTopology.TWO_SIDED),
"radius" : definition.fillet
});` : ""}`,
};
}
function tCylinder(d) {
const boreDefault = d.holeRadiusInches > 0
? Math.min(d.holeRadiusInches, Math.max(0.01, d.radiusInches * 0.45))
: 0;
const blindTopHole = d.topHoleMode === "blind_top";
const holeDepthDefault = Math.max(0.05, Math.min(d.holeDepthInches || d.depthInches * 0.6 || 0.5, d.depthInches || 1));
return {
precondition: [
preconditionPlane(),
preconditionLength("radius", "Radius", 0.01, d.radiusInches, 24),
preconditionLength("height", "Height", 0.01, d.depthInches, 48),
preconditionLength("holeRadius", "Hole Radius", 0, Math.max(0, boreDefault), 24),
blindTopHole
? preconditionLength("holeDepth", "Top Hole Depth", 0.01, holeDepthDefault, Math.max(1, d.depthInches || 1))
: "",
].join("\n"),
body: `${planeVar()}
var hasBore = definition.holeRadius > 0 * inch && definition.holeRadius < definition.radius;
var sketch1 = newSketchOnPlane(context, id + "sketch1", { "sketchPlane" : skPlane });
skCircle(sketch1, "outer", { "center" : vector(0, 0) * inch, "radius" : definition.radius });
if (hasBore && ${blindTopHole ? "false" : "true"})
{
skCircle(sketch1, "inner", { "center" : vector(0, 0) * inch, "radius" : definition.holeRadius });
}
skSolve(sketch1);
var cylEntities = hasBore && ${blindTopHole ? "false" : "true"} ? qSketchRegion(id + "sketch1", true) : qSketchRegion(id + "sketch1");
opExtrude(context, id + "extrude1", {
"entities" : cylEntities,
"direction" : skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.height
});${blindTopHole ? `
if (hasBore)
{
var topHolePlane = plane(skPlane.origin + skPlane.normal * definition.height, skPlane.normal, skPlane.x);
var holeSketch = newSketchOnPlane(context, id + "holeSketch", { "sketchPlane" : topHolePlane });
skCircle(holeSketch, "topHole", { "center" : vector(0, 0) * inch, "radius" : definition.holeRadius });
skSolve(holeSketch);
opExtrude(context, id + "topHoleCut", {
"entities" : qSketchRegion(id + "holeSketch"),
"direction" : -skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.holeDepth,
"operationType" : NewBodyOperationType.REMOVE
});
}` : ""}`,
};
}
function tPolygon(d) {
const sides = Math.max(3, Math.round(d.sides || 6));
return {
precondition: [
preconditionPlane(),
preconditionLength("circumradius", "Circumradius", 0.01, d.radiusInches, 24),
preconditionLength("depth", "Depth", 0.01, d.depthInches, 48),
].join("\n"),
body: `${planeVar()}
var sketch1 = newSketchOnPlane(context, id + "sketch1", { "sketchPlane" : skPlane });
skRegularPolygon(sketch1, "poly1", {
"center" : vector(0, 0) * inch,
"firstVertex" : vector(1, 0) * definition.circumradius,
"sides" : ${sides}
});
skSolve(sketch1);
opExtrude(context, id + "extrude1", {
"entities" : qSketchRegion(id + "sketch1"),
"direction" : skPlane.normal,
"endBound" : BoundingType.BLIND,
"endDepth" : definition.depth
});`,
};
}
function tLinkage(d) {
const holeR = d.holeRadiusInches > 0 ? d.holeRadiusInches : d.widthInches * 0.18;
return {
precondition: [
preconditionPlane(),
preconditionLength("length", "Total Length", 0.1, d.shaftLengthInches || d.widthInches * 3, 48),
preconditionLength("width", "Bar Width", 0.05, d.widthInches, 12),
preconditionLength("thickness", "Thickness", 0.01, d.depthInches, 4),
preconditionLength("holeRadius","Pin Hole Radius", 0.01, holeR, 4),
].join("\n"),
body: `${planeVar()}
var holeOffset = definition.length * 0.5 - definition.holeRadius * 2.5;
var sketch1 = newSketchOnPlane(context, id + "sketch1", { "sketchPlane" : skPlane });
skRectangle(sketch1, "body", {
"firstCorner" : vector(-definition.length / (2 * inch), -definition.width / (2 * inch)) * inch,
"secondCorner" : vector( definition.length / (2 * inch), definition.width / (2 * inch)) * inch
});