@agentage/extension 0.5.0 → 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.
Files changed (38) hide show
  1. package/dist/api/openapi-doc.d.ts +6 -0
  2. package/dist/api/openapi-doc.js +68 -0
  3. package/dist/api/routes.d.ts +36 -0
  4. package/dist/api/routes.js +30 -0
  5. package/dist/context/context.d.ts +2 -0
  6. package/dist/context/context.js +4 -0
  7. package/dist/context/package-extension.d.ts +2 -0
  8. package/dist/context/package-extension.js +22 -0
  9. package/dist/context/test-context.d.ts +10 -0
  10. package/dist/context/test-context.js +30 -4
  11. package/dist/index.d.ts +3 -2
  12. package/dist/index.js +1 -0
  13. package/dist/mcp/snapshot.d.ts +3 -0
  14. package/dist/mcp/snapshot.js +7 -0
  15. package/dist/runtime/part-runners.js +7 -3
  16. package/dist/server/api-routes.d.ts +7 -0
  17. package/dist/server/api-routes.js +45 -0
  18. package/dist/server/part.types.d.ts +2 -2
  19. package/dist/server/part.types.js +1 -1
  20. package/dist/testing/test-server.d.ts +6 -2
  21. package/dist/testing/test-server.js +8 -3
  22. package/dist/tool/check.d.ts +1 -0
  23. package/dist/tool/check.js +6 -3
  24. package/dist/tool/contracts.d.ts +1 -0
  25. package/dist/tool/contracts.js +63 -0
  26. package/dist/tool/index.d.ts +1 -0
  27. package/dist/tool/index.js +1 -0
  28. package/dist/tool/record-extras.d.ts +5 -0
  29. package/dist/tool/record-extras.js +7 -0
  30. package/dist/tool/rules/folders.d.ts +4 -0
  31. package/dist/tool/rules/folders.js +38 -0
  32. package/dist/tool/rules/sealing.js +3 -1
  33. package/dist/tool/rules/surface.d.ts +4 -0
  34. package/dist/tool/rules/surface.js +32 -11
  35. package/dist/tool/up/health.d.ts +3 -0
  36. package/dist/tool/up/health.js +40 -0
  37. package/dist/tool/up/up.js +8 -3
  38. package/package.json +1 -1
@@ -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
+ };
@@ -1,5 +1,6 @@
1
1
  import { type Caller } from '../auth/token-check.js';
2
2
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type StoreKind } from '../manifest/primitives.schema.js';
3
4
  import { type Log } from '../log/log.js';
4
5
  import { type Store } from '../store/store.types.js';
5
6
  import { type Secrets } from './secrets.js';
@@ -11,6 +12,7 @@ export interface ExtensionInfo {
11
12
  part: ServerPartKind;
12
13
  origin: string;
13
14
  commit: string;
15
+ store?: StoreKind;
14
16
  }
15
17
  export interface PartContext {
16
18
  readonly extension: Readonly<ExtensionInfo>;
@@ -1,5 +1,7 @@
1
1
  import { callerOf } from '../auth/token-check.js';
2
2
  import {} from '../manifest/manifest.schema.js';
3
+ import { storeOf } from '../manifest/parts.js';
4
+ import {} from '../manifest/primitives.schema.js';
3
5
  import { createLog } from '../log/log.js';
4
6
  import {} from '../store/store.types.js';
5
7
  import {} from './secrets.js';
@@ -12,12 +14,14 @@ export const NO_STORE = {
12
14
  export const settingDefaults = (pkg) => Object.fromEntries(Object.entries(pkg.agentage.settings ?? {}).map(([key, setting]) => [key, setting.default]));
13
15
  export const createContext = (input) => {
14
16
  const { pkg, part, origin, commit, store } = input;
17
+ const kind = storeOf(pkg);
15
18
  const extension = Object.freeze({
16
19
  id: pkg.agentage.id,
17
20
  version: pkg.version,
18
21
  part,
19
22
  origin,
20
23
  commit,
24
+ ...(kind && { store: kind }),
21
25
  });
22
26
  const log = input.log ?? createLog({ extension: pkg.agentage.id, part });
23
27
  const settings = Object.freeze({ ...settingDefaults(pkg), ...input.settings });
@@ -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,6 +1,8 @@
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';
5
+ import { type JobOptions } from '../worker/job-options.js';
4
6
  import { type JobRun } from '../worker/runs.js';
5
7
  import { type Schedule } from '../worker/scheduler.js';
6
8
  import { type ExtensionInfo, type PartContext, type SettingValue } from './context.js';
@@ -16,8 +18,16 @@ export interface TestContext extends PartContext {
16
18
  readonly schedule: Schedule;
17
19
  readonly tool: ToolRegistrar;
18
20
  readonly tools: ToolEntry[];
21
+ readonly route: RouteRegistrar;
22
+ readonly routes: RouteEntry[];
23
+ readonly jobs: ScheduledJob[];
19
24
  runJob(name: string): Promise<JobRun | undefined>;
20
25
  }
26
+ export interface ScheduledJob {
27
+ name: string;
28
+ cron: string;
29
+ options?: JobOptions;
30
+ }
21
31
  export interface TestCommandContext extends CliContext {
22
32
  readonly output: {
23
33
  stdout: string[];
@@ -1,12 +1,16 @@
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';
4
5
  import { createToolRegistry } from '../mcp/tools.js';
5
6
  import { migrate } from '../store/migrations.js';
6
7
  import { createTestStore } from '../store/test-store.js';
8
+ import {} from '../worker/job-options.js';
7
9
  import { runLog } from '../worker/run-log.js';
8
10
  import { memoryRuns } from '../worker/runs.js';
9
11
  import { createScheduler } from '../worker/scheduler.js';
12
+ import {} from '../manifest/primitives.schema.js';
13
+ import { packageExtension } from './package-extension.js';
10
14
  import { NO_STORE } from './context.js';
11
15
  import {} from '../command/args.js';
12
16
  const recordingLog = (logs) => ({
@@ -34,13 +38,34 @@ const TEST_EXTENSION = {
34
38
  // Jobs run by hand with runJob, tools recorded as the mcp part registers them.
35
39
  const recorders = (log) => {
36
40
  const scheduler = createScheduler({ runs: memoryRuns(), log });
37
- return { ...createToolRegistry(), schedule: scheduler.schedule, runJob: scheduler.run };
41
+ const jobs = [];
42
+ const schedule = (name, cron, job, options) => {
43
+ scheduler.schedule(name, cron, job, options);
44
+ jobs.push({ name, cron, options });
45
+ };
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 } };
38
63
  };
39
64
  const serverContext = (options) => {
40
65
  const logs = [];
41
66
  const log = runLog(recordingLog(logs));
42
- const store = testStore(options.store, recordingLog([]));
43
- const extension = { ...TEST_EXTENSION, ...options.extension };
67
+ const { extension, ...open } = identityOf(options);
68
+ const store = testStore(open.store, recordingLog([]));
44
69
  const caller = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
45
70
  return {
46
71
  extension,
@@ -63,7 +88,8 @@ const commandContext = (options) => {
63
88
  stdout: lines(output.stdout),
64
89
  stderr: lines(output.stderr),
65
90
  });
66
- 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' };
67
93
  return {
68
94
  extension,
69
95
  args: { ...options.args },
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
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';
4
5
  export { type ExtensionInfo, type PartContext, type ServerPartKind, type SettingValue, } from './context/context.js';
5
6
  export { type Secrets } from './context/secrets.js';
6
- export { createTestContext, type LogEntry, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
7
+ export { createTestContext, type LogEntry, type ScheduledJob, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
7
8
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from './discovery/discovery.schema.js';
8
9
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
9
10
  export { ERROR_CODES, ERROR_STATUS, type ErrorCode } from './envelope/codes.js';
@@ -21,7 +22,7 @@ export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, }
21
22
  export { versionPage, type PagesContext, type PagesSite } from './pages/pages.js';
22
23
  export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
23
24
  export { type QueryResult, type Row, type Store } from './store/store.types.js';
24
- export { startTestMcp, startTestServer, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
25
+ export { startTestMcp, startTestServer, type TestMcp, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
25
26
  export { type JobOptions } from './worker/job-options.js';
26
27
  export { type JobRun, type RunStatus } from './worker/runs.js';
27
28
  export { type Job, type Schedule } from './worker/scheduler.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';
@@ -7,5 +7,8 @@ export interface McpSnapshot {
7
7
  };
8
8
  tools: Record<string, unknown>[];
9
9
  }
10
+ type Json = Record<string, unknown>;
10
11
  export declare const canonical: (value: unknown) => unknown;
11
12
  export declare const mcpSnapshot: (url: string, version: ProtocolVersion) => Promise<McpSnapshot>;
13
+ export declare const callTool: (url: string, name: string, args: Json) => Promise<unknown>;
14
+ export {};
@@ -67,3 +67,10 @@ export const mcpSnapshot = async (url, version) => {
67
67
  tools: listed['tools'],
68
68
  });
69
69
  };
70
+ // One tools/call as a stateless 2025-11-25 client sends it: the structured result, or a tool error thrown.
71
+ export const callTool = async (url, name, args) => {
72
+ const result = await post(url, '2025-11-25', 'tools/call', { name, arguments: args });
73
+ if (result['isError'])
74
+ throw new Error(`tool ${name}: ${JSON.stringify(result['content'])}`);
75
+ return result['structuredContent'];
76
+ };
@@ -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 {
@@ -14,5 +15,8 @@ export interface TestServer {
14
15
  fetch(path: string, init?: RequestInit): Promise<Response>;
15
16
  close(): Promise<void>;
16
17
  }
18
+ export interface TestMcp extends TestServer {
19
+ call(name: string, args?: Record<string, unknown>): Promise<unknown>;
20
+ }
17
21
  export declare const startTestServer: <C extends PartContext = PartContext>(options: TestServerOptions<C>) => Promise<TestServer>;
18
- export declare const startTestMcp: (options: TestMcpOptions) => Promise<TestServer>;
22
+ export declare const startTestMcp: (options: TestMcpOptions) => Promise<TestMcp>;
@@ -1,10 +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
- import { createToolRegistry } from '../mcp/tools.js';
8
+ import { callTool } from '../mcp/snapshot.js';
9
+ import { createToolRegistry, prefixed } from '../mcp/tools.js';
10
+ import { mountApi } from '../server/api-routes.js';
8
11
  import { createApiApp } from '../server/app.js';
9
12
  import {} from '../server/part.types.js';
10
13
  import { listen } from '../server/serve.js';
@@ -27,7 +30,7 @@ const startOn = async (app) => {
27
30
  // Runs an api part's create(ctx) inside the kit's real app on 127.0.0.1, port chosen by the OS.
28
31
  export const startTestServer = async (options) => {
29
32
  const ctx = options.ctx ?? createTestContext();
30
- const router = await options.create(ctx);
33
+ const { router } = await mountApi(ctx, (api) => options.create({ ...ctx, ...api }));
31
34
  const pkg = testPackage(ctx, { api: true });
32
35
  return startOn(createApiApp({ pkg, build: TEST_BUILD, router, log: ctx.log }));
33
36
  };
@@ -44,5 +47,7 @@ export const startTestMcp = async (options) => {
44
47
  tools: registry.tools,
45
48
  listing: 'open',
46
49
  });
47
- return startOn(app);
50
+ const server = await startOn(app);
51
+ const call = (name, args = {}) => callTool(`${server.url}/mcp`, prefixed(ctx.extension.id, name), args);
52
+ return { ...server, call };
48
53
  };
@@ -32,6 +32,7 @@ export interface CheckReport {
32
32
  problems: CheckProblem[];
33
33
  skipped: Record<string, string>;
34
34
  }
35
+ export declare const NOT_BUILT = "is missing: build the package first (npm run build)";
35
36
  export declare const RULES: readonly CheckRule[];
36
37
  export declare const check: (at: string, options?: CheckOptions) => Promise<CheckReport>;
37
38
  export declare const assertConforms: (dir: string, options?: CheckOptions) => Promise<void>;
@@ -10,12 +10,14 @@ import {} from '../manifest/primitives.schema.js';
10
10
  import { formatIssues, readJsonIfExists } from '../manifest/read-manifest.js';
11
11
  import { runCommand } from './exec.js';
12
12
  import { problemLines } from './format.js';
13
+ import { exportedPartCode } from './rules/folders.js';
13
14
  import { sealing } from './rules/sealing.js';
14
15
  import { store } from './rules/store.js';
15
16
  import { surface } from './rules/surface.js';
16
17
  import { KIT_VERSION } from './kit-version.js';
17
18
  import { assertBuilt, exists } from './stage.js';
18
19
  const RECIPE = /^(?:dockerfile|containerfile)(?:\..+)?$|^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i;
20
+ export const NOT_BUILT = 'is missing: build the package first (npm run build)';
19
21
  const NO_PACKAGE = 'is missing: run it in an extension package folder';
20
22
  const manifest = {
21
23
  name: 'manifest',
@@ -52,15 +54,16 @@ const partProblem = async ({ dir, pkg }, part) => {
52
54
  return `${normalize(entryOf(pkg, part))} not found: the package build must write the cli part there`;
53
55
  return part === 'ui' ? null : exportProblem(dir, pkg, part);
54
56
  };
55
- // Every part built where its image looks, exporting create and nothing else; cli handlers = commands.
57
+ // Every part built and exporting only create; cli handlers = commands; exports hold no part code.
56
58
  const entries = {
57
59
  name: 'entries',
58
60
  run: async (input) => {
59
61
  if (!(await exists(join(input.dir, 'dist'))))
60
- return [{ file: 'dist', problem: 'is missing: build the package first (npm run build)' }];
62
+ return [{ file: 'dist', problem: NOT_BUILT }];
61
63
  const parts = Object.keys(normalizeParts(input.pkg.agentage.parts).code);
62
64
  const found = parts.map((part) => partProblem(input, part).catch(messageOf));
63
- return (await Promise.all(found)).flatMap((problem) => (problem ? [{ problem }] : []));
65
+ const problems = (await Promise.all(found)).flatMap((problem) => problem ? [{ problem }] : []);
66
+ return [...problems, ...exportedPartCode(input.pkg)];
64
67
  },
65
68
  };
66
69
  const MAJORS = { express: '^5', zod: '^4', '@modelcontextprotocol/server': '^2' };
@@ -0,0 +1 @@
1
+ export declare const writeContracts: (at: string) => Promise<string[]>;
@@ -0,0 +1,63 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { generatedOpenapi } from '../api/openapi-doc.js';
4
+ import {} from '../api/routes.js';
5
+ import { OPENAPI_FILE } from '../discovery/openapi.js';
6
+ import { loadCreate } from '../manifest/entry.js';
7
+ import {} from '../manifest/manifest.schema.js';
8
+ import { normalizeParts } from '../manifest/parts.js';
9
+ import { readManifest } from '../manifest/read-manifest.js';
10
+ import { canonical } from '../mcp/snapshot.js';
11
+ import {} from '../mcp/tools.js';
12
+ import { NOT_BUILT } from './check.js';
13
+ import { registeredRoutes } from './record-extras.js';
14
+ import { generatedMcp } from './rules/surface.js';
15
+ import { exists } from './stage.js';
16
+ const readText = (file) => readFile(file, 'utf8').catch(() => undefined);
17
+ const sameJson = (text, value) => text !== undefined &&
18
+ JSON.stringify(canonical(JSON.parse(text))) === JSON.stringify(canonical(value));
19
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
20
+ const writeMcp = async (dir, pkg) => {
21
+ const file = `${pkg.agentage.id}.mcpc.json`;
22
+ const create = await loadCreate(dir, pkg, 'mcp');
23
+ const snapshot = canonical(await generatedMcp(create, pkg));
24
+ if (sameJson(await readText(join(dir, file)), snapshot))
25
+ return [];
26
+ await writeFile(join(dir, file), json(snapshot));
27
+ return [file];
28
+ };
29
+ const INFO_VERSION = /("info"\s*:\s*\{[^{}]*?"version"\s*:\s*)"[^"]*"/;
30
+ // Only info.version, in place so the file keeps its formatting; check reports any other drift.
31
+ const writeOpenapiVersion = async (dir, version) => {
32
+ const file = join(dir, OPENAPI_FILE);
33
+ const text = await readText(file);
34
+ if (text === undefined)
35
+ return [];
36
+ const inPlace = text.replace(INFO_VERSION, `$1${JSON.stringify(version)}`);
37
+ if (inPlace === text)
38
+ return [];
39
+ await writeFile(file, inPlace);
40
+ return [OPENAPI_FILE];
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
+ };
54
+ // check --write: the committed contracts regenerated from the built code; returns the files it changed.
55
+ export const writeContracts = async (at) => {
56
+ const dir = resolve(at);
57
+ const pkg = await readManifest(dir);
58
+ if (!(await exists(join(dir, 'dist'))))
59
+ throw new Error(`dist ${NOT_BUILT}`);
60
+ const { code } = normalizeParts(pkg.agentage.parts);
61
+ const mcp = code.mcp ? await writeMcp(dir, pkg) : [];
62
+ return [...mcp, ...(code.api ? await writeOpenapi(dir, pkg) : [])];
63
+ };
@@ -4,6 +4,7 @@ export { type ExtensionPackage, type CommandSpec } from '../manifest/manifest.sc
4
4
  export { readManifest, validateManifest } from '../manifest/read-manifest.js';
5
5
  export { build, type BuildDeps, type BuildOptions, type BuildResult, type BuiltImage, } from './build.js';
6
6
  export { check, type CheckProblem, type CheckReport } from './check.js';
7
+ export { writeContracts } from './contracts.js';
7
8
  export { buildLines, checkLines } from './format.js';
8
9
  export { KIT_VERSION } from './kit-version.js';
9
10
  export { down, type DownOptions, type DownResult } from './up/down.js';
@@ -4,6 +4,7 @@ export {} from '../manifest/manifest.schema.js';
4
4
  export { readManifest, validateManifest } from '../manifest/read-manifest.js';
5
5
  export { build, } from './build.js';
6
6
  export { check } from './check.js';
7
+ export { writeContracts } from './contracts.js';
7
8
  export { buildLines, checkLines } from './format.js';
8
9
  export { KIT_VERSION } from './kit-version.js';
9
10
  export { down } from './up/down.js';
@@ -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;
@@ -0,0 +1,4 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ import { type Finding } from '../check.js';
3
+ export declare const crossPartImports: (file: string, code: string) => Finding[];
4
+ export declare const exportedPartCode: (pkg: ExtensionPackage) => Finding[];
@@ -0,0 +1,38 @@
1
+ import { normalize, posix } from 'node:path';
2
+ import {} from '../../manifest/manifest.schema.js';
3
+ import { entryOf, normalizeParts } from '../../manifest/parts.js';
4
+ import { IMAGE_PART_KINDS } from '../../manifest/primitives.schema.js';
5
+ import {} from '../check.js';
6
+ const PARTS = [...IMAGE_PART_KINDS, 'cli'];
7
+ const PART_FOLDER = /^(?:src|dist)\/(?:pages|ui|api|mcp|worker|cli)(?:\/|$)/;
8
+ // Erased at build, so a type crosses no image; blanked keeping newlines for the line count.
9
+ const TYPE_ONLY = /\b(?:import|export)\s+type\b[^;'"]*?from\s*(['"])[^'"]*\1/g;
10
+ const RELATIVE = /\b(?:from|import)\s*\(?\s*(['"])(\.{1,2}\/[^'"]*)\1/g;
11
+ // Each image carries one part folder and src/lib, so a part imports nothing else.
12
+ export const crossPartImports = (file, code) => {
13
+ const [src, part = ''] = file.split('/');
14
+ if (src !== 'src' || !PARTS.includes(part))
15
+ return [];
16
+ const values = code.replace(TYPE_ONLY, (t) => t.replace(/[^\n]/g, ''));
17
+ return [...values.matchAll(RELATIVE)].flatMap((m) => {
18
+ const target = posix.join(posix.dirname(file), m[2] ?? '');
19
+ if (target.startsWith(`src/${part}/`) || target.startsWith('src/lib/'))
20
+ return [];
21
+ const line = values.slice(0, m.index).split('\n').length;
22
+ return [
23
+ { file, line, problem: `imports ${m[2]}: a part imports only its own folder and src/lib` },
24
+ ];
25
+ });
26
+ };
27
+ const targets = (value) => typeof value === 'string' ? [value] : Object.values(Object(value)).flatMap(targets);
28
+ // The package is the manifest and the record; part code reaches users only through its image.
29
+ export const exportedPartCode = (pkg) => {
30
+ const parts = Object.keys(normalizeParts(pkg.agentage.parts).code);
31
+ const entries = parts.map((part) => normalize(entryOf(pkg, part)));
32
+ const partCode = (target) => PART_FOLDER.test(normalize(target)) || entries.includes(normalize(target));
33
+ const exported = targets(pkg.exports).filter(partCode);
34
+ return exported.map((target) => ({
35
+ file: 'package.json',
36
+ problem: `exports ${target}: the package exports no part code`,
37
+ }));
38
+ };
@@ -2,6 +2,7 @@ import { lstat, readdir, readFile } from 'node:fs/promises';
2
2
  import { join, relative } from 'node:path';
3
3
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
4
4
  import {} from '../check.js';
5
+ import { crossPartImports } from './folders.js';
5
6
  const CODE = /\.[cm]?[jt]sx?$/;
6
7
  const TEST = /\.(test|spec)\.[cm]?[jt]sx?$/;
7
8
  // Strings first, so a // inside one is no comment; a comment keeps its newlines for the line count.
@@ -36,7 +37,8 @@ const matches = (file, text, patterns) => patterns.flatMap(([pattern, problem])
36
37
  const fileFindings = (file, text) => {
37
38
  const kept = text.replace(TOKENS, (t) => (t.startsWith('/') ? t.replace(/[^\n]/g, '') : t));
38
39
  const code = kept.replace(QUOTED, (s) => (/\s/.test(s) ? "''" : s));
39
- return [...matches(file, code, ON_CODE), ...matches(file, kept, ON_STRINGS)];
40
+ const found = [...matches(file, code, ON_CODE), ...matches(file, kept, ON_STRINGS)];
41
+ return [...found, ...crossPartImports(file, kept)];
40
42
  };
41
43
  const LINKED = 'is a symlink: part code is plain files';
42
44
  // Every non-test source under src/; any symlink met is refused, since it could point anywhere.
@@ -1,2 +1,6 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ import { type McpSnapshot } from '../../mcp/snapshot.js';
3
+ import { type McpContext } from '../../mcp/tools.js';
1
4
  import { type CheckRule } from '../check.js';
5
+ export declare const generatedMcp: (create: (ctx: McpContext) => unknown, pkg: ExtensionPackage) => Promise<McpSnapshot>;
2
6
  export declare const surface: CheckRule;
@@ -1,13 +1,15 @@
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';
6
+ import {} from '../../manifest/manifest.schema.js';
5
7
  import { normalizeParts } from '../../manifest/parts.js';
6
8
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
7
9
  import { canonical } from '../../mcp/snapshot.js';
8
10
  import { prefixed } from '../../mcp/tools.js';
9
11
  import {} from '../check.js';
10
- import { recordingContext, registeredTools } from '../record-extras.js';
12
+ import { registeredRoutes, registeredTools } from '../record-extras.js';
11
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])));
12
14
  const routeKeys = ({ path, stack }) => [path].flat().flatMap((one) => {
13
15
  const at = `/api/v1${String(one).replace(/:(\w+)/g, '{$1}')}`;
@@ -27,6 +29,11 @@ const METHODS = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'pat
27
29
  const operations = (doc) => Object.entries((doc['paths'] ?? {})).flatMap(([path, ops]) => Object.entries(ops ?? {})
28
30
  .filter(([method]) => METHODS.has(method))
29
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
+ };
30
37
  const declaresAccess = (security) => Array.isArray(security) &&
31
38
  (security.length === 0 ||
32
39
  security.some((need) => Object.values(need ?? {}).some((s) => s.length > 0)));
@@ -42,17 +49,28 @@ const apiProblems = (doc, routes, version) => {
42
49
  ...open.map(([key]) => `${key} declares neither a scope nor security: []`),
43
50
  ];
44
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'];
45
63
  const apiSurface = async ({ dir, pkg }) => {
46
64
  const create = await loadCreate(dir, pkg, 'api').catch(() => null);
47
65
  if (!create)
48
66
  return [];
67
+ const { routes, returned } = await registeredRoutes(create, pkg);
49
68
  const doc = await readOpenapi(dir);
50
- const found = doc
51
- ? apiProblems(doc, servedRoutes(await create(recordingContext(pkg, 'api'))), pkg.version)
52
- : ['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);
53
72
  return found.map((problem) => ({ file: OPENAPI_FILE, problem }));
54
73
  };
55
- const schemaOf = (zod, io) => zod['~standard'].jsonSchema[io]({ target: 'draft-2020-12' });
56
74
  const listed = (id, { name, spec }) => ({
57
75
  name: prefixed(id, name),
58
76
  description: spec.description,
@@ -63,18 +81,21 @@ const byName = ({ serverInfo, tools }) => ({
63
81
  serverInfo,
64
82
  ...Object.fromEntries(tools.map((tool) => [String(tool['name']), tool])),
65
83
  });
84
+ // The tool list the mcp part serves, generated from its code: what {id}.mcpc.json must hold.
85
+ export const generatedMcp = async (create, pkg) => {
86
+ const { id } = pkg.agentage;
87
+ const tools = (await registeredTools(create, pkg)).map((tool) => listed(id, tool));
88
+ return { serverInfo: { name: `agentage-${id}`, version: pkg.version }, tools };
89
+ };
66
90
  const mcpSurface = async ({ dir, pkg }) => {
67
91
  const create = await loadCreate(dir, pkg, 'mcp').catch(() => null);
68
92
  if (!create)
69
93
  return [];
70
- const { id } = pkg.agentage;
71
- const file = `${id}.mcpc.json`;
94
+ const file = `${pkg.agentage.id}.mcpc.json`;
72
95
  const committed = (await readJsonIfExists(join(dir, file)));
73
96
  if (!committed)
74
97
  return [{ file, problem: 'is missing: the mcp part commits its tool list' }];
75
- const tools = (await registeredTools(create, pkg)).map((tool) => listed(id, tool));
76
- const serverInfo = { name: `agentage-${id}`, version: pkg.version };
77
- const diff = differing(byName({ serverInfo, tools }), byName(committed));
98
+ const diff = differing(byName(await generatedMcp(create, pkg)), byName(committed));
78
99
  const problem = `differs from the generated tool list (${diff.join(', ')})`;
79
100
  return diff.length > 0 ? [{ file, problem }] : [];
80
101
  };
@@ -0,0 +1,3 @@
1
+ import { type Run } from '../exec.js';
2
+ import { type ComposeTarget } from './compose-run.js';
3
+ export declare const assertHealthBodies: (run: Run, target: ComposeTarget, parts: string[], commit: string) => Promise<[part: string, checks: string][]>;
@@ -0,0 +1,40 @@
1
+ import {} from '../exec.js';
2
+ import { compose } from './compose-run.js';
3
+ import { PART_PORT } from './gateway.js';
4
+ // Inside the container: parts publish no host port, and the image always has node.
5
+ const FETCH = `fetch('http://127.0.0.1:${PART_PORT}/health').then(async (r) => process.stdout.write(await r.text()))`;
6
+ const dataOf = (text) => {
7
+ try {
8
+ return JSON.parse(text).data;
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ };
14
+ // 200 ok or degraded is an answering part (the /health standard); only unavailable fails.
15
+ const wants = (part, commit) => [
16
+ ['status', (v) => v === 'ok' || v === 'degraded', 'ok or degraded'],
17
+ ['commit', (v) => v === commit, commit],
18
+ ['part', (v) => v === part, part],
19
+ ];
20
+ // The first field that differs from the build, as one FAIL line.
21
+ const mismatch = (part, commit, data, text) => {
22
+ if (!data)
23
+ return `FAIL ${part} /health body is not the health envelope: ${text.slice(0, 120)}`;
24
+ const bad = wants(part, commit).find(([field, fits]) => !fits(data[field]));
25
+ return bad && `FAIL ${part} /health ${bad[0]} ${String(data[bad[0]])}, needs ${bad[2]}`;
26
+ };
27
+ const notOk = (data) => Object.entries(Object(data['checks']))
28
+ .filter(([, status]) => status !== 'ok')
29
+ .map(([name, status]) => `${name} ${String(status)}`)
30
+ .join(' · ');
31
+ // Docker's healthy only says the probe answered; the body must name this build and this part.
32
+ export const assertHealthBodies = async (run, target, parts, commit) => {
33
+ const read = parts.map((part) => compose(run, target, ['exec', '-T', part, 'node', '-e', FETCH]));
34
+ const bodies = await Promise.all(read);
35
+ const data = bodies.map(dataOf);
36
+ const failed = parts.flatMap((part, i) => mismatch(part, commit, data[i], bodies[i] ?? '') ?? []);
37
+ if (failed.length > 0)
38
+ throw new Error(failed.join('\n'));
39
+ return parts.flatMap((part, i) => data[i]?.['status'] === 'degraded' ? [[part, notOk(data[i])]] : []);
40
+ };
@@ -17,6 +17,7 @@ import { assertPortsFree } from './ports.js';
17
17
  import { writeUpSecrets } from './secrets.js';
18
18
  import { projectName, workingCopy } from './project.js';
19
19
  import { storePhrase, summaryOf } from './store-line.js';
20
+ import { assertHealthBodies } from './health.js';
20
21
  import { waitHealthy } from './wait.js';
21
22
  const GATEWAY = `http://localhost:${GATEWAY_PORT}`;
22
23
  const jsonFile = (file, value) => writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
@@ -37,6 +38,7 @@ const buildStep = async (s, env) => {
37
38
  assertDiscoverable(record, GATEWAY);
38
39
  s.line('record', `${LOCAL_DIR}/record.json`, 'discovery valid');
39
40
  await renderFiles(s, file, Object.fromEntries(built.images.map((i) => [i.part, i.tag])));
41
+ return built.commit;
40
42
  };
41
43
  // The migrate job runs before any part starts; a kept volume reports what it already had.
42
44
  const storeStep = async (s) => {
@@ -52,9 +54,12 @@ const storeStep = async (s) => {
52
54
  export const routesOf = (pkg) => Object.keys(PART_PATHS)
53
55
  .filter((part) => imageParts(pkg).includes(part))
54
56
  .map((part) => partPath(part, pkg.version));
55
- const partsStep = async (s) => {
57
+ const partsStep = async (s, commit) => {
56
58
  await compose(s.deps.run, s.target, ['up', '-d', '--remove-orphans'], TIMEOUTS.start);
57
59
  await waitHealthy(s.target, [...imageParts(s.pkg), 'gateway', 'issuer'], s.deps);
60
+ const degraded = await assertHealthBodies(s.deps.run, s.target, imageParts(s.pkg), commit);
61
+ for (const [part, checks] of degraded)
62
+ s.line('degraded', part, checks);
58
63
  s.line('issuer', 'dev tokens', `http://localhost:${ISSUER_PORT}`);
59
64
  s.line('gateway', GATEWAY, routesOf(s.pkg).join(' · '));
60
65
  };
@@ -74,12 +79,12 @@ export const up = async (options = {}, deps = { run: runCommand }) => {
74
79
  const started = Date.now();
75
80
  const s = await sessionOf(options, deps);
76
81
  await assertPortsFree(s.deps.run, s.target.project);
77
- await buildStep(s, options.env ?? process.env);
82
+ const commit = await buildStep(s, options.env ?? process.env);
78
83
  // Again after the build: another up may have started meanwhile, and the store comes next.
79
84
  await assertPortsFree(s.deps.run, s.target.project);
80
85
  if (hasStore(s.pkg, 'postgres'))
81
86
  await storeStep(s);
82
- await partsStep(s);
87
+ await partsStep(s, commit);
83
88
  const parts = imageParts(s.pkg).length + (hasStore(s.pkg, 'postgres') ? 1 : 0) + cliParts(s.pkg);
84
89
  const seconds = Math.round((Date.now() - started) / 1000);
85
90
  s.line('ready', `${plural(parts, 'part')} healthy`, `${seconds} s`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.5.0",
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",