Hono
Hono 应用可以把 aidy 运行时内嵌在同一进程中,运行于 Node 或 Cloudflare Workers。用 @hono/zod-openapi 声明的路由在 schema 旁边带上 x-aidy,应用自己提供 OpenAPI 3.1 文档,aidy 通过 app.fetch 在进程内调用应用。
npm install hono @hono/zod-openapi @aidy-dev/core @aidy-dev/spec @aidy-dev/sqlcreateRoute 接受 OpenAPI 扩展键,因此 x-aidy 直接写在路由对象上,@hono/zod-openapi 会把它复制到生成的操作中。
import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
const app = new OpenAPIHono();
const stopVm = createRoute({ method: 'post', path: '/api/vm/{vm_id}/stop', summary: 'Stop server', request: { params: z.object({ vm_id: z.string() }), body: { content: { 'application/json': { schema: z.object({ forced: z.boolean().default(false) }) } } }, }, responses: { 200: { description: 'Stopped', content: { 'application/json': { schema: Vm } } } }, 'x-aidy': { name: 'stop_vm', description: 'Stop a running cloud server (VM).', open: '/console/instance/{vm_id}', confirmation: { title: 'Stop server {resource_name}?', lookup: { path: '/api/vm/{vm_id}', labelPath: 'name' }, }, },});
app.openapi(stopVm, async (c) => { const { vm_id } = c.req.valid('param'); return c.json(await vms.stop(vm_id, c.req.valid('json')), 200);});路径参数、查询参数和 JSON 请求体字段会合并成一个扁平的输入 schema;同一个名字出现在两处属于目录错误。详见操作。
提供 OpenAPI 文档
Section titled “提供 OpenAPI 文档”aidy 用用户自己的凭证获取这份文档,所以宿主可以只向每个用户返回其可用的操作。以 OpenAPI 3.1 格式提供:
app.doc31('/openapi.json', { openapi: '3.1.0', info: { title: 'Cloud Console', version: '1.0.0', description: 'Cloud servers on demand.' },});info.title 和 info.description 会作为产品名称和简介出现在 /skill.md 与 /llms.txt 中。用 aidy check --openapi http://localhost:8787/openapi.json 检查目录。
一个带 role: identity 的 GET 操作负责回答凭证属于谁:
const whoami = createRoute({ method: 'get', path: '/api/me', responses: { 200: { description: 'Caller', content: { 'application/json': { schema: Identity } } } }, 'x-aidy': { name: 'whoami', role: 'identity' },});
app.openapi(whoami, (c) => { const user = c.get('user'); return c.json({ subject: user.id, tenant: user.tenantId, name: user.name, scopes: user.scopes }, 200);});搜索源的写法相同,使用 role: 'search' 和必填的查询参数 q,详见搜索。
挂载 aidy
Section titled “挂载 aidy”@aidy-dev/core 的 createAidy(config) 返回 { fetch(request, ctx?), migrate(), close() }。fetch 是处理所有 aidy 路由的 Web 标准处理函数。把应用自己的 fetch 传给 host.fetch,aidy 发出的调用就留在进程内。
import { createAidy, SqlStore } from '@aidy-dev/core';import { importSigningKey } from '@aidy-dev/spec/delegation';import { sqliteDriver } from '@aidy-dev/sql/sqlite';
// The private JWK from `aidy keys generate`, imported extractable so aidy can publish the// public key at /.well-known/aidy-keys.json.const signingKey = await importSigningKey(JSON.parse(process.env.AIDY_SIGNING_KEY!));
const aidy = createAidy({ url: 'https://console.example.com', host: { origin: 'https://console.example.com', openapi: '/openapi.json', fetch: (request) => app.fetch(request), }, signingKey, secret: process.env.AIDY_SECRET!, store: new SqlStore(sqliteDriver('aidy.sqlite')), models: { chain: [ { id: 'qwen', provider: 'openai-compatible', model: 'qwen3-max', baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1', apiKey: process.env.DASHSCOPE_API_KEY, }, ], },});
for (const path of ['/aidy/v0/*', '/mcp', '/skill.md', '/llms.txt', '/.well-known/aidy-keys.json']) { app.all(path, (c) => aidy.fetch(c.req.raw));}在 Workers 上,把执行上下文作为第二个参数传入(aidy.fetch(c.req.raw, c.executionCtx)),让运行在响应结束后继续,并改用 @aidy-dev/sql/d1 的 d1Driver。挂在某个前缀下时,设置 basePath(例如 /assistant),并让 url 与之一致;此时 aidy 的所有路由都在该前缀下,用一个 app.all('/assistant/*', …) 即可挂载。aidy 不提供 Hono 适配包:上面几行加上下面的中间件就是全部集成。
在 Workers 上,waitUntil 受请求生命周期的限制,响应提前关闭时运行可能被中断。生产环境中,应把每个用户(或每个对话)路由到一个持有 aidy 实例的 Durable Object,见部署:多实例。Workers AI 模型见模型。
aidy 发出的每个调用都带有 Aidy-Assertion。在路由之前加一个中间件,用 @aidy-dev/spec/delegation 校验它:verifyAssertion 负责签名、有效期、audience、方法、URL、请求体哈希和重放;checkCall 负责用户、操作和审批。
import { createMiddleware } from 'hono/factory';import { ASSERTION_HEADER, AssertionError, checkCall, importPublicKeys, verifyAssertion,} from '@aidy-dev/spec/delegation';
const keys = await importPublicKeys([JSON.parse(process.env.AIDY_PUBLIC_JWK!)]);const seen = new Map<string, number>(); // jti -> expiry; prune it, or use Redis/KV with several instances
type Op = { method: string; pattern: RegExp; op: string; approval: 'never' | 'always' };let operations: Op[] | undefined;function catalogOps(): Op[] { const doc = app.getOpenAPI31Document({ openapi: '3.1.0', info: { title: 'Cloud Console', version: '1.0.0' } }); return Object.entries(doc.paths ?? {}).flatMap(([path, item]) => Object.entries(item ?? {}).flatMap(([method, operation]) => { const ext = (operation as { 'x-aidy'?: { name: string; effect?: string; approval?: 'never' | 'always' } })['x-aidy']; if (!ext) return []; const read = (ext.effect ?? (method === 'get' || method === 'head' ? 'read' : 'write')) === 'read'; return [{ method: method.toUpperCase(), pattern: new RegExp(`^${path.replace(/\{[^}]+\}/g, '[^/]+')}$`), op: ext.name, approval: ext.approval ?? (read ? 'never' : 'always'), }]; }), );}
app.use('/api/*', createMiddleware(async (c, next) => { const token = c.req.header(ASSERTION_HEADER); if (!token) return next(); // an ordinary user request try { const claims = await verifyAssertion(token, { keys, audience: 'https://console.example.com', request: { method: c.req.method, url: c.req.url, body: new Uint8Array(await c.req.raw.clone().arrayBuffer()) }, remember: (jti, until) => { if (seen.has(jti)) return false; seen.set(jti, until); return true; }, }); operations ??= catalogOps(); const served = operations.find((o) => o.method === c.req.method && o.pattern.test(c.req.path)); const user = c.get('user'); // resolved from Authorization by your auth middleware checkCall(claims, { subject: user.id, tenant: user.tenantId, op: served?.op ?? '', approval: served?.approval ?? 'always' }); c.set('aidy', claims); // rid, cid, apr for your audit log } catch (error) { if (!(error instanceof AssertionError)) throw error; return c.json({ error: 'aidy_assertion_invalid', code: error.code }, 401); } return next();}));c.req.url 必须等于断言中的 htu:host.origin 加上 aidy 调用的路径和查询串。使用 host.fetch 且未设置 host.baseUrl 时正是如此。如果代理改写了主机名或剥掉了前缀,就用公开源重建它。规则见委托。