@hop-top/kit 0.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,187 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import * as path from "path";
3
+ import {
4
+ loadToolSpec,
5
+ validateToolSpec,
6
+ type ToolSpec,
7
+ type Command,
8
+ } from "./toolspec";
9
+
10
+ const EXAMPLE_PATH = path.resolve(
11
+ __dirname,
12
+ "../../../examples/spaced/spaced.toolspec.yaml",
13
+ );
14
+
15
+ describe("loadToolSpec", () => {
16
+ it("parses the spaced example without errors", () => {
17
+ const spec = loadToolSpec(EXAMPLE_PATH);
18
+ expect(spec.name).toBe("spaced");
19
+ expect(spec.schemaVersion).toBe("1");
20
+ });
21
+
22
+ it("loads stateIntrospection", () => {
23
+ const spec = loadToolSpec(EXAMPLE_PATH);
24
+ expect(spec.stateIntrospection).toBeDefined();
25
+ expect(spec.stateIntrospection!.configCommands).toEqual([
26
+ "spaced config show",
27
+ ]);
28
+ expect(spec.stateIntrospection!.envVars).toEqual([
29
+ "SPACED_FORMAT",
30
+ "SPACED_LOG_LEVEL",
31
+ "SPACED_LOG_FORMAT",
32
+ ]);
33
+ });
34
+
35
+ it("loads commands with nested children", () => {
36
+ const spec = loadToolSpec(EXAMPLE_PATH);
37
+ expect(spec.commands.length).toBeGreaterThanOrEqual(3);
38
+
39
+ const launch = spec.commands.find((c) => c.name === "launch");
40
+ expect(launch).toBeDefined();
41
+ expect(launch!.intent?.domain).toBe("space");
42
+ expect(launch!.intent?.category).toBe("operations");
43
+ expect(launch!.intent?.tags).toEqual(["mission", "launch"]);
44
+ });
45
+
46
+ it("loads contract fields", () => {
47
+ const spec = loadToolSpec(EXAMPLE_PATH);
48
+ const launch = spec.commands.find((c) => c.name === "launch")!;
49
+ expect(launch.contract).toBeDefined();
50
+ expect(launch.contract!.idempotent).toBe(false);
51
+ expect(launch.contract!.retryable).toBe(false);
52
+ expect(launch.contract!.sideEffects).toHaveLength(2);
53
+ });
54
+
55
+ it("loads safety fields", () => {
56
+ const spec = loadToolSpec(EXAMPLE_PATH);
57
+ const launch = spec.commands.find((c) => c.name === "launch")!;
58
+ expect(launch.safety).toBeDefined();
59
+ expect(launch.safety!.level).toBe("dangerous");
60
+ expect(launch.safety!.requiresConfirmation).toBe(false);
61
+ });
62
+
63
+ it("loads previewModes", () => {
64
+ const spec = loadToolSpec(EXAMPLE_PATH);
65
+ const launch = spec.commands.find((c) => c.name === "launch")!;
66
+ expect(launch.previewModes).toEqual(["--dry-run"]);
67
+ });
68
+
69
+ it("loads outputSchema", () => {
70
+ const spec = loadToolSpec(EXAMPLE_PATH);
71
+ const launch = spec.commands.find((c) => c.name === "launch")!;
72
+ expect(launch.outputSchema).toBeDefined();
73
+ expect(launch.outputSchema!.format).toBe("text");
74
+ expect(launch.outputSchema!.fields).toContain("mission");
75
+ });
76
+
77
+ it("loads flags on commands", () => {
78
+ const spec = loadToolSpec(EXAMPLE_PATH);
79
+ const launch = spec.commands.find((c) => c.name === "launch")!;
80
+ expect(launch.flags).toBeDefined();
81
+ expect(launch.flags!.length).toBeGreaterThan(0);
82
+ const payload = launch.flags!.find((f) => f.name === "--payload");
83
+ expect(payload).toBeDefined();
84
+ expect(payload!.type).toBe("string[]");
85
+ });
86
+
87
+ it("loads suggestedNext", () => {
88
+ const spec = loadToolSpec(EXAMPLE_PATH);
89
+ const launch = spec.commands.find((c) => c.name === "launch")!;
90
+ expect(launch.suggestedNext).toEqual(["mission list", "telemetry"]);
91
+ });
92
+
93
+ it("loads nested children (mission.list)", () => {
94
+ const spec = loadToolSpec(EXAMPLE_PATH);
95
+ const mission = spec.commands.find((c) => c.name === "mission");
96
+ expect(mission).toBeDefined();
97
+ expect(mission!.children).toBeDefined();
98
+ expect(mission!.children!.length).toBeGreaterThanOrEqual(1);
99
+ const list = mission!.children!.find((c) => c.name === "list");
100
+ expect(list).toBeDefined();
101
+ expect(list!.contract?.idempotent).toBe(true);
102
+ expect(list!.safety?.level).toBe("safe");
103
+ });
104
+ });
105
+
106
+ describe("validateToolSpec", () => {
107
+ it("returns no errors for valid spaced example", () => {
108
+ const spec = loadToolSpec(EXAMPLE_PATH);
109
+ const errors = validateToolSpec(spec);
110
+ expect(errors).toEqual([]);
111
+ });
112
+
113
+ it("returns error when name is missing", () => {
114
+ const spec: ToolSpec = { name: "", schemaVersion: "1", commands: [] };
115
+ const errors = validateToolSpec(spec);
116
+ expect(errors).toContain("name is required");
117
+ });
118
+
119
+ it("returns error when schemaVersion is missing", () => {
120
+ const spec: ToolSpec = { name: "test", schemaVersion: "", commands: [] };
121
+ const errors = validateToolSpec(spec);
122
+ expect(errors).toContain("schemaVersion is required");
123
+ });
124
+
125
+ it("returns error when commands is empty", () => {
126
+ const spec: ToolSpec = { name: "test", schemaVersion: "1", commands: [] };
127
+ const errors = validateToolSpec(spec);
128
+ expect(errors).toContain("at least one command is required");
129
+ });
130
+
131
+ it("returns error when command name is missing", () => {
132
+ const spec: ToolSpec = {
133
+ name: "test",
134
+ schemaVersion: "1",
135
+ commands: [{ name: "" }],
136
+ };
137
+ const errors = validateToolSpec(spec);
138
+ expect(errors.some((e) => e.includes("command name"))).toBe(true);
139
+ });
140
+
141
+ it("returns error for invalid safety level", () => {
142
+ const spec: ToolSpec = {
143
+ name: "test",
144
+ schemaVersion: "1",
145
+ commands: [
146
+ {
147
+ name: "foo",
148
+ safety: { level: "yolo" as any, requiresConfirmation: false },
149
+ },
150
+ ],
151
+ };
152
+ const errors = validateToolSpec(spec);
153
+ expect(errors.some((e) => e.includes("safety level"))).toBe(true);
154
+ });
155
+ });
156
+
157
+ describe("findCommand", () => {
158
+ it("finds top-level command", () => {
159
+ const spec = loadToolSpec(EXAMPLE_PATH);
160
+ const launch = findCmd(spec, "launch");
161
+ expect(launch).toBeDefined();
162
+ expect(launch!.name).toBe("launch");
163
+ });
164
+
165
+ it("finds nested command", () => {
166
+ const spec = loadToolSpec(EXAMPLE_PATH);
167
+ const list = findCmd(spec, "list");
168
+ expect(list).toBeDefined();
169
+ expect(list!.name).toBe("list");
170
+ });
171
+
172
+ it("returns undefined for missing command", () => {
173
+ const spec = loadToolSpec(EXAMPLE_PATH);
174
+ expect(findCmd(spec, "nonexistent")).toBeUndefined();
175
+ });
176
+ });
177
+
178
+ // BFS findCommand mirroring Go's ToolSpec.FindCommand
179
+ function findCmd(spec: ToolSpec, name: string): Command | undefined {
180
+ const queue: Command[] = [...spec.commands];
181
+ while (queue.length > 0) {
182
+ const c = queue.shift()!;
183
+ if (c.name === name) return c;
184
+ if (c.children) queue.push(...c.children);
185
+ }
186
+ return undefined;
187
+ }
@@ -0,0 +1,279 @@
1
+ import * as fs from "fs";
2
+ import * as yaml from "js-yaml";
3
+
4
+ // --- Types ---
5
+
6
+ export type SafetyLevel = "safe" | "caution" | "dangerous";
7
+
8
+ export interface Contract {
9
+ idempotent: boolean;
10
+ sideEffects?: string[];
11
+ retryable: boolean;
12
+ preConditions?: string[];
13
+ }
14
+
15
+ export interface Safety {
16
+ level: SafetyLevel;
17
+ requiresConfirmation?: boolean;
18
+ permissions?: string[];
19
+ }
20
+
21
+ export interface OutputSchema {
22
+ format?: string;
23
+ fields?: string[];
24
+ example?: string;
25
+ }
26
+
27
+ export interface StateIntrospection {
28
+ configCommands?: string[];
29
+ envVars?: string[];
30
+ authCommands?: string[];
31
+ }
32
+
33
+ export interface Provenance {
34
+ source?: string;
35
+ retrievedAt?: string;
36
+ confidence?: number;
37
+ }
38
+
39
+ export interface Intent {
40
+ domain?: string;
41
+ category?: string;
42
+ tags?: string[];
43
+ }
44
+
45
+ export interface Flag {
46
+ name: string;
47
+ short?: string;
48
+ type?: string;
49
+ description?: string;
50
+ deprecated?: boolean;
51
+ replacedBy?: string;
52
+ }
53
+
54
+ export interface Command {
55
+ name: string;
56
+ aliases?: string[];
57
+ flags?: Flag[];
58
+ children?: Command[];
59
+ contract?: Contract;
60
+ safety?: Safety;
61
+ previewModes?: string[];
62
+ outputSchema?: OutputSchema;
63
+ deprecated?: boolean;
64
+ deprecatedSince?: string;
65
+ replacedBy?: string;
66
+ intent?: Intent;
67
+ suggestedNext?: string[];
68
+ }
69
+
70
+ export interface ErrorPattern {
71
+ pattern: string;
72
+ fix: string;
73
+ source?: string;
74
+ cause?: string;
75
+ fixes?: string[];
76
+ confidence?: number;
77
+ provenance?: Provenance;
78
+ }
79
+
80
+ export interface Workflow {
81
+ name: string;
82
+ steps: string[];
83
+ after?: Record<string, string[]>;
84
+ provenance?: Provenance;
85
+ }
86
+
87
+ export interface ToolSpec {
88
+ name: string;
89
+ schemaVersion: string;
90
+ commands: Command[];
91
+ flags?: Flag[];
92
+ errorPatterns?: ErrorPattern[];
93
+ workflows?: Workflow[];
94
+ stateIntrospection?: StateIntrospection;
95
+ }
96
+
97
+ // --- YAML mapping helpers ---
98
+
99
+ // snake_case YAML -> camelCase TS
100
+ function mapFlag(raw: any): Flag {
101
+ return {
102
+ name: raw.name ?? "",
103
+ short: raw.short,
104
+ type: raw.type,
105
+ description: raw.description,
106
+ deprecated: raw.deprecated,
107
+ replacedBy: raw.replaced_by,
108
+ };
109
+ }
110
+
111
+ function mapProvenance(raw: any): Provenance | undefined {
112
+ if (!raw) return undefined;
113
+ return {
114
+ source: raw.source,
115
+ retrievedAt: raw.retrieved_at,
116
+ confidence: raw.confidence,
117
+ };
118
+ }
119
+
120
+ function mapContract(raw: any): Contract | undefined {
121
+ if (!raw) return undefined;
122
+ return {
123
+ idempotent: raw.idempotent ?? false,
124
+ sideEffects: raw.side_effects,
125
+ retryable: raw.retryable ?? false,
126
+ preConditions: raw.pre_conditions,
127
+ };
128
+ }
129
+
130
+ function mapSafety(raw: any): Safety | undefined {
131
+ if (!raw) return undefined;
132
+ return {
133
+ level: raw.level,
134
+ requiresConfirmation: raw.requires_confirmation,
135
+ permissions: raw.permissions,
136
+ };
137
+ }
138
+
139
+ function mapOutputSchema(raw: any): OutputSchema | undefined {
140
+ if (!raw) return undefined;
141
+ return {
142
+ format: raw.format,
143
+ fields: raw.fields,
144
+ example: raw.example,
145
+ };
146
+ }
147
+
148
+ function mapIntent(raw: any): Intent | undefined {
149
+ if (!raw) return undefined;
150
+ return {
151
+ domain: raw.domain,
152
+ category: raw.category,
153
+ tags: raw.tags,
154
+ };
155
+ }
156
+
157
+ function mapCommand(raw: any): Command {
158
+ return {
159
+ name: raw.name ?? "",
160
+ aliases: raw.aliases,
161
+ flags: raw.flags?.map(mapFlag),
162
+ children: raw.children?.map(mapCommand),
163
+ contract: mapContract(raw.contract),
164
+ safety: mapSafety(raw.safety),
165
+ previewModes: raw.preview_modes,
166
+ outputSchema: mapOutputSchema(raw.output_schema),
167
+ deprecated: raw.deprecated,
168
+ deprecatedSince: raw.deprecated_since,
169
+ replacedBy: raw.replaced_by,
170
+ intent: mapIntent(raw.intent),
171
+ suggestedNext: raw.suggested_next,
172
+ };
173
+ }
174
+
175
+ function mapStateIntrospection(
176
+ raw: any,
177
+ ): StateIntrospection | undefined {
178
+ if (!raw) return undefined;
179
+ return {
180
+ configCommands: raw.config_commands,
181
+ envVars: raw.env_vars,
182
+ authCommands: raw.auth_commands,
183
+ };
184
+ }
185
+
186
+ function mapErrorPattern(raw: any): ErrorPattern {
187
+ return {
188
+ pattern: raw.pattern ?? "",
189
+ fix: raw.fix ?? "",
190
+ source: raw.source,
191
+ cause: raw.cause,
192
+ fixes: raw.fixes,
193
+ confidence: raw.confidence,
194
+ provenance: mapProvenance(raw.provenance),
195
+ };
196
+ }
197
+
198
+ function mapWorkflow(raw: any): Workflow {
199
+ return {
200
+ name: raw.name ?? "",
201
+ steps: raw.steps ?? [],
202
+ after: raw.after,
203
+ provenance: mapProvenance(raw.provenance),
204
+ };
205
+ }
206
+
207
+ // --- Public API ---
208
+
209
+ /** Parse a YAML toolspec file into a ToolSpec object. */
210
+ export function loadToolSpec(yamlPath: string): ToolSpec {
211
+ const content = fs.readFileSync(yamlPath, "utf-8");
212
+ const raw = yaml.load(content) as any;
213
+
214
+ return {
215
+ name: raw.name ?? "",
216
+ schemaVersion: raw.schema_version ?? "",
217
+ commands: (raw.commands ?? []).map(mapCommand),
218
+ flags: raw.flags?.map(mapFlag),
219
+ errorPatterns: raw.error_patterns?.map(mapErrorPattern),
220
+ workflows: raw.workflows?.map(mapWorkflow),
221
+ stateIntrospection: mapStateIntrospection(
222
+ raw.state_introspection,
223
+ ),
224
+ };
225
+ }
226
+
227
+ const VALID_SAFETY_LEVELS: Set<string> = new Set([
228
+ "safe",
229
+ "caution",
230
+ "dangerous",
231
+ ]);
232
+
233
+ /** Validate a ToolSpec, returning a list of error strings. */
234
+ export function validateToolSpec(spec: ToolSpec): string[] {
235
+ const errors: string[] = [];
236
+
237
+ if (!spec.name) errors.push("name is required");
238
+ if (!spec.schemaVersion) errors.push("schemaVersion is required");
239
+ if (!spec.commands || spec.commands.length === 0) {
240
+ errors.push("at least one command is required");
241
+ }
242
+
243
+ const validateCmd = (cmd: Command, path: string) => {
244
+ if (!cmd.name) {
245
+ errors.push(`${path}: command name is required`);
246
+ }
247
+ if (cmd.safety && !VALID_SAFETY_LEVELS.has(cmd.safety.level)) {
248
+ errors.push(
249
+ `${path}: invalid safety level "${cmd.safety.level}"` +
250
+ ` (must be safe|caution|dangerous)`,
251
+ );
252
+ }
253
+ if (cmd.children) {
254
+ for (const child of cmd.children) {
255
+ validateCmd(child, `${path}/${child.name || "<unnamed>"}`);
256
+ }
257
+ }
258
+ };
259
+
260
+ for (const cmd of spec.commands ?? []) {
261
+ validateCmd(cmd, cmd.name || "<unnamed>");
262
+ }
263
+
264
+ return errors;
265
+ }
266
+
267
+ /** BFS search for a command by name (mirrors Go FindCommand). */
268
+ export function findCommand(
269
+ spec: ToolSpec,
270
+ name: string,
271
+ ): Command | undefined {
272
+ const queue: Command[] = [...spec.commands];
273
+ while (queue.length > 0) {
274
+ const c = queue.shift()!;
275
+ if (c.name === name) return c;
276
+ if (c.children) queue.push(...c.children);
277
+ }
278
+ return undefined;
279
+ }
@@ -0,0 +1,205 @@
1
+ import { describe, it, expect, vi, afterEach } from "vitest";
2
+ import {
3
+ parseTritonURI,
4
+ TritonClient,
5
+ TritonError,
6
+ } from "./client";
7
+ import type { InferResponse } from "./client";
8
+
9
+ // ─── parseTritonURI ──────────────────────────────────────────────────────────
10
+
11
+ describe("parseTritonURI", () => {
12
+ it("parses host:port/model", () => {
13
+ const r = parseTritonURI("triton://localhost:8000/my_model");
14
+ expect(r.host).toBe("localhost");
15
+ expect(r.port).toBe(8000);
16
+ expect(r.modelName).toBe("my_model");
17
+ expect(r.modelVersion).toBeUndefined();
18
+ });
19
+
20
+ it("parses host:port/model/version", () => {
21
+ const r = parseTritonURI("triton://gpu:9000/bert/1");
22
+ expect(r.host).toBe("gpu");
23
+ expect(r.port).toBe(9000);
24
+ expect(r.modelName).toBe("bert");
25
+ expect(r.modelVersion).toBe("1");
26
+ });
27
+
28
+ it("throws on wrong scheme", () => {
29
+ expect(() => parseTritonURI("http://x:8000/m")).toThrow(TritonError);
30
+ });
31
+
32
+ it("throws on missing model", () => {
33
+ expect(() => parseTritonURI("triton://x:8000/")).toThrow(TritonError);
34
+ });
35
+
36
+ it("throws on missing port", () => {
37
+ expect(() => parseTritonURI("triton://host/model")).toThrow(TritonError);
38
+ });
39
+
40
+ it("throws on non-numeric port", () => {
41
+ expect(() => parseTritonURI("triton://host:abc/model")).toThrow(
42
+ TritonError,
43
+ );
44
+ });
45
+ });
46
+
47
+ // ─── TritonClient ────────────────────────────────────────────────────────────
48
+
49
+ describe("TritonClient", () => {
50
+ const originalFetch = globalThis.fetch;
51
+
52
+ afterEach(() => {
53
+ globalThis.fetch = originalFetch;
54
+ });
55
+
56
+ it("constructs from URI", () => {
57
+ const c = TritonClient.fromURI("triton://localhost:8000/mf_model");
58
+ expect(c.baseUrl).toBe("http://localhost:8000");
59
+ expect(c.modelName).toBe("mf_model");
60
+ });
61
+
62
+ it("infer sends correct request and parses response", async () => {
63
+ const mockResponse: InferResponse = {
64
+ model_name: "test",
65
+ outputs: [
66
+ {
67
+ name: "output",
68
+ shape: [1, 1],
69
+ datatype: "FP32",
70
+ data: [0.75],
71
+ },
72
+ ],
73
+ };
74
+
75
+ globalThis.fetch = vi.fn(async () => ({
76
+ ok: true,
77
+ json: async () => mockResponse,
78
+ text: async () => "",
79
+ })) as unknown as typeof fetch;
80
+
81
+ const client = new TritonClient("http://localhost:8000", "test");
82
+ const resp = await client.infer({
83
+ inputs: [
84
+ {
85
+ name: "input",
86
+ shape: [1, 4],
87
+ datatype: "FP32",
88
+ data: [1, 2, 3, 4],
89
+ },
90
+ ],
91
+ });
92
+
93
+ expect(resp.outputs[0].data[0]).toBe(0.75);
94
+ expect(globalThis.fetch).toHaveBeenCalledWith(
95
+ "http://localhost:8000/v2/models/test/infer",
96
+ expect.objectContaining({ method: "POST" }),
97
+ );
98
+ });
99
+
100
+ it("infer includes version in URL when set", async () => {
101
+ const mockResponse: InferResponse = {
102
+ model_name: "test",
103
+ outputs: [{ name: "o", shape: [1], datatype: "FP32", data: [0] }],
104
+ };
105
+
106
+ globalThis.fetch = vi.fn(async () => ({
107
+ ok: true,
108
+ json: async () => mockResponse,
109
+ text: async () => "",
110
+ })) as unknown as typeof fetch;
111
+
112
+ const client = new TritonClient("http://localhost:8000", "test", "2");
113
+ await client.infer({ inputs: [] });
114
+
115
+ const url = (globalThis.fetch as ReturnType<typeof vi.fn>).mock
116
+ .calls[0][0] as string;
117
+ expect(url).toContain("/versions/2/infer");
118
+ });
119
+
120
+ it("infer throws TritonError on HTTP error", async () => {
121
+ globalThis.fetch = vi.fn(async () => ({
122
+ ok: false,
123
+ status: 500,
124
+ text: async () => "internal error",
125
+ })) as unknown as typeof fetch;
126
+
127
+ const client = new TritonClient("http://localhost:8000", "test");
128
+ await expect(client.infer({ inputs: [] })).rejects.toThrow(TritonError);
129
+ });
130
+
131
+ it("score sends FP32 input and returns first output value", async () => {
132
+ const mockResponse: InferResponse = {
133
+ model_name: "mf",
134
+ outputs: [
135
+ {
136
+ name: "output",
137
+ shape: [1, 1],
138
+ datatype: "FP32",
139
+ data: [0.42],
140
+ },
141
+ ],
142
+ };
143
+
144
+ globalThis.fetch = vi.fn(async () => ({
145
+ ok: true,
146
+ json: async () => mockResponse,
147
+ text: async () => "",
148
+ })) as unknown as typeof fetch;
149
+
150
+ const client = new TritonClient("http://localhost:8000", "mf");
151
+ const result = await client.score(new Float32Array([1, 2, 3]));
152
+ expect(result).toBe(0.42);
153
+ });
154
+
155
+ it("score throws on empty output", async () => {
156
+ const mockResponse: InferResponse = {
157
+ model_name: "mf",
158
+ outputs: [],
159
+ };
160
+
161
+ globalThis.fetch = vi.fn(async () => ({
162
+ ok: true,
163
+ json: async () => mockResponse,
164
+ text: async () => "",
165
+ })) as unknown as typeof fetch;
166
+
167
+ const client = new TritonClient("http://localhost:8000", "mf");
168
+ await expect(
169
+ client.score(new Float32Array([1])),
170
+ ).rejects.toThrow(TritonError);
171
+ });
172
+
173
+ it("health returns live/ready status", async () => {
174
+ globalThis.fetch = vi.fn(async (url: string) => {
175
+ if (url.includes("live")) return { ok: true };
176
+ if (url.includes("ready")) return { ok: false };
177
+ return { ok: false };
178
+ }) as unknown as typeof fetch;
179
+
180
+ const client = new TritonClient("http://localhost:8000", "test");
181
+ const h = await client.health();
182
+ expect(h.live).toBe(true);
183
+ expect(h.ready).toBe(false);
184
+ });
185
+
186
+ it("health handles fetch errors gracefully", async () => {
187
+ globalThis.fetch = vi.fn(async () => {
188
+ throw new Error("network error");
189
+ }) as unknown as typeof fetch;
190
+
191
+ const client = new TritonClient("http://localhost:8000", "test");
192
+ const h = await client.health();
193
+ expect(h.live).toBe(false);
194
+ expect(h.ready).toBe(false);
195
+ });
196
+
197
+ it("modelReady returns boolean", async () => {
198
+ globalThis.fetch = vi.fn(async () => ({
199
+ ok: true,
200
+ })) as unknown as typeof fetch;
201
+
202
+ const client = new TritonClient("http://localhost:8000", "mf");
203
+ expect(await client.modelReady()).toBe(true);
204
+ });
205
+ });