Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

index.ts

549 lines16.6 KB

1#!/usr/bin/env node
2/**
3 * modelschemas CLI (PLAN.md task 7.5) — thin command layer over
4 * @modelschemas/client. `--json` everywhere (default when stdout is not a
5 * TTY) so the CLI is itself agent-friendly.
6 */
7import { readFileSync } from 'node:fs'
8import { parseArgs } from 'node:util'
9import {
10 createModelschemasClient,
11 estimateCost,
12 getModel,
13 getSchema,
14 listChanges,
15 listModels,
16 listProviderSchemas,
17 validatePayload,
18} from '@modelschemas/client'
19​
20import {
21 pull,
22 readManifest,
23 verify,
24 verifyIntegrity,
25} from '@modelschemas/codegen'
26import type { OptionalStyle, PullConfig } from '@modelschemas/codegen'
27​
28import { mintAgentJwt, registerAgent, waitForActivation } from './agent-auth.ts'
29import {
30 credentialsPath,
31 loadCredentials,
32 saveCredentials,
33} from './credentials.ts'
34import type { Credentials } from './credentials.ts'
35​
36const HELP = `modelschemas — live AI model schemas
37​
38Usage: modelschemas <command> [options]
39​
40Commands:
41 login [--name <n>] [--delegated] [--api-key] register this machine
42 whoami show identity, grants, usage
43 models list [--activity a] [--provider p] [--q text]
44 models get <provider> <modelId>
45 schema get <provider> <endpointId> [--kind input|output]
46 validate <provider/endpointId> <file> [--kind input|output]
47 estimate <provider> <model> [body.json] {request?,usage?} or usage object
48 changes [--since <epoch>] [--provider p] [--type t]
49 subscribe <url> [--events e1,e2] [--provider p]
50 pull <selection...> [--out dir] [--no-types] [--optional exact|undefined]
51 generate schema/type modules
52 (e.g. anthropic/v1/messages#request, gemini/*)
53 update [--out dir] refresh pulled modules (selection
54 comes from the manifest)
55 verify [--out dir] verify pulled modules: files match
56 the manifest AND the service still
57 serves bytes matching each pinned
58 content hash (reports provenance)
59​
60Options:
61 --base-url <url> service origin (default: $MODELSCHEMAS_URL or https://modelschemas.com)
62 --json force JSON output (default when piped)
63 -h, --help this help
65​
66interface Ctx {
67 baseUrl: string
68 json: boolean
69 values: Record<string, string | boolean | undefined>
70 positionals: Array<string>
72​
73function output(ctx: Ctx, value: unknown): void {
74 const pretty = !ctx.json && process.stdout.isTTY
75 console.log(JSON.stringify(value, null, pretty ? 2 : 0))
77​
78function fail(message: string): never {
79 console.error(`error: ${message}`)
80 process.exit(1)
82​
83async function authHeader(
84 credentials: Credentials | null,
85): Promise<string | undefined> {
86 if (!credentials) return undefined
87 if (credentials.type === 'api-key') return `Bearer ${credentials.apiKey}`
88 return `Bearer ${await mintAgentJwt(credentials)}`
90​
91function makeClient(ctx: Ctx) {
92 return createModelschemasClient({ baseUrl: ctx.baseUrl })
94​
95function headerFields(
96 headers: HeadersInit | undefined,
97): Record<string, string> {
98 if (headers === undefined) return {}
99 if (headers instanceof Headers) return Object.fromEntries(headers.entries())
100 if (Array.isArray(headers)) return Object.fromEntries(headers)
101 const record: Record<string, string> = {}
102 for (const [key, value] of Object.entries(headers)) {
103 if (typeof value === 'string') record[key] = value
104 }
105 return record
107​
108async function authedFetch(
109 ctx: Ctx,
110 path: string,
111 init?: RequestInit,
112): Promise<Response> {
113 const header = await authHeader(loadCredentials())
114 return fetch(`${ctx.baseUrl}${path}`, {
115 ...init,
116 headers: {
117 ...headerFields(init?.headers),
118 ...(header ? { Authorization: header } : {}),
119 ...(init?.body ? { 'Content-Type': 'application/json' } : {}),
120 },
121 })
123​
124async function cmdLogin(ctx: Ctx): Promise<void> {
125 const name = String(ctx.values.name ?? 'modelschemas-cli')
126 if (ctx.values['api-key']) {
127 const response = await fetch(`${ctx.baseUrl}/v1/agents/register-key`, {
128 method: 'POST',
129 headers: { 'Content-Type': 'application/json' },
130 body: JSON.stringify({ name }),
131 })
132 if (!response.ok) fail(`register-key failed: ${await response.text()}`)
133 const body = (await response.json()) as { key: string }
134 const path = saveCredentials({
135 type: 'api-key',
136 baseUrl: ctx.baseUrl,
137 apiKey: body.key,
138 })
139 output(ctx, { ok: true, type: 'api-key', credentials: path })
140 return
141 }
142​
143 const mode = ctx.values.delegated ? 'delegated' : 'autonomous'
144 const registered = await registerAgent(ctx.baseUrl, { name, mode })
145 const credentials: Credentials = {
146 type: 'agent',
147 baseUrl: ctx.baseUrl,
148 ...registered.credentials,
149 }
150 const path = saveCredentials(credentials)
151​
152 if (mode === 'delegated' && registered.status !== 'active') {
153 console.error(
154 `approve this agent: ${registered.approval?.verificationUri ?? 'see your dashboard'}` +
155 (registered.approval?.userCode
156 ? ` (code: ${registered.approval.userCode})`
157 : ''),
158 )
159 const activated = await waitForActivation(
160 ctx.baseUrl,
161 registered.credentials,
162 )
163 if (!activated) fail('approval timed out — re-run login once approved')
164 }
165 output(ctx, {
166 ok: true,
167 type: 'agent',
168 mode,
169 agentId: registered.credentials.agentId,
170 status: registered.status,
171 credentials: path,
172 })
174​
175async function cmdWhoami(ctx: Ctx): Promise<void> {
176 const credentials = loadCredentials()
177 if (!credentials) fail("not logged in — run 'modelschemas login' first")
178 const response = await authedFetch(ctx, '/v1/agents/me')
179 if (!response.ok) fail(`whoami failed: ${await response.text()}`)
180 output(ctx, await response.json())
182​
183async function cmdModels(ctx: Ctx): Promise<void> {
184 const [sub, provider, modelId] = ctx.positionals
185 const client = makeClient(ctx)
186 if (sub === 'get') {
187 if (!provider || !modelId) fail('usage: models get <provider> <modelId>')
188 const result = await getModel({
189 client,
190 path: { provider, modelId },
191 })
192 if (result.error !== undefined) fail(JSON.stringify(result.error))
193 output(ctx, result.data)
194 return
195 }
196 const result = await listModels({
197 client,
198 query: {
199 activity: ctx.values.activity as never,
200 provider: ctx.values.provider as string | undefined,
201 capability: ctx.values.capability as string | undefined,
202 q: ctx.values.q as string | undefined,
203 },
204 })
205 if (result.error !== undefined) fail(JSON.stringify(result.error))
206 output(ctx, result.data)
208​
209async function resolveActivity(
210 ctx: Ctx,
211 provider: string,
212 endpointId: string,
213): Promise<string> {
214 const client = makeClient(ctx)
215 const index = await listProviderSchemas({ client, path: { provider } })
216 if (index.error !== undefined) fail(JSON.stringify(index.error))
217 const activities = (
218 index.data as { activities: Record<string, Array<string>> }
219 ).activities
220 for (const [activity, ids] of Object.entries(activities)) {
221 if (ids.includes(endpointId)) return activity
222 }
223 fail(
224 `endpoint '${endpointId}' not found for ${provider}. Known: ${Object.values(activities).flat().join(', ')}`,
225 )
227​
228async function cmdSchema(ctx: Ctx): Promise<void> {
229 const [sub, provider, endpointId] = ctx.positionals
230 if (sub !== 'get' || !provider || !endpointId) {
231 fail('usage: schema get <provider> <endpointId> [--kind input|output]')
232 }
233 const activity = await resolveActivity(ctx, provider, endpointId)
234 const result = await getSchema({
235 client: makeClient(ctx),
236 path: { provider, activity: activity as never, endpointId },
237 query: { kind: (ctx.values.kind ?? 'input') as never },
238 })
239 if (result.error !== undefined) fail(JSON.stringify(result.error))
240 output(ctx, result.data)
242​
243const isRecord = (value: unknown): value is Record<string, unknown> =>
244 typeof value === 'object' && value !== null && !Array.isArray(value)
245​
246/** `{ request?, usage? }` wrapper, or a bare usage object (SKILL.md). */
247export function estimateBodyFromFile(parsed: unknown): {
248 request?: Record<string, unknown>
249 usage?: Record<string, unknown>
250} | null {
251 if (!isRecord(parsed)) return null
252 if ('request' in parsed || 'usage' in parsed) {
253 if (parsed.request !== undefined && !isRecord(parsed.request)) return null
254 if (parsed.usage !== undefined && !isRecord(parsed.usage)) return null
255 return {
256 request: parsed.request,
257 usage: parsed.usage,
258 }
259 }
260 return { usage: parsed }
262​
263async function cmdEstimate(ctx: Ctx): Promise<void> {
264 const [provider, model, file] = ctx.positionals
265 if (!provider || !model) {
266 fail('usage: estimate <provider> <model> [body.json]')
267 }
268 let extra: {
269 request?: Record<string, unknown>
270 usage?: Record<string, unknown>
271 } = {}
272 if (file) {
273 let parsed: unknown
274 try {
275 parsed = JSON.parse(readFileSync(file, 'utf8'))
276 } catch (error) {
277 fail(`could not read body file: ${String(error)}`)
278 }
279 const body = estimateBodyFromFile(parsed)
280 if (!body) {
281 fail(
282 'body file must be a JSON object { request?, usage? } or a usage object',
283 )
284 }
285 extra = body
286 }
287 const result = await estimateCost({
288 client: makeClient(ctx),
289 body: {
290 provider,
291 model,
292 request: extra.request,
293 usage: extra.usage,
294 },
295 })
296 if (result.error !== undefined) fail(JSON.stringify(result.error))
297 output(ctx, result.data)
299​
300async function cmdValidate(ctx: Ctx): Promise<void> {
301 const [target, file] = ctx.positionals
302 if (!target?.includes('/') || !file) {
303 fail('usage: validate <provider/endpointId> <payload.json>')
304 }
305 const slash = target.indexOf('/')
306 const provider = target.slice(0, slash)
307 const endpointId = target.slice(slash + 1)
308 let payload: unknown
309 try {
310 payload = JSON.parse(readFileSync(file, 'utf8'))
311 } catch (error) {
312 fail(`could not read payload file: ${String(error)}`)
313 }
314 const result = await validatePayload({
315 client: makeClient(ctx),
316 body: {
317 provider,
318 endpointId,
319 kind: ctx.values.kind as never,
320 payload,
321 },
322 })
323 if (result.error !== undefined) fail(JSON.stringify(result.error))
324 const verdict = result.data as { valid: boolean }
325 output(ctx, result.data)
326 // Agent-friendly: invalid payloads exit non-zero.
327 if (!verdict.valid) process.exit(2)
329​
330async function cmdChanges(ctx: Ctx): Promise<void> {
331 const result = await listChanges({
332 client: makeClient(ctx),
333 query: {
334 since: ctx.values.since ? Number(ctx.values.since) : undefined,
335 provider: ctx.values.provider as string | undefined,
336 type: ctx.values.type as never,
337 },
338 })
339 if (result.error !== undefined) fail(JSON.stringify(result.error))
340 output(ctx, result.data)
342​
343async function cmdSubscribe(ctx: Ctx): Promise<void> {
344 const [url] = ctx.positionals
345 if (!url) fail('usage: subscribe <url> [--events e1,e2] [--provider p]')
346 const events = String(ctx.values.events ?? 'model.added,model.removed')
347 .split(',')
348 .map((event) => event.trim())
349 const response = await authedFetch(ctx, '/v1/subscriptions', {
350 method: 'POST',
351 body: JSON.stringify({
352 url,
353 events,
354 provider: ctx.values.provider as string | undefined,
355 }),
356 })
357 if (!response.ok) fail(`subscribe failed: ${await response.text()}`)
358 output(ctx, await response.json())
360​
361export interface PullFlags {
362 outDir: string
363 types: boolean
364 optionalStyle: OptionalStyle | undefined
366​
367/** Shared flag parsing for `pull`/`update` — exported for tests. */
368export function parsePullFlags(
369 values: Record<string, string | boolean | undefined>,
370): PullFlags {
371 const optional = values.optional
372 if (
373 optional !== undefined &&
374 optional !== 'exact' &&
375 optional !== 'undefined'
376 ) {
377 fail(`invalid --optional '${String(optional)}' — use exact or undefined`)
378 }
379 return {
380 outDir: typeof values.out === 'string' ? values.out : 'src/modelschemas',
381 types: values['no-types'] !== true,
382 optionalStyle: optional,
383 }
385​
386function pullApiKey(): string | undefined {
387 if (process.env.MODELSCHEMAS_API_KEY !== undefined) {
388 return process.env.MODELSCHEMAS_API_KEY
389 }
390 const credentials = loadCredentials()
391 return credentials?.type === 'api-key' ? credentials.apiKey : undefined
393​
394async function runPull(ctx: Ctx, config: PullConfig): Promise<void> {
395 const summary = await pull(config)
396 output(ctx, summary)
397 if (summary.failed.length > 0) process.exit(1)
399​
400async function cmdPull(ctx: Ctx): Promise<void> {
401 if (ctx.positionals.length === 0) {
402 fail(
403 'usage: pull <selection...> [--out dir] [--no-types] [--optional exact|undefined]',
404 )
405 }
406 const flags = parsePullFlags(ctx.values)
407 await runPull(ctx, {
408 baseUrl: ctx.baseUrl,
409 apiKey: pullApiKey(),
410 outDir: flags.outDir,
411 selections: ctx.positionals,
412 types: flags.types,
413 optionalStyle: flags.optionalStyle,
414 log: (message) => console.error(message),
415 })
417​
418async function cmdUpdate(ctx: Ctx): Promise<void> {
419 const flags = parsePullFlags(ctx.values)
420 const manifest = await readManifest(flags.outDir)
421 if (manifest === null) {
422 fail(
423 `no ${flags.outDir}/.manifest.json — run 'modelschemas pull <selection...>' first`,
424 )
425 }
426 await runPull(ctx, {
427 // Explicit --base-url wins; otherwise refresh from where we pulled.
428 baseUrl:
429 typeof ctx.values['base-url'] === 'string'
430 ? ctx.baseUrl
431 : manifest.baseUrl,
432 apiKey: pullApiKey(),
433 outDir: flags.outDir,
434 selections: manifest.selections,
435 types: manifest.types,
436 optionalStyle: manifest.optionalStyle,
437 log: (message) => console.error(message),
438 })
440​
441async function cmdVerify(ctx: Ctx): Promise<void> {
442 const flags = parsePullFlags(ctx.values)
443 const manifest = await readManifest(flags.outDir)
444 if (manifest === null) {
445 fail(
446 `no ${flags.outDir}/.manifest.json — run 'modelschemas pull <selection...>' first`,
447 )
448 }
449 const config = {
450 // Explicit --base-url wins; otherwise verify against where we pulled.
451 baseUrl:
452 typeof ctx.values['base-url'] === 'string'
453 ? ctx.baseUrl
454 : manifest.baseUrl,
455 apiKey: pullApiKey(),
456 outDir: flags.outDir,
457 selections: manifest.selections,
458 log: (message: string) => console.error(message),
459 }
460 const files = await verify(config)
461 const integrity = await verifyIntegrity(config)
462 const ok = files.ok && integrity.ok
463 output(ctx, { ok, files, integrity })
464 if (!ok) process.exit(2)
466​
467async function main(): Promise<void> {
468 const { values, positionals } = parseArgs({
469 args: process.argv.slice(2),
470 allowPositionals: true,
471 options: {
472 'base-url': { type: 'string' },
473 json: { type: 'boolean' },
474 help: { type: 'boolean', short: 'h' },
475 name: { type: 'string' },
476 delegated: { type: 'boolean' },
477 'api-key': { type: 'boolean' },
478 activity: { type: 'string' },
479 provider: { type: 'string' },
480 capability: { type: 'string' },
481 q: { type: 'string' },
482 kind: { type: 'string' },
483 since: { type: 'string' },
484 type: { type: 'string' },
485 events: { type: 'string' },
486 out: { type: 'string' },
487 'no-types': { type: 'boolean' },
488 optional: { type: 'string' },
489 },
490 })
491​
492 const [command, ...rest] = positionals
493 if (values.help || !command) {
494 console.log(HELP)
495 process.exit(command ? 0 : 1)
496 }
497​
498 const stored = loadCredentials()
499 const ctx: Ctx = {
500 baseUrl:
501 values['base-url'] ??
502 process.env.MODELSCHEMAS_URL ??
503 stored?.baseUrl ??
504 'https://modelschemas.com',
505 json: values.json ?? !process.stdout.isTTY,
506 values,
507 positionals: rest,
508 }
509​
510 switch (command) {
511 case 'login':
512 return cmdLogin(ctx)
513 case 'whoami':
514 return cmdWhoami(ctx)
515 case 'models':
516 return cmdModels(ctx)
517 case 'schema':
518 return cmdSchema(ctx)
519 case 'validate':
520 return cmdValidate(ctx)
521 case 'estimate':
522 return cmdEstimate(ctx)
523 case 'changes':
524 return cmdChanges(ctx)
525 case 'subscribe':
526 return cmdSubscribe(ctx)
527 case 'pull':
528 return cmdPull(ctx)
529 case 'update':
530 return cmdUpdate(ctx)
531 case 'verify':
532 return cmdVerify(ctx)
533 default:
534 fail(`unknown command '${command}'.\n${HELP}`)
535 }
537​
538// Only run when executed as the bin — not when imported (e.g. by tests).
539if (import.meta.main) {
540 main().catch((error: unknown) => {
541 console.error(
542 `error: ${error instanceof Error ? error.message : String(error)}`,
543 )
544 process.exit(1)
545 })
547​
548// Referenced for help/tests; credentialsPath is part of the public surface.
549export { credentialsPath, HELP }