forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-tool-surfaces.mjs
More file actions
717 lines (632 loc) · 22.1 KB
/
Copy pathgenerate-tool-surfaces.mjs
File metadata and controls
717 lines (632 loc) · 22.1 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
#!/usr/bin/env node
/**
* Generate Swift tool surfaces and test fixtures from omi-tool-manifest.ts.
* Run: node --experimental-strip-types scripts/generate-tool-surfaces.mjs [--check]
*/
import { createHash, randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import {
OMI_TOOL_MANIFEST_DIGEST,
OMI_CHAT_FIRST_TOOL_MANIFEST_DIGEST,
OMI_TOOL_MANIFEST_VERSION,
allOmiToolManifest,
omiToolManifest,
} from "../dist/runtime/omi-tool-manifest.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_DIR = join(__dirname, "..");
const MACOS_DIR = join(AGENT_DIR, "..");
const GENERATED_DIR = join(MACOS_DIR, "Desktop", "Sources", "Generated");
const FIXTURE_PATH = join(AGENT_DIR, "tests", "fixtures", "tool-manifest.json");
const VALID_SURFACES = new Set(["desktop_chat", "realtime_voice", "onboarding", "task_chat"]);
const PROVIDER_TOP_LEVEL_COMPOSITE_SCHEMA_KEYS = ["anyOf", "oneOf", "allOf"];
const CHECK_MODE = process.argv.includes("--check");
const OUTPUTS = [
join(GENERATED_DIR, "GeneratedToolCapabilities.swift"),
join(GENERATED_DIR, "GeneratedRealtimeTools.swift"),
join(GENERATED_DIR, "GeneratedToolExecutors.swift"),
join(GENERATED_DIR, "OmiToolManifest.generated.swift"),
FIXTURE_PATH,
];
function swiftEscape(value) {
return value
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\r/g, "")
.replace(/\n/g, "\\n");
}
function swiftStringArray(values) {
if (values.length === 0) return "[]";
return `[\n${values.map((v) => ` ${JSON.stringify(v)}`).join(",\n")}\n ]`;
}
function latencyEnum(latency) {
switch (latency) {
case "fast local":
return ".fastLocal";
case "fast network":
return ".fastNetwork";
case "async background":
return ".asyncBackground";
default:
throw new Error(`Unknown latency: ${latency}`);
}
}
function surfaceEnum(surface) {
switch (surface) {
case "desktop_chat":
return ".desktopChat";
case "realtime_voice":
return ".realtimeHub";
case "onboarding":
return ".onboarding";
case "task_chat":
return ".taskChat";
default:
throw new Error(`Unknown surface: ${surface}`);
}
}
function surfaceSet(surfaces) {
const unique = [...new Set(surfaces)];
return `Set([${unique.map(surfaceEnum).join(", ")}])`;
}
function assertFlatProviderInputSchema(schema, label) {
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
throw new Error(`${label} provider input schema must be an object`);
}
if (schema.type !== "object") {
throw new Error(`${label} provider input schema must have top-level type=object`);
}
if (!schema.properties || typeof schema.properties !== "object" || Array.isArray(schema.properties)) {
throw new Error(`${label} provider input schema must have top-level properties`);
}
for (const key of PROVIDER_TOP_LEVEL_COMPOSITE_SCHEMA_KEYS) {
if (Object.prototype.hasOwnProperty.call(schema, key)) {
throw new Error(`${label} provider input schema must not use top-level ${key}`);
}
}
}
function validateManifest() {
const names = new Set();
const aliases = new Map();
for (const tool of allOmiToolManifest) {
if (tool.intendedForAgents !== false && !tool.surfaces?.length) {
throw new Error(`Tool ${tool.name} is missing surfaces`);
}
if (!tool.capabilityDoc?.title) {
throw new Error(`Tool ${tool.name} is missing capabilityDoc`);
}
for (const surface of tool.surfaces) {
if (!VALID_SURFACES.has(surface)) {
throw new Error(`Tool ${tool.name} references unknown surface ${surface}`);
}
}
if (!tool.executor?.kind) {
throw new Error(`Tool ${tool.name} is missing executor.kind`);
}
assertFlatProviderInputSchema(tool.inputSchema, `${tool.name} manifest`);
if (tool.mcpInputSchema) {
assertFlatProviderInputSchema(tool.mcpInputSchema, `${tool.name} MCP`);
}
if (tool.executor.kind === "swiftTool" && !tool.executor.executorName) {
tool.executor.executorName = "chatToolExecutor";
}
if (names.has(tool.name)) {
throw new Error(`Duplicate tool name: ${tool.name}`);
}
names.add(tool.name);
const registerAlias = (alias) => {
if (aliases.has(alias)) {
throw new Error(`Duplicate alias ${alias} on ${tool.name} and ${aliases.get(alias)}`);
}
aliases.set(alias, tool.name);
};
for (const alias of tool.aliases ?? []) {
registerAlias(alias);
}
for (const alias of Object.keys(tool.aliasCapabilityDocs ?? {})) {
if (!(tool.aliases ?? []).includes(alias)) {
registerAlias(alias);
}
}
}
}
function collectCapabilities() {
const capabilities = [];
const pushCapability = (toolName, tool, doc, surfaces, { mergeGuidelines = false } = {}) => {
// Canonical entries fold promptGuidelines into the capability bullets so
// the manifest stays the single declaration site (guidelines are never
// hand-mirrored into capabilityDoc; ChatDiscoverabilityTests enforces the
// superset). Aliases keep their own doc verbatim.
const bullets = [...doc.bullets];
if (mergeGuidelines) {
for (const guideline of tool.promptGuidelines ?? []) {
if (!bullets.includes(guideline)) bullets.push(guideline);
}
}
capabilities.push({
toolName,
title: doc.title,
latency: tool.latency,
surfaces,
summary: doc.summary,
bullets,
});
};
for (const tool of omiToolManifest) {
pushCapability(tool.name, tool, tool.capabilityDoc, tool.surfaces, { mergeGuidelines: true });
for (const [alias, doc] of Object.entries(tool.aliasCapabilityDocs ?? {})) {
const aliasSurfaces = doc.surfaces ?? tool.surfaces;
pushCapability(alias, tool, doc, aliasSurfaces);
}
}
return capabilities;
}
function realtimeToolName(tool) {
const aliasDocs = tool.aliasCapabilityDocs ?? {};
for (const [alias, doc] of Object.entries(aliasDocs)) {
const aliasSurfaces = doc.surfaces ?? tool.surfaces;
if (aliasSurfaces.includes("realtime_voice")) {
return alias;
}
}
return tool.name;
}
function realtimeTools() {
const REALTIME_CONTROL_TOOLS = new Set([
"list_agent_sessions",
"get_agent_run",
"cancel_agent_run",
"inspect_agent_artifacts",
"read_tool_output",
"search_tool_output",
"update_agent_artifact_lifecycle",
"spawn_agent",
"set_desktop_attention_override",
]);
const hasRealtimeVoiceSurface = (tool) => {
if (tool.surfaces.includes("realtime_voice")) return true;
for (const doc of Object.values(tool.aliasCapabilityDocs ?? {})) {
const aliasSurfaces = doc.surfaces ?? tool.surfaces;
if (aliasSurfaces.includes("realtime_voice")) return true;
}
return false;
};
const shouldExpose = (tool) => {
if (tool.voice?.realtimeExpose === false) return false;
if (tool.voice?.realtimeExpose === true) return true;
if (tool.executor.kind === "runtimeControl") {
return REALTIME_CONTROL_TOOLS.has(tool.name) && hasRealtimeVoiceSurface(tool);
}
return hasRealtimeVoiceSurface(tool);
};
const entries = [];
const seen = new Set();
const push = (exposedName, tool) => {
if (seen.has(exposedName)) return;
seen.add(exposedName);
entries.push({ exposedName, tool });
};
for (const tool of omiToolManifest) {
if (shouldExpose(tool)) {
push(realtimeToolName(tool), tool);
}
for (const [alias, doc] of Object.entries(tool.aliasCapabilityDocs ?? {})) {
const aliasSurfaces = doc.surfaces ?? tool.surfaces;
if (!aliasSurfaces.includes("realtime_voice")) continue;
if (!shouldExpose(tool)) continue;
push(alias, tool);
}
}
const truncatableRealtimeTools = omiToolManifest.filter(
(tool) => shouldExpose(tool) && tool.resultContract?.budgets?.realtime_voice,
);
if (truncatableRealtimeTools.length > 0) {
for (const drillIn of ["read_tool_output", "search_tool_output"]) {
if (!entries.some((entry) => entry.exposedName === drillIn)) {
throw new Error(`Realtime exposes truncatable tools but is missing ${drillIn}`);
}
}
}
return entries;
}
function schemaForRealtime(tool) {
return tool.voice?.schemaOverride ?? tool.inputSchema;
}
function descriptionForRealtime(tool) {
return tool.voice?.realtimeDescription ?? tool.description;
}
// Gemini Live functionDeclaration.parameters uses OpenAPI 3.0 Schema, not full JSON Schema.
// Strip keys that make setup fail (e.g. additionalProperties) before embedding in realtime tools.
const GEMINI_UNSUPPORTED_REALTIME_SCHEMA_KEYS = new Set([
"additionalProperties",
"$schema",
"default",
"title",
"pattern",
"const",
]);
function sanitizeRealtimeVoiceSchema(schema) {
if (schema === null || typeof schema !== "object" || Array.isArray(schema)) {
return schema;
}
const out = {};
for (const [key, value] of Object.entries(schema)) {
if (GEMINI_UNSUPPORTED_REALTIME_SCHEMA_KEYS.has(key)) continue;
if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
const props = {};
for (const [propKey, propValue] of Object.entries(value)) {
props[propKey] = sanitizeRealtimeVoiceSchema(propValue);
}
out[key] = props;
continue;
}
if (key === "items" && value && typeof value === "object") {
out[key] = sanitizeRealtimeVoiceSchema(value);
continue;
}
if (Array.isArray(value)) {
out[key] = value.map((item) =>
item && typeof item === "object" ? sanitizeRealtimeVoiceSchema(item) : item,
);
continue;
}
if (value && typeof value === "object") {
out[key] = sanitizeRealtimeVoiceSchema(value);
continue;
}
out[key] = value;
}
return out;
}
function openAIToolDefinition({ exposedName, tool }, { includeSpawnProvider = false, directedProviders = [] } = {}) {
const schema = schemaForRealtime(tool);
const description = descriptionForRealtime(tool);
if (tool.name === "spawn_agent" && includeSpawnProvider) {
const properties = {
brief: {
type: "string",
description:
"The user's raw delegation intent or proposed task. Include concrete details you know; Omi's resolver will rewrite it before any child agent sees it.",
},
title: {
type: "string",
description:
"A short Title Case label for the task pill (≤ ~5 words, no trailing punctuation), e.g. 'Draft Launch Email'.",
},
};
if (directedProviders.length > 0) {
properties.provider = {
type: "string",
enum: directedProviders,
description:
"Optional local provider only when the current user explicitly names it; omit for a regular Omi agent.",
};
}
return {
type: "function",
name: exposedName,
description,
parameters: {
type: "object",
properties,
required: ["brief"],
},
};
}
const parameters = sanitizeRealtimeVoiceSchema({ ...schema });
return {
type: "function",
name: exposedName,
description,
parameters,
};
}
function generateCapabilitiesSwift(capabilities, realtimeExposedNames) {
const entries = capabilities
.map((cap) => {
const bullets = swiftStringArray(cap.bullets);
return ` Capability(
toolName: ${JSON.stringify(cap.toolName)},
title: ${JSON.stringify(cap.title)},
latency: ${latencyEnum(cap.latency)},
surfaces: ${surfaceSet(cap.surfaces)},
summary: ${JSON.stringify(cap.summary)},
bullets: ${bullets}
)`;
})
.join(",\n");
return `// Generated by agent/scripts/generate-tool-surfaces.mjs — do not edit.
import Foundation
enum GeneratedToolCapabilities {
enum Surface: Hashable {
case desktopChat
case realtimeHub
case onboarding
case taskChat
}
enum LatencyClass: String {
case fastLocal = "fast local"
case fastNetwork = "fast network"
case asyncBackground = "async background"
}
struct Capability {
let toolName: String
let title: String
let latency: LatencyClass
let surfaces: Set<Surface>
let summary: String
let bullets: [String]
func supports(_ surface: Surface) -> Bool {
surfaces.contains(surface)
}
}
static let capabilities: [Capability] = [
${entries}
]
static func capabilities(for surface: Surface) -> [Capability] {
capabilities.filter { $0.supports(surface) }
}
static var desktopToolNames: [String] {
capabilities(for: .desktopChat).map(\\.toolName)
}
static var realtimeToolNames: [String] {
${JSON.stringify(realtimeExposedNames)}
}
}
`;
}
function generateRealtimeToolsSwift(realtimeEntries) {
const baseTools = realtimeEntries.map((entry) => openAIToolDefinition(entry));
for (const tool of baseTools) {
assertFlatProviderInputSchema(tool.parameters, `${tool.name} realtime`);
}
// Double backslashes so Swift multiline strings preserve JSON escapes (e.g. \n).
const json = JSON.stringify(baseTools, null, 2).replace(/\\/g, "\\\\");
const hubCases = realtimeEntries
.map(({ exposedName }) => {
const caseName = exposedName
.replace(/_([a-z])/g, (_, c) => c.toUpperCase())
.replace(/_([0-9])/g, (_, d) => d);
const swiftCase = caseName.charAt(0).toLowerCase() + caseName.slice(1);
return ` case ${swiftCase} = "${exposedName}"`;
})
.join("\n");
return `// Generated by agent/scripts/generate-tool-surfaces.mjs — do not edit.
import Foundation
enum HubTool: String {
${hubCases}
}
enum GeneratedRealtimeTools {
private static let baseOpenAIToolsTemplateJSON = """
${json}
"""
static var baseOpenAIToolsTemplate: [[String: Any]] {
guard let data = baseOpenAIToolsTemplateJSON.data(using: .utf8),
let tools = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]
else {
fatalError("Invalid generated realtime tools JSON")
}
return tools
}
static func baseOpenAITools(providerProperty: [String: Any]?) -> [[String: Any]] {
var tools = baseOpenAIToolsTemplate
guard let index = tools.firstIndex(where: { ($0["name"] as? String) == "spawn_agent" }) else {
return tools
}
guard var parameters = tools[index]["parameters"] as? [String: Any],
var properties = parameters["properties"] as? [String: Any] else {
return tools
}
if let providerProperty {
properties["provider"] = providerProperty
} else {
properties.removeValue(forKey: "provider")
}
parameters["properties"] = properties
tools[index]["parameters"] = parameters
return tools
}
}
`;
}
function swiftExecutorEnum(name) {
switch (name) {
case "chatToolExecutor":
return ".chatToolExecutor";
case "realtimeHub":
return ".realtimeHub";
default:
throw new Error(`Unknown swift executor: ${name}`);
}
}
function swiftToolCaseName(name) {
const camel = name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
return camel;
}
function generateExecutorsSwift() {
const swiftTools = allOmiToolManifest.filter((tool) => tool.executor.kind === "swiftTool");
const enumCases = swiftTools
.map((tool) => ` case ${swiftToolCaseName(tool.name)} = "${tool.name}"`)
.join("\n");
const aliasMapEntries = [];
const aliasKeys = new Set();
for (const tool of swiftTools) {
for (const alias of [...(tool.aliases ?? []), ...Object.keys(tool.aliasCapabilityDocs ?? {})]) {
if (aliasKeys.has(alias)) continue;
aliasKeys.add(alias);
aliasMapEntries.push(` "${alias}": .${swiftToolCaseName(tool.name)}`);
}
}
const executorEntries = swiftTools
.map(
(tool) =>
` .${swiftToolCaseName(tool.name)}: ${swiftExecutorEnum(tool.executor.executorName ?? "chatToolExecutor")}`,
)
.join(",\n");
const chatToolCases = swiftTools
.filter((tool) => (tool.executor.executorName ?? "chatToolExecutor") === "chatToolExecutor")
.map((tool) => ` case ${swiftToolCaseName(tool.name)}`)
.join("\n");
return `// Generated by agent/scripts/generate-tool-surfaces.mjs — do not edit.
import Foundation
enum GeneratedSwiftTool: String, CaseIterable {
${enumCases}
}
enum GeneratedSwiftToolExecutor: String {
case chatToolExecutor
case realtimeHub
}
enum GeneratedToolExecutors {
static let manifestVersion = ${OMI_TOOL_MANIFEST_VERSION}
static let manifestDigest = ${JSON.stringify(OMI_TOOL_MANIFEST_DIGEST)}
static let chatFirstManifestDigest = ${JSON.stringify(OMI_CHAT_FIRST_TOOL_MANIFEST_DIGEST)}
static let aliasToCanonical: [String: GeneratedSwiftTool] = [
${aliasMapEntries.join(",\n")}
]
static let executorByTool: [GeneratedSwiftTool: GeneratedSwiftToolExecutor] = [
${executorEntries}
]
static func resolve(_ name: String) -> GeneratedSwiftTool? {
if let direct = GeneratedSwiftTool(rawValue: name) {
return direct
}
return aliasToCanonical[name]
}
static func isChatToolExecutorTool(_ name: String) -> Bool {
guard let tool = resolve(name) else { return false }
return executorByTool[tool] == .chatToolExecutor
}
static var chatToolExecutorToolNames: Set<String> {
Set(
executorByTool.compactMap { tool, executor in
executor == .chatToolExecutor ? tool.rawValue : nil
}
+ aliasToCanonical.compactMap { alias, tool in
executorByTool[tool] == .chatToolExecutor ? alias : nil
}
)
}
static var realtimeHubToolNames: Set<String> {
Set(GeneratedToolCapabilities.realtimeToolNames)
}
/// Dispatch surface for ChatToolExecutor — chatToolExecutor-bound tools only.
enum ChatDispatch {
${chatToolCases}
case unhandled
}
static func chatDispatch(for name: String) -> ChatDispatch {
guard let tool = resolve(name), executorByTool[tool] == .chatToolExecutor else {
return .unhandled
}
switch tool {
${swiftTools
.filter((tool) => (tool.executor.executorName ?? "chatToolExecutor") === "chatToolExecutor")
.map((tool) => ` case .${swiftToolCaseName(tool.name)}: return .${swiftToolCaseName(tool.name)}`)
.join("\n")}
default: return .unhandled
}
}
}
`;
}
function schemaPropertyToSwift(name, schema) {
const lines = [`"${name}": [`];
if (schema.type) lines.push(` "type": "${schema.type}",`);
if (schema.description) lines.push(` "description": ${JSON.stringify(schema.description)},`);
if (schema.enum) lines.push(` "enum": ${JSON.stringify(schema.enum)},`);
if (schema.items) {
lines.push(` "items": [`);
if (schema.items.type) lines.push(` "type": "${schema.items.type}",`);
if (schema.items.description) lines.push(` "description": ${JSON.stringify(schema.items.description)},`);
lines.push(` ],`);
}
lines.push(`]`);
return lines.join("\n ");
}
function generateLocalApiSwift() {
const localTools = omiToolManifest.filter((tool) => tool.adapters["local-agent-api"]?.advertised === true);
const entries = localTools
.map((tool) => {
const properties = Object.entries(tool.inputSchema.properties ?? {});
const propertiesSwift =
properties.length === 0
? "[:]"
: `[\n ${properties.map(([name, schema]) => schemaPropertyToSwift(name, schema)).join(",\n ")}\n ]`;
const required = swiftStringArray(tool.inputSchema.required ?? []);
const annotations = [
`"readOnlyHint": ${tool.annotations.readOnlyHint ?? false}`,
`"destructiveHint": ${tool.annotations.destructiveHint ?? false}`,
`"openWorldHint": ${tool.annotations.openWorldHint ?? false}`,
].join(", ");
return ` LocalAgentTool(
name: ${JSON.stringify(tool.name)},
description: ${JSON.stringify(tool.description)},
properties: ${propertiesSwift},
required: ${required},
annotations: [${annotations}]
)`;
})
.join(",\n");
return `// Generated by agent/scripts/generate-tool-surfaces.mjs — do not edit.
import Foundation
enum OmiToolManifest {
static let localAgentAPITools: [LocalAgentTool] = [
${entries}
]
}
`;
}
function generateFixture() {
return `${JSON.stringify(omiToolManifest, null, 2)}\n`;
}
function writeAtomically(path, content) {
const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
writeFileSync(temporaryPath, content, { encoding: "utf8", flag: "wx" });
renameSync(temporaryPath, path);
} catch (error) {
try {
unlinkSync(temporaryPath);
} catch {
// The temporary file either was never created or was already renamed.
}
throw error;
}
}
function writeOrCheck(path, content) {
if (CHECK_MODE) {
const existing = readFileSync(path, "utf8");
if (existing !== content) {
throw new Error(`Generated output drift: ${path}`);
}
return false;
}
if (existsSync(path) && readFileSync(path, "utf8") === content) return false;
writeAtomically(path, content);
return true;
}
function main() {
validateManifest();
const capabilities = collectCapabilities();
const realtimeEntries = realtimeTools();
const realtimeExposedNames = realtimeEntries.map((entry) => entry.exposedName).sort();
mkdirSync(GENERATED_DIR, { recursive: true });
mkdirSync(dirname(FIXTURE_PATH), { recursive: true });
const files = {
[join(GENERATED_DIR, "GeneratedToolCapabilities.swift")]: generateCapabilitiesSwift(capabilities, realtimeExposedNames),
[join(GENERATED_DIR, "GeneratedRealtimeTools.swift")]: generateRealtimeToolsSwift(realtimeEntries),
[join(GENERATED_DIR, "GeneratedToolExecutors.swift")]: generateExecutorsSwift(),
[join(GENERATED_DIR, "OmiToolManifest.generated.swift")]: generateLocalApiSwift(),
[FIXTURE_PATH]: generateFixture(),
};
const changedOutputCount = Object.entries(files).filter(([path, content]) => writeOrCheck(path, content)).length;
if (CHECK_MODE) {
console.log("generate-tool-surfaces: all outputs match (--check)");
} else {
const hash = createHash("sha256").update(JSON.stringify(omiToolManifest)).digest("hex").slice(0, 12);
const outcome = changedOutputCount === 0 ? "outputs already current" : `wrote ${changedOutputCount} file(s)`;
console.log(`generate-tool-surfaces: ${outcome} (manifest ${hash})`);
}
}
main();