Skip to content

Quickstart: Hono on Workers

This quickstart embeds aidy in a Hono app on Cloudflare Workers. The runtime runs in the same Worker as your API: it reaches your routes through app.fetch in-process, stores threads in D1, and serves the agent, MCP and generated documents from your own origin.

The running example is a cloud console at https://console.example.com with a stop_vm operation.

Terminal window
npm install @aidy-dev/core @aidy-dev/sql @aidy-dev/spec @hono/zod-openapi
npm install @aidy-dev/client @aidy-dev/react
npm install -g @aidy-dev/cli

The CLI is used once here, to generate aidy’s signing key.

With @hono/zod-openapi, add an x-aidy object to each route that aidy may call. Routes without one stay invisible to aidy. @hono/zod-openapi copies the key into the generated OpenAPI operation as is.

src/api.ts
import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi';
import type { AssertionClaims } from '@aidy-dev/spec/delegation';
export type Env = {
DB: D1Database;
AIDY_SIGNING_KEY: string; // private JWK, a secret
AIDY_PUBLIC_JWK: string; // public JWK, a var
AIDY_SECRET: string;
OPENAI_API_KEY: string;
};
type Vars = { user: { id: string; orgId: string; name: string }; aidy?: AssertionClaims };
export const app = new OpenAPIHono<{ Bindings: Env; Variables: Vars }>();
app.use('/api/*', authenticate); // your existing session or bearer auth, sets c.var.user
const Vm = z.object({ id: z.string(), name: z.string(), status: z.enum(['running', 'stopped']) });
app.openapi(
aidyRoute({
method: 'get',
path: '/api/vm/{vm_id}',
summary: 'Get a server',
request: { params: z.object({ vm_id: z.string() }) },
responses: { 200: { description: 'The VM', content: { 'application/json': { schema: Vm } } } },
'x-aidy': { name: 'get_vm', description: 'Get a cloud server (VM) by id.' },
}),
async (c) => c.json(await getVm(c.var.user, c.req.valid('param').vm_id), 200),
);
app.openapi(
aidyRoute({
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',
title: 'Stop server',
description: 'Stop a running cloud server (VM).',
effect: 'update',
open: '/console/instance/{vm_id}',
confirmation: {
title: 'Stop server {resource_name}?',
fields: [{ key: 'forced', label: 'Force', values: { true: 'Yes', false: 'No' } }],
lookup: { path: '/api/vm/{vm_id}', labelPath: 'name' },
},
},
}),
async (c) => c.json(await stopVm(c.var.user, c.req.valid('param').vm_id, c.req.valid('json')), 200),
);

A POST defaults to the effect create. Stopping a server changes an existing one, so set effect: 'update' on stop_vm. Any effect other than read is a write and needs approval by default; see Operations and effects.

aidy needs exactly one role: identity operation to learn who a credential belongs to, and can federate any number of role: search operations.

const Identity = z.object({ subject: z.string(), tenant: z.string().optional(), name: z.string().optional() });
app.openapi(
aidyRoute({
method: 'get',
path: '/api/me',
responses: { 200: { description: 'Me', content: { 'application/json': { schema: Identity } } } },
'x-aidy': { name: 'whoami', role: 'identity' },
}),
(c) => c.json({ subject: c.var.user.id, tenant: c.var.user.orgId, name: c.var.user.name }, 200),
);
app.openapi(
aidyRoute({
method: 'get',
path: '/api/vms/search',
request: { query: z.object({ q: z.string(), limit: z.coerce.number().max(50).default(10) }) },
responses: { 200: { description: 'Hits', content: { 'application/json': { schema: z.object({ hits: z.array(z.any()) }) } } } },
'x-aidy': { name: 'search_vms', role: 'search' },
}),
async (c) => {
const { q, limit } = c.req.valid('query');
const vms = await findVms(c.var.user, q, limit);
return c.json({ hits: vms.map((vm) => ({ type: 'vm', id: vm.id, title: vm.name, url: `/console/instance/${vm.id}` })) }, 200);
},
);
app.doc31('/openapi.json', { openapi: '3.1.0', info: { title: 'Console', version: '1' } });

See Identity and Search and knowledge.

Every call aidy makes carries the user’s credential and an Aidy-Assertion. Your API authenticates the credential as usual and verifies the assertion. aidyRoute attaches a middleware to each annotated route that does both halves of the check from Delegation: verifyAssertion (signature, lifetime, audience, method, URL, body, replay) and checkCall (subject, tenant, operation, approval).

No aidy package ships aidyRoute; it is a few lines of your own code on top of @aidy-dev/spec/delegation:

src/aidy-route.ts
import { createRoute, type RouteConfig } from '@hono/zod-openapi';
import { checkCall, importPublicKeys, verifyAssertion } from '@aidy-dev/spec/delegation';
import { createMiddleware } from 'hono/factory';
type XAidy = { name: string; effect?: string; approval?: 'never' | 'always' } & Record<string, unknown>;
const seen = new Map<string, number>(); // jti → exp, per isolate
export function aidyRoute<R extends RouteConfig & { 'x-aidy': XAidy }>(route: R) {
const meta = route['x-aidy'];
const effect = meta.effect ?? (route.method === 'get' ? 'read' : 'write');
const approval = meta.approval ?? (effect === 'read' ? 'never' : 'always');
const verify = createMiddleware(async (c, next) => {
const token = c.req.header('aidy-assertion');
if (!token) return next(); // an ordinary request from your UI
try {
const claims = await verifyAssertion(token, {
keys: await importPublicKeys([JSON.parse(c.env.AIDY_PUBLIC_JWK)]),
audience: 'https://console.example.com',
request: { method: c.req.method, url: c.req.url, body: new Uint8Array(await c.req.arrayBuffer()) },
remember: (jti, exp) => {
if (seen.has(jti)) return false;
seen.set(jti, exp);
return true;
},
});
const user = c.get('user');
checkCall(claims, { subject: user.id, tenant: user.orgId, op: meta.name, approval });
c.set('aidy', claims); // audit: actor = aidy, claims.rid, claims.apr
} catch {
return c.json({ error: 'aidy_assertion_invalid' }, 401);
}
return next();
});
return createRoute({ ...route, middleware: [verify] });
}
Terminal window
aidy keys generate --kid aidy-2026-11 -o aidy-2026-11.private.jwk

The command prints the public JWK and writes the private JWK to a new file with mode 0600. It never prints the private key.

Terminal window
npx wrangler secret put AIDY_SIGNING_KEY < aidy-2026-11.private.jwk
openssl rand -base64 32 | npx wrangler secret put AIDY_SECRET
npx wrangler secret put OPENAI_API_KEY
rm aidy-2026-11.private.jwk

Put the printed public JWK in wrangler.jsonc as the var AIDY_PUBLIC_JWK. AIDY_SECRET seals model API keys that admins save in settings.

Terminal window
npx wrangler d1 create console-aidy
wrangler.jsonc
{
"name": "console",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"d1_databases": [{ "binding": "DB", "database_name": "console-aidy", "database_id": "<id>" }],
"vars": { "AIDY_PUBLIC_JWK": "{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"x\":\"…\",\"kid\":\"aidy-2026-11\"}" }
}

aidy creates its aidy_* tables on the first request, or when you call aidy.migrate().

src/index.ts
import { createAidy, SqlStore, type Aidy } from '@aidy-dev/core';
import { importSigningKey } from '@aidy-dev/spec/delegation';
import { d1Driver } from '@aidy-dev/sql/d1';
import type { Context } from 'hono';
import { app, type Env } from './api';
let aidy: Promise<Aidy> | undefined;
function aidyFor(env: Env): Promise<Aidy> {
aidy ??= (async () => {
const signingKey = await importSigningKey(JSON.parse(env.AIDY_SIGNING_KEY));
return createAidy({
url: 'https://console.example.com',
host: {
origin: 'https://console.example.com',
openapi: '/openapi.json',
fetch: (request) => app.fetch(request, env), // in-process, no network hop
},
signingKey,
secret: env.AIDY_SECRET,
store: new SqlStore(d1Driver(env.DB)),
models: { chain: [{ id: 'main', provider: 'openai', model: 'gpt-4.1-mini', apiKey: env.OPENAI_API_KEY }] },
});
})();
return aidy;
}
const serve = async (c: Context<{ Bindings: Env }>) => (await aidyFor(c.env)).fetch(c.req.raw, c.executionCtx);
app.all('/aidy/v0/*', serve);
app.all('/mcp', serve);
app.get('/skill.md', serve);
app.get('/llms.txt', serve);
app.get('/.well-known/aidy-keys.json', serve);
export default app;

importSigningKey imports the private JWK as an extractable key, so aidy can publish its public half at /.well-known/aidy-keys.json, and drops the members workerd refuses (a Node-exported alg, key_ops, ext). createAidy returns { fetch(request, ctx?), migrate(), close() }; passing c.executionCtx lets runs continue after the response with waitUntil. createAidy does no I/O until the first request, so building it once per isolate is cheap. To mount aidy below a prefix such as /assistant, set basePath. Model choice and fallbacks are covered in Models.

Deploy and check the generated documents:

Terminal window
npx wrangler deploy
curl -H "Authorization: Bearer $TOKEN" https://console.example.com/skill.md
web/Shell.tsx
import { createClient } from '@aidy-dev/client';
import { AidyDock, AidyProvider, SearchPalette } from '@aidy-dev/react';
import '@aidy-dev/react/styles.css';
import type { ReactNode } from 'react';
import { useNavigate } from 'react-router';
const client = createClient(); // same origin; the client adds /aidy/v0
export function Shell({ children }: { children: ReactNode }) {
const navigate = useNavigate();
return (
<AidyProvider client={client} locale="en" onOpen={(path) => navigate(path)}>
{children}
<AidyDock />
<SearchPalette />
</AidyProvider>
);
}

aidy treats the request’s Authorization and Cookie headers as the user’s credential, so a same-origin cookie session works as is. With bearer tokens, add them in createClient:

const client = createClient({
headers: () => ({ Authorization: `Bearer ${getToken()}` }),
});

⌘J toggles the dock. Ask it to “stop gpu-train-01”: it looks the server up, shows an approval card titled “Stop server gpu-train-01?”, and runs only after you approve. After success, onOpen receives /console/instance/vm-42.