Open History to see the last commit
1/**
2 * Agent-auth protocol client for the CLI: discovery, registration
3 * (autonomous by default, delegated via the device-authorization flow),
4 * and per-request JWT minting (jtis are replay-protected server-side).
5 */
6import { SignJWT, exportJWK, generateKeyPair, importJWK } from 'jose'
7
8import type { AgentCredentials } from './credentials.ts'
9
10export interface Discovery {
11 issuer: string
12 default_location: string
13 endpoints: Record<string, string>
14}
15
16export async function fetchDiscovery(baseUrl: string): Promise<Discovery> {
17 const response = await fetch(`${baseUrl}/.well-known/agent-configuration`)
18 if (!response.ok) {
19 throw new Error(
20 `discovery failed: ${String(response.status)} — is ${baseUrl} a modelschemas server?`,
21 )
22 }
23 return (await response.json()) as Discovery
24}
25
26interface RegisterOutcome {
27 credentials: Omit<AgentCredentials, 'type' | 'baseUrl'>
28 status: string
29 /** Present for delegated registrations needing user approval. */
30 approval?: { verificationUri?: string; userCode?: string }
31}
32
33export async function registerAgent(
34 baseUrl: string,
35 options: { name: string; mode: 'autonomous' | 'delegated' },
36): Promise<RegisterOutcome> {
37 const discovery = await fetchDiscovery(baseUrl)
38 const hostKeys = await generateKeyPair('Ed25519', { extractable: true })
39 const agentKeys = await generateKeyPair('Ed25519', { extractable: true })
40 const hostId = crypto.randomUUID()
41
42 const hostJwt = await new SignJWT({
43 aud: discovery.issuer,
44 host_public_key: await exportJWK(hostKeys.publicKey),
45 agent_public_key: await exportJWK(agentKeys.publicKey),
46 })
47 .setProtectedHeader({ alg: 'EdDSA', typ: 'host+jwt' })
48 .setIssuer(hostId)
49 .setIssuedAt()
50 .setJti(crypto.randomUUID())
51 .setExpirationTime('5m')
52 .sign(hostKeys.privateKey)
53
54 const response = await fetch(discovery.endpoints.register ?? '', {
55 method: 'POST',
56 headers: {
57 'Content-Type': 'application/json',
58 Authorization: `Bearer ${hostJwt}`,
59 },
60 body: JSON.stringify({
61 name: options.name,
62 mode: options.mode,
63 host_name: `${options.name} (modelschemas cli)`,
64 }),
65 })
66 if (!response.ok) {
67 throw new Error(
68 `register failed: ${String(response.status)} ${await response.text()}`,
69 )
70 }
71 const body = (await response.json()) as {
72 agent_id?: string
73 host_id?: string
74 status?: string
75 verification_uri?: string
76 verification_uri_complete?: string
77 user_code?: string
78 }
79 if (!body.agent_id) {
80 throw new Error(`register returned no agent id: ${JSON.stringify(body)}`)
81 }
82 return {
83 credentials: {
84 agentId: body.agent_id,
85 hostId: body.host_id ?? hostId,
86 privateKeyJwk: await exportJWK(agentKeys.privateKey),
87 },
88 status: body.status ?? 'unknown',
89 approval:
90 body.verification_uri || body.user_code
91 ? {
92 verificationUri:
93 body.verification_uri_complete ?? body.verification_uri,
94 userCode: body.user_code,
95 }
96 : undefined,
97 }
98}
99
100/** Poll agent status until active (delegated approval) or timeout. */
101export async function waitForActivation(
102 baseUrl: string,
103 credentials: Omit<AgentCredentials, 'type' | 'baseUrl'>,
104 timeoutSeconds = 300,
105): Promise<boolean> {
106 const discovery = await fetchDiscovery(baseUrl)
107 const statusUrl = discovery.endpoints.status
108 if (!statusUrl) return false
109 const deadline = Date.now() + timeoutSeconds * 1000
110 while (Date.now() < deadline) {
111 const jwt = await mintAgentJwt(
112 { type: 'agent', baseUrl, ...credentials },
113 discovery,
114 )
115 const response = await fetch(statusUrl, {
116 headers: { Authorization: `Bearer ${jwt}` },
117 })
118 if (response.ok) {
119 const body = (await response.json()) as { status?: string }
120 if (body.status === 'active') return true
121 }
122 await new Promise((resolve) => setTimeout(resolve, 3000))
123 }
124 return false
125}
126
127export async function mintAgentJwt(
128 credentials: AgentCredentials,
129 discovery?: Discovery,
130): Promise<string> {
131 const resolved = discovery ?? (await fetchDiscovery(credentials.baseUrl))
132 const key = await importJWK(credentials.privateKeyJwk, 'EdDSA')
133 return new SignJWT({ aud: resolved.default_location })
134 .setProtectedHeader({ alg: 'EdDSA', typ: 'agent+jwt' })
135 .setIssuer(credentials.hostId)
136 .setSubject(credentials.agentId)
137 .setIssuedAt()
138 .setJti(crypto.randomUUID())
139 .setExpirationTime('2m')
140 .sign(key)
141}