@agentage/extension 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
+ import { type RouteEntry } from './routes.js';
3
+ type Json = Record<string, unknown>;
4
+ export declare const schemaOf: (zod: object, io: "input" | "output") => Json;
5
+ export declare const generatedOpenapi: (pkg: ExtensionPackage, routes: RouteEntry[]) => Json;
6
+ export {};
@@ -0,0 +1,68 @@
1
+ import { scopeOf } from '../auth/token-check.js';
2
+ import { ErrorEnvelopeSchema } from '../envelope/envelope.schema.js';
3
+ import {} from '../manifest/manifest.schema.js';
4
+ import {} from './routes.js';
5
+ // Through Standard Schema, so an author's own zod copy lists like the kit's.
6
+ export const schemaOf = (zod, io) => zod['~standard'].jsonSchema[io]({ target: 'draft-2020-12' });
7
+ const bare = (zod, io) => {
8
+ const schema = { ...schemaOf(zod, io) };
9
+ delete schema['$schema'];
10
+ return schema;
11
+ };
12
+ const json = (schema) => ({ 'application/json': { schema } });
13
+ const content = (description, schema) => ({ description, content: json(schema) });
14
+ const okResponse = (output) => content('the envelope', {
15
+ type: 'object',
16
+ properties: {
17
+ success: { type: 'boolean', const: true },
18
+ data: output ? bare(output, 'output') : {},
19
+ },
20
+ required: ['success', 'data'],
21
+ });
22
+ const INVALID = content('VALIDATION_ERROR', bare(ErrorEnvelopeSchema, 'input'));
23
+ const inQuery = ({ method }) => method === 'get' || method === 'delete';
24
+ const parameters = (entry) => {
25
+ const path = [...entry.path.matchAll(/\{(\w+)\}/g)].map(([, name]) => ({
26
+ name,
27
+ in: 'path',
28
+ required: true,
29
+ schema: { type: 'string' },
30
+ }));
31
+ if (!entry.spec.input || !inQuery(entry))
32
+ return path;
33
+ const { properties = {}, required = [] } = bare(entry.spec.input, 'input');
34
+ const query = Object.entries(properties).map(([name, schema]) => ({
35
+ name,
36
+ in: 'query',
37
+ required: required.includes(name),
38
+ schema,
39
+ }));
40
+ return [...path, ...query];
41
+ };
42
+ const operation = (id, entry) => {
43
+ const { summary, scope, input, output } = entry.spec;
44
+ const params = parameters(entry);
45
+ return {
46
+ summary,
47
+ security: scope === 'public' ? [] : [{ pat: [scopeOf(id, scope)] }],
48
+ ...(params.length > 0 && { parameters: params }),
49
+ ...(input &&
50
+ !inQuery(entry) && { requestBody: { required: true, content: json(bare(input, 'input')) } }),
51
+ responses: { '200': okResponse(output), ...(input && { '400': INVALID }) },
52
+ };
53
+ };
54
+ // The api's contract from its ctx.route declarations: what openapi.json must hold.
55
+ export const generatedOpenapi = (pkg, routes) => {
56
+ const { id } = pkg.agentage;
57
+ const paths = {};
58
+ for (const entry of routes) {
59
+ const at = `/api/v1${entry.path}`;
60
+ paths[at] = { ...paths[at], [entry.method]: operation(id, entry) };
61
+ }
62
+ return {
63
+ openapi: '3.1.0',
64
+ info: { title: id, version: pkg.version },
65
+ components: { securitySchemes: { pat: { type: 'http', scheme: 'bearer' } } },
66
+ paths,
67
+ };
68
+ };
@@ -0,0 +1,36 @@
1
+ import { type z } from 'zod';
2
+ import { type Access, type Caller } from '../auth/token-check.js';
3
+ import { type PartContext } from '../context/context.js';
4
+ export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
5
+ export type RouteMethod = (typeof ROUTE_METHODS)[number];
6
+ type ObjectSchema = z.ZodObject;
7
+ export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extends Access = Access> {
8
+ summary: string;
9
+ scope?: S;
10
+ input?: I;
11
+ output?: O;
12
+ }
13
+ export type ParamsOf<P extends string> = P extends `${string}{${infer N}}${infer R}` ? {
14
+ [K in N]: string;
15
+ } & ParamsOf<R> : Record<never, string>;
16
+ export interface RouteRequest<I, P extends string, S extends Access = Access> {
17
+ input: I;
18
+ params: ParamsOf<P>;
19
+ caller: S extends 'public' ? Caller | null : Caller;
20
+ }
21
+ export type RouteHandler<I extends ObjectSchema, O extends z.ZodType, P extends string, S extends Access = Access> = (request: RouteRequest<z.output<I>, P, S>) => z.input<O> | Promise<z.input<O>>;
22
+ export type RouteRegistrar = <P extends string, I extends ObjectSchema = z.ZodObject<Record<never, z.ZodType>>, O extends z.ZodType = z.ZodUnknown, S extends Access = 'read'>(method: RouteMethod, path: P, spec: RouteSpec<I, O, S>, handler: RouteHandler<I, O, P, S>) => void;
23
+ export interface ApiContext extends PartContext {
24
+ readonly route: RouteRegistrar;
25
+ }
26
+ export interface RouteEntry {
27
+ method: RouteMethod;
28
+ path: string;
29
+ spec: RouteSpec<ObjectSchema, z.ZodType>;
30
+ handler: (request: RouteRequest<Record<string, unknown>, string, 'public'>) => unknown;
31
+ }
32
+ export declare const createRouteRegistry: () => {
33
+ route: RouteRegistrar;
34
+ routes: RouteEntry[];
35
+ };
36
+ export {};
@@ -0,0 +1,30 @@
1
+ import {} from 'zod';
2
+ import {} from '../auth/token-check.js';
3
+ import {} from '../context/context.js';
4
+ export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
5
+ const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
6
+ const SCOPES = ['public', 'read', 'write', 'admin'];
7
+ const problemOf = (routes, { method, path, spec }) => {
8
+ if (!ROUTE_METHODS.includes(method))
9
+ return `method ${String(method)}: one of get, post, put, patch, delete`;
10
+ if (!PATH.test(path))
11
+ return 'path: /segments and {param} segments under /api/v1';
12
+ if (routes.some((r) => r.method === method && r.path === path))
13
+ return 'is registered twice';
14
+ if (!spec.summary)
15
+ return 'needs a summary: it documents the route';
16
+ if (spec.scope !== undefined && !SCOPES.includes(spec.scope))
17
+ return `scope ${String(spec.scope)}: one of ${SCOPES.join(', ')}`;
18
+ return null;
19
+ };
20
+ export const createRouteRegistry = () => {
21
+ const routes = [];
22
+ const route = (method, path, spec, handler) => {
23
+ const entry = { method, path, spec, handler: handler };
24
+ const problem = problemOf(routes, entry);
25
+ if (problem)
26
+ throw new Error(`route ${String(method).toUpperCase()} ${path} ${problem}`);
27
+ routes.push(entry);
28
+ };
29
+ return { route, routes };
30
+ };
@@ -0,0 +1,2 @@
1
+ import { type ExtensionInfo } from './context.js';
2
+ export declare const packageExtension: (dir?: string) => Partial<ExtensionInfo>;
@@ -0,0 +1,22 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { PackageSchema } from '../manifest/manifest.schema.js';
4
+ import { storeOf } from '../manifest/parts.js';
5
+ import {} from './context.js';
6
+ const readJson = (file) => {
7
+ try {
8
+ return JSON.parse(readFileSync(file, 'utf8'));
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ };
14
+ // The id, version and store kind of the package a test runs in; nothing outside an extension.
15
+ export const packageExtension = (dir = process.cwd()) => {
16
+ const parsed = PackageSchema.safeParse(readJson(join(dir, 'package.json')));
17
+ if (!parsed.success)
18
+ return {};
19
+ const { version, agentage } = parsed.data;
20
+ const store = storeOf(parsed.data);
21
+ return { id: agentage.id, version, ...(store && { store }) };
22
+ };
@@ -1,3 +1,4 @@
1
+ import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
1
2
  import { type CliContext } from '../command/command.types.js';
2
3
  import { type LogFields, type LogLevel } from '../log/log.js';
3
4
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
@@ -17,6 +18,8 @@ export interface TestContext extends PartContext {
17
18
  readonly schedule: Schedule;
18
19
  readonly tool: ToolRegistrar;
19
20
  readonly tools: ToolEntry[];
21
+ readonly route: RouteRegistrar;
22
+ readonly routes: RouteEntry[];
20
23
  readonly jobs: ScheduledJob[];
21
24
  runJob(name: string): Promise<JobRun | undefined>;
22
25
  }
@@ -1,3 +1,4 @@
1
+ import { createRouteRegistry } from '../api/routes.js';
1
2
  import {} from '../command/command.types.js';
2
3
  import { createOut } from '../command/out.js';
3
4
  import { messageOf } from '../log/log.js';
@@ -8,6 +9,8 @@ import {} from '../worker/job-options.js';
8
9
  import { runLog } from '../worker/run-log.js';
9
10
  import { memoryRuns } from '../worker/runs.js';
10
11
  import { createScheduler } from '../worker/scheduler.js';
12
+ import {} from '../manifest/primitives.schema.js';
13
+ import { packageExtension } from './package-extension.js';
11
14
  import { NO_STORE } from './context.js';
12
15
  import {} from '../command/args.js';
13
16
  const recordingLog = (logs) => ({
@@ -40,14 +43,29 @@ const recorders = (log) => {
40
43
  scheduler.schedule(name, cron, job, options);
41
44
  jobs.push({ name, cron, options });
42
45
  };
43
- return { ...createToolRegistry(), schedule, jobs, runJob: scheduler.run };
46
+ return {
47
+ ...createToolRegistry(),
48
+ ...createRouteRegistry(),
49
+ schedule,
50
+ jobs,
51
+ runJob: scheduler.run,
52
+ };
53
+ };
54
+ // ./package.json's identity and store kind; its postgres store opens a test store unless store is false.
55
+ const identityOf = (options) => {
56
+ const { store: kind, ...identity } = packageExtension();
57
+ const store = options.store ?? kind === 'postgres';
58
+ // An open test store is postgres; a closed one hides postgres but keeps a kind it cannot serve.
59
+ const closedKind = kind === 'postgres' ? undefined : kind;
60
+ const own = store ? 'postgres' : closedKind;
61
+ const extension = { ...TEST_EXTENSION, ...identity, ...(own && { store: own }) };
62
+ return { store, extension: { ...extension, ...options.extension } };
44
63
  };
45
64
  const serverContext = (options) => {
46
65
  const logs = [];
47
66
  const log = runLog(recordingLog(logs));
48
- const store = testStore(options.store, recordingLog([]));
49
- const kind = options.store ? { store: 'postgres' } : {};
50
- const extension = { ...TEST_EXTENSION, ...kind, ...options.extension };
67
+ const { extension, ...open } = identityOf(options);
68
+ const store = testStore(open.store, recordingLog([]));
51
69
  const caller = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
52
70
  return {
53
71
  extension,
@@ -70,7 +88,8 @@ const commandContext = (options) => {
70
88
  stdout: lines(output.stdout),
71
89
  stderr: lines(output.stderr),
72
90
  });
73
- const extension = { id: 'test', version: '0.0.0', ...options.extension, part: 'cli' };
91
+ const { id = 'test', version = '0.0.0' } = packageExtension();
92
+ const extension = { id, version, ...options.extension, part: 'cli' };
74
93
  return {
75
94
  extension,
76
95
  args: { ...options.args },
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { type ApiContext, type ParamsOf, type RouteHandler, type RouteMethod, type RouteRegistrar, type RouteRequest, type RouteSpec, } from './api/routes.js';
1
2
  export { type ArgValue } from './command/args.js';
2
3
  export { type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
3
4
  export { type Out } from './command/out.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export {} from './api/routes.js';
1
2
  export {} from './command/args.js';
2
3
  export {} from './command/command.types.js';
3
4
  export {} from './command/out.js';
@@ -1,4 +1,5 @@
1
1
  import { join } from 'node:path';
2
+ import { generatedOpenapi } from '../api/openapi-doc.js';
2
3
  import {} from 'express';
3
4
  import {} from '../context/context.js';
4
5
  import {} from '../manifest/manifest.schema.js';
@@ -9,7 +10,7 @@ import { createMcpApp } from '../mcp/mcp-app.js';
9
10
  import { createToolRegistry } from '../mcp/tools.js';
10
11
  import { createPagesApp } from '../pages/pages-app.js';
11
12
  import { createApiApp, createPartApp } from '../server/app.js';
12
- import {} from '../server/part.types.js';
13
+ import { mountApi } from '../server/api-routes.js';
13
14
  import {} from './build-info.js';
14
15
  import { createUiApp } from '../ui/ui-app.js';
15
16
  import { runLog } from '../worker/run-log.js';
@@ -18,8 +19,11 @@ import { createScheduler } from '../worker/scheduler.js';
18
19
  // ui has no code to run; every other part is its create(ctx).
19
20
  const callCreate = async (input, part, ctx) => (await loadCreate(input.dir, input.pkg, part, input.importModule))(ctx);
20
21
  const api = async (input) => {
21
- const router = (await callCreate(input, 'api', input.ctx()));
22
- return { app: createApiApp({ ...input.base, router, openapi: input.openapi }) };
22
+ const ctx = input.ctx();
23
+ const { router, routes } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
24
+ // Declared routes guard at their own scope, whatever the committed file says.
25
+ const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
26
+ return { app: createApiApp({ ...input.base, router, openapi }) };
23
27
  };
24
28
  const mcp = async (input) => {
25
29
  const registry = createToolRegistry();
@@ -0,0 +1,7 @@
1
+ import { type ApiContext, type RouteEntry } from '../api/routes.js';
2
+ import { type PartContext } from '../context/context.js';
3
+ import { type ApiHandler } from './part.types.js';
4
+ export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<{
5
+ router: ApiHandler;
6
+ routes: RouteEntry[];
7
+ }>;
@@ -0,0 +1,45 @@
1
+ import { Router } from 'express';
2
+ import { createRouteRegistry } from '../api/routes.js';
3
+ import {} from '../context/context.js';
4
+ import { ok } from '../envelope/envelope.js';
5
+ import { parse } from '../envelope/parse.js';
6
+ import {} from './part.types.js';
7
+ const inQuery = (method) => method === 'get' || method === 'delete';
8
+ const inputOf = ({ method, spec }, query, body) => {
9
+ if (!spec.input)
10
+ return {};
11
+ if (inQuery(method))
12
+ return parse(spec.input, query, 'Invalid query');
13
+ return parse(spec.input, body ?? {}, 'Invalid body');
14
+ };
15
+ // Validated in, the handler's answer parsed by its output schema and sent in the envelope.
16
+ const handlerOf = (ctx, entry) => async (req, res) => {
17
+ const input = inputOf(entry, req.query, req.body);
18
+ const caller = ctx.auth.caller(req);
19
+ const data = await entry.handler({ input, params: req.params, caller });
20
+ res.json(ok(entry.spec.output ? entry.spec.output.parse(data) : data));
21
+ };
22
+ // /items/{id} as Express writes it.
23
+ const expressPath = (path) => path.replace(/\{(\w+)\}/g, ':$1');
24
+ const routesRouter = (ctx, routes) => {
25
+ const router = Router();
26
+ for (const entry of routes)
27
+ router[entry.method](expressPath(entry.path), handlerOf(ctx, entry));
28
+ return router;
29
+ };
30
+ // What create(ctx) gave: its ctx.route routes, or the router it returned; exactly one.
31
+ const handlerFor = (ctx, routes, returned) => {
32
+ if (routes.length > 0 && returned)
33
+ throw new Error('the api part registers ctx.route routes and returns a router: pick one');
34
+ if (routes.length > 0)
35
+ return routesRouter(ctx, routes);
36
+ if (!returned)
37
+ throw new Error('the api part registers nothing and returns no router');
38
+ return returned;
39
+ };
40
+ // Runs the api part's create(ctx) with ctx.route; the runtime and the test server mount alike.
41
+ export const mountApi = async (ctx, create) => {
42
+ const { route, routes } = createRouteRegistry();
43
+ const returned = await create({ ...ctx, route });
44
+ return { router: handlerFor(ctx, routes, returned), routes };
45
+ };
@@ -1,7 +1,7 @@
1
1
  import { type RequestHandler, type Router } from 'express';
2
- import { type PartContext } from '../context/context.js';
2
+ import { type ApiContext } from '../api/routes.js';
3
3
  export type ApiHandler = Router | RequestHandler;
4
- export type ApiCreate<C extends PartContext = PartContext> = (ctx: C) => ApiHandler | Promise<ApiHandler>;
4
+ export type ApiCreate<C extends ApiContext = ApiContext> = (ctx: C) => ApiHandler | void | Promise<ApiHandler | void>;
5
5
  export interface ApiPart {
6
6
  create: ApiCreate;
7
7
  }
@@ -1,2 +1,2 @@
1
1
  import {} from 'express';
2
- import {} from '../context/context.js';
2
+ import {} from '../api/routes.js';
@@ -1,8 +1,9 @@
1
+ import { type ApiContext } from '../api/routes.js';
1
2
  import { type PartContext } from '../context/context.js';
2
3
  import { type McpContext } from '../mcp/tools.js';
3
4
  import { type ApiCreate } from '../server/part.types.js';
4
5
  export interface TestServerOptions<C extends PartContext> {
5
- create: ApiCreate<C>;
6
+ create: ApiCreate<C & ApiContext>;
6
7
  ctx?: C;
7
8
  }
8
9
  export interface TestMcpOptions {
@@ -1,11 +1,13 @@
1
1
  import {} from 'node:net';
2
2
  import {} from 'express';
3
+ import {} from '../api/routes.js';
3
4
  import {} from '../context/context.js';
4
5
  import { createTestContext } from '../context/test-context.js';
5
6
  import {} from '../manifest/manifest.schema.js';
6
7
  import { createMcpApp } from '../mcp/mcp-app.js';
7
8
  import { callTool } from '../mcp/snapshot.js';
8
9
  import { createToolRegistry, prefixed } from '../mcp/tools.js';
10
+ import { mountApi } from '../server/api-routes.js';
9
11
  import { createApiApp } from '../server/app.js';
10
12
  import {} from '../server/part.types.js';
11
13
  import { listen } from '../server/serve.js';
@@ -28,7 +30,7 @@ const startOn = async (app) => {
28
30
  // Runs an api part's create(ctx) inside the kit's real app on 127.0.0.1, port chosen by the OS.
29
31
  export const startTestServer = async (options) => {
30
32
  const ctx = options.ctx ?? createTestContext();
31
- const router = await options.create(ctx);
33
+ const { router } = await mountApi(ctx, (api) => options.create({ ...ctx, ...api }));
32
34
  const pkg = testPackage(ctx, { api: true });
33
35
  return startOn(createApiApp({ pkg, build: TEST_BUILD, router, log: ctx.log }));
34
36
  };
@@ -1,5 +1,7 @@
1
1
  import { readFile, writeFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
+ import { generatedOpenapi } from '../api/openapi-doc.js';
4
+ import {} from '../api/routes.js';
3
5
  import { OPENAPI_FILE } from '../discovery/openapi.js';
4
6
  import { loadCreate } from '../manifest/entry.js';
5
7
  import {} from '../manifest/manifest.schema.js';
@@ -8,6 +10,7 @@ import { readManifest } from '../manifest/read-manifest.js';
8
10
  import { canonical } from '../mcp/snapshot.js';
9
11
  import {} from '../mcp/tools.js';
10
12
  import { NOT_BUILT } from './check.js';
13
+ import { registeredRoutes } from './record-extras.js';
11
14
  import { generatedMcp } from './rules/surface.js';
12
15
  import { exists } from './stage.js';
13
16
  const readText = (file) => readFile(file, 'utf8').catch(() => undefined);
@@ -36,6 +39,18 @@ const writeOpenapiVersion = async (dir, version) => {
36
39
  await writeFile(file, inPlace);
37
40
  return [OPENAPI_FILE];
38
41
  };
42
+ // A ctx.route api: the whole document from its routes; a router api: only info.version.
43
+ const writeOpenapi = async (dir, pkg) => {
44
+ const create = await loadCreate(dir, pkg, 'api');
45
+ const { routes } = await registeredRoutes(create, pkg);
46
+ if (routes.length === 0)
47
+ return writeOpenapiVersion(dir, pkg.version);
48
+ const doc = generatedOpenapi(pkg, routes);
49
+ if (sameJson(await readText(join(dir, OPENAPI_FILE)), doc))
50
+ return [];
51
+ await writeFile(join(dir, OPENAPI_FILE), json(doc));
52
+ return [OPENAPI_FILE];
53
+ };
39
54
  // check --write: the committed contracts regenerated from the built code; returns the files it changed.
40
55
  export const writeContracts = async (at) => {
41
56
  const dir = resolve(at);
@@ -44,5 +59,5 @@ export const writeContracts = async (at) => {
44
59
  throw new Error(`dist ${NOT_BUILT}`);
45
60
  const { code } = normalizeParts(pkg.agentage.parts);
46
61
  const mcp = code.mcp ? await writeMcp(dir, pkg) : [];
47
- return [...mcp, ...(code.api ? await writeOpenapiVersion(dir, pkg.version) : [])];
62
+ return [...mcp, ...(code.api ? await writeOpenapi(dir, pkg) : [])];
48
63
  };
@@ -1,8 +1,13 @@
1
+ import { type ApiContext } from '../api/routes.js';
1
2
  import { type RecordExtras } from '../discovery/discovery.js';
2
3
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
4
  import { type McpContext } from '../mcp/tools.js';
4
5
  export declare const recordingContext: (pkg: ExtensionPackage, part: "api" | "mcp") => import("../context/context.js").PartContext;
5
6
  export declare const registeredTools: (create: (ctx: McpContext) => unknown, pkg: ExtensionPackage) => Promise<import("../mcp/tools.js").ToolEntry[]>;
7
+ export declare const registeredRoutes: (create: (ctx: ApiContext) => unknown, pkg: ExtensionPackage) => Promise<{
8
+ routes: import("../api/routes.js").RouteEntry[];
9
+ returned: unknown;
10
+ }>;
6
11
  export declare const toolsOf: (dir: string, pkg: ExtensionPackage) => Promise<{
7
12
  name: string;
8
13
  scope: string;
@@ -1,5 +1,6 @@
1
1
  import { join } from 'node:path';
2
2
  import { z } from 'zod';
3
+ import { createRouteRegistry } from '../api/routes.js';
3
4
  import { scopeOf } from '../auth/token-check.js';
4
5
  import { createContext } from '../context/context.js';
5
6
  import {} from '../discovery/discovery.js';
@@ -34,6 +35,12 @@ export const registeredTools = async (create, pkg) => {
34
35
  await create({ ...recordingContext(pkg, 'mcp'), tool: registry.tool });
35
36
  return registry.tools;
36
37
  };
38
+ // What an api part's create(ctx) registers with ctx.route, and what it returns.
39
+ export const registeredRoutes = async (create, pkg) => {
40
+ const registry = createRouteRegistry();
41
+ const returned = await create({ ...recordingContext(pkg, 'api'), route: registry.route });
42
+ return { routes: registry.routes, returned };
43
+ };
37
44
  export const toolsOf = async (dir, pkg) => {
38
45
  const tools = await registeredTools(await loadCreate(dir, pkg, 'mcp'), pkg);
39
46
  const { id } = pkg.agentage;
@@ -1,5 +1,6 @@
1
1
  import { join } from 'node:path';
2
- import {} from '../../context/context.js';
2
+ import { generatedOpenapi, schemaOf } from '../../api/openapi-doc.js';
3
+ import {} from '../../api/routes.js';
3
4
  import { OPENAPI_FILE, readOpenapi } from '../../discovery/openapi.js';
4
5
  import { loadCreate } from '../../manifest/entry.js';
5
6
  import {} from '../../manifest/manifest.schema.js';
@@ -8,7 +9,7 @@ import { readJsonIfExists } from '../../manifest/read-manifest.js';
8
9
  import { canonical } from '../../mcp/snapshot.js';
9
10
  import { prefixed } from '../../mcp/tools.js';
10
11
  import {} from '../check.js';
11
- import { recordingContext, registeredTools } from '../record-extras.js';
12
+ import { registeredRoutes, registeredTools } from '../record-extras.js';
12
13
  const differing = (generated, committed) => [...new Set([...Object.keys(generated), ...Object.keys(committed)])].filter((key) => JSON.stringify(canonical(generated[key])) !== JSON.stringify(canonical(committed[key])));
13
14
  const routeKeys = ({ path, stack }) => [path].flat().flatMap((one) => {
14
15
  const at = `/api/v1${String(one).replace(/:(\w+)/g, '{$1}')}`;
@@ -28,6 +29,11 @@ const METHODS = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'pat
28
29
  const operations = (doc) => Object.entries((doc['paths'] ?? {})).flatMap(([path, ops]) => Object.entries(ops ?? {})
29
30
  .filter(([method]) => METHODS.has(method))
30
31
  .map(([method, op]) => [`${method.toUpperCase()} ${path}`, op]));
32
+ // One entry per operation and per top-level key, so a diff names what moved.
33
+ const flat = (doc) => {
34
+ const top = Object.entries(doc).filter(([key]) => key !== 'paths');
35
+ return Object.fromEntries([...top, ...operations(doc)]);
36
+ };
31
37
  const declaresAccess = (security) => Array.isArray(security) &&
32
38
  (security.length === 0 ||
33
39
  security.some((need) => Object.values(need ?? {}).some((s) => s.length > 0)));
@@ -43,17 +49,28 @@ const apiProblems = (doc, routes, version) => {
43
49
  ...open.map(([key]) => `${key} declares neither a scope nor security: []`),
44
50
  ];
45
51
  };
52
+ const routeProblems = (pkg, doc, routes, returned) => {
53
+ if (returned)
54
+ return ['the api part registers ctx.route routes and returns a router: pick one'];
55
+ if (!doc)
56
+ return ['is missing: check --write generates it from the ctx.route routes'];
57
+ const diff = differing(flat(generatedOpenapi(pkg, routes)), flat(doc));
58
+ return diff.length > 0 ? [`differs from the generated contract (${diff.join(', ')})`] : [];
59
+ };
60
+ const routerProblems = (pkg, doc, returned) => doc
61
+ ? apiProblems(doc, servedRoutes(returned), pkg.version)
62
+ : ['is missing: the api part commits its contract'];
46
63
  const apiSurface = async ({ dir, pkg }) => {
47
64
  const create = await loadCreate(dir, pkg, 'api').catch(() => null);
48
65
  if (!create)
49
66
  return [];
67
+ const { routes, returned } = await registeredRoutes(create, pkg);
50
68
  const doc = await readOpenapi(dir);
51
- const found = doc
52
- ? apiProblems(doc, servedRoutes(await create(recordingContext(pkg, 'api'))), pkg.version)
53
- : ['is missing: the api part commits its contract'];
69
+ const found = routes.length > 0
70
+ ? routeProblems(pkg, doc, routes, returned)
71
+ : routerProblems(pkg, doc, returned);
54
72
  return found.map((problem) => ({ file: OPENAPI_FILE, problem }));
55
73
  };
56
- const schemaOf = (zod, io) => zod['~standard'].jsonSchema[io]({ target: 'draft-2020-12' });
57
74
  const listed = (id, { name, spec }) => ({
58
75
  name: prefixed(id, name),
59
76
  description: spec.description,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "The agentage extension kit: create(ctx) per part (pages, ui, api, mcp, worker, cli), the store, /health, discovery, the envelope, and the build tool with up and token",
5
5
  "type": "module",
6
6
  "license": "MIT",