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

agent-roundtrip.ts

147 lines4.7 KB

1// End-to-end agent-auth round-trip against a running dev server (task 5.1
2// acceptance): discovery → POST /agent/register (autonomous, dynamic host,
3// inline Ed25519 keys) → POST /capability/execute round-tripping getSchema.
4//
5// bun scripts/agent-roundtrip.ts [baseUrl]
6//
7// Exits non-zero on any failure. Also used as a reference client until the
8// real CLI lands (task 7.5).
9import { SignJWT, exportJWK, generateKeyPair } from 'jose'
10​
11const base = process.argv[2] ?? 'http://localhost:3000'
12​
13interface Discovery {
14 issuer: string
15 default_location: string
16 algorithms: Array<string>
17 endpoints: Record<string, string>
19​
20async function fail(step: string, response: Response): Promise<never> {
21 console.error(`${step} failed: ${String(response.status)}`)
22 console.error(await response.text())
23 process.exit(1)
25​
26const discoveryResponse = await fetch(`${base}/.well-known/agent-configuration`)
27if (!discoveryResponse.ok) await fail('discovery', discoveryResponse)
28const discovery = (await discoveryResponse.json()) as Discovery
29console.log(`discovery ok (issuer ${discovery.issuer})`)
30​
31const hostKeys = await generateKeyPair('Ed25519', { extractable: true })
32const agentKeys = await generateKeyPair('Ed25519', { extractable: true })
33const hostJwk = await exportJWK(hostKeys.publicKey)
34const agentJwk = await exportJWK(agentKeys.publicKey)
35const hostId = crypto.randomUUID()
36​
37const hostJwt = await new SignJWT({
38 aud: discovery.issuer,
39 host_public_key: hostJwk,
40 agent_public_key: agentJwk,
41})
42 .setProtectedHeader({ alg: 'EdDSA', typ: 'host+jwt' })
43 .setIssuer(hostId)
44 .setIssuedAt()
45 .setJti(crypto.randomUUID())
46 .setExpirationTime('5m')
47 .sign(hostKeys.privateKey)
48​
49const registerResponse = await fetch(discovery.endpoints.register ?? '', {
50 method: 'POST',
51 headers: {
52 'Content-Type': 'application/json',
53 Authorization: `Bearer ${hostJwt}`,
54 },
55 body: JSON.stringify({
56 name: 'roundtrip-test-agent',
57 mode: 'autonomous',
58 capabilities: ['getSchema'],
59 host_name: 'roundtrip-host',
60 }),
61})
62if (!registerResponse.ok) await fail('register', registerResponse)
63const registration = (await registerResponse.json()) as Record<string, unknown>
64const agentId =
65 (registration.agent_id as string | undefined) ??
66 (registration.id as string | undefined)
67console.log(
68 `register ok (agent ${String(agentId)}, status ${String(registration.status)})`,
70if (!agentId) {
71 console.error('no agent id in register response:', registration)
72 process.exit(1)
74​
75// iss = host id, sub = agent id (§ the server resolves the agent by `sub`
76// and cross-checks `iss` against the agent's host).
77const registeredHostId = (registration.host_id as string | undefined) ?? hostId
78const agentJwt = await new SignJWT({
79 aud: discovery.default_location,
80 capabilities: ['getSchema'],
81})
82 .setProtectedHeader({ alg: 'EdDSA', typ: 'agent+jwt' })
83 .setIssuer(registeredHostId)
84 .setSubject(agentId)
85 .setIssuedAt()
86 .setJti(crypto.randomUUID())
87 .setExpirationTime('2m')
88 .sign(agentKeys.privateKey)
89​
90const executeResponse = await fetch(discovery.default_location, {
91 method: 'POST',
92 headers: {
93 'Content-Type': 'application/json',
94 Authorization: `Bearer ${agentJwt}`,
95 },
96 body: JSON.stringify({
97 capability: 'getSchema',
98 arguments: {
99 provider: 'anthropic',
100 activity: 'chat',
101 endpointId: 'v1/messages',
102 kind: 'input',
103 },
104 }),
105})
106if (!executeResponse.ok) await fail('execute', executeResponse)
107const executed = (await executeResponse.json()) as {
108 data?: { contentHash?: string; schema?: unknown }
109 contentHash?: string
110 schema?: unknown
112const payload = executed.data ?? executed
113if (!payload.schema || !payload.contentHash) {
114 console.error(
115 'execute returned no schema:',
116 JSON.stringify(executed).slice(0, 500),
117 )
118 process.exit(1)
120console.log(
121 `execute ok — getSchema round-tripped (contentHash ${String(payload.contentHash).slice(0, 12)}…)`,
123​
124// Native protected route (task 5.2): /v1/agents/me with a fresh agent JWT
125// (jti is replay-protected, so the execute JWT can't be reused).
126const meJwt = await new SignJWT({ aud: discovery.default_location })
127 .setProtectedHeader({ alg: 'EdDSA', typ: 'agent+jwt' })
128 .setIssuer(registeredHostId)
129 .setSubject(agentId)
130 .setIssuedAt()
131 .setJti(crypto.randomUUID())
132 .setExpirationTime('2m')
133 .sign(agentKeys.privateKey)
134const meResponse = await fetch(`${base}/v1/agents/me`, {
135 headers: { Authorization: `Bearer ${meJwt}` },
136})
137if (!meResponse.ok) await fail('agents/me', meResponse)
138const me = (await meResponse.json()) as {
139 agent?: { agentId?: string; capabilities?: Array<string> }
141if (me.agent?.agentId !== agentId) {
142 console.error('agents/me returned wrong agent:', me)
143 process.exit(1)
145console.log(
146 `agents/me ok (capabilities: ${(me.agent.capabilities ?? []).join(', ')})`,