@agentage/extension 0.6.0 → 0.7.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 (39) hide show
  1. package/dist/api/openapi-doc.js +55 -19
  2. package/dist/api/page.d.ts +14 -0
  3. package/dist/api/page.js +33 -0
  4. package/dist/api/routes.d.ts +18 -8
  5. package/dist/api/routes.js +4 -2
  6. package/dist/api/well-known.d.ts +13 -0
  7. package/dist/api/well-known.js +13 -0
  8. package/dist/auth/token-check.d.ts +1 -1
  9. package/dist/auth/token-check.js +8 -4
  10. package/dist/auth/verify-token.d.ts +2 -1
  11. package/dist/auth/verify-token.js +3 -2
  12. package/dist/context/secrets.js +9 -3
  13. package/dist/context/test-context.d.ts +2 -0
  14. package/dist/context/test-context.js +1 -0
  15. package/dist/envelope/envelope.d.ts +12 -0
  16. package/dist/envelope/envelope.js +8 -0
  17. package/dist/index.d.ts +3 -1
  18. package/dist/index.js +3 -1
  19. package/dist/mcp/tools.d.ts +1 -1
  20. package/dist/pages/pages-app.d.ts +3 -0
  21. package/dist/pages/pages-app.js +28 -3
  22. package/dist/runtime/part-runners.js +4 -4
  23. package/dist/server/api-routes.d.ts +2 -0
  24. package/dist/server/api-routes.js +14 -7
  25. package/dist/server/app.d.ts +2 -0
  26. package/dist/server/app.js +12 -0
  27. package/dist/store/kit-migrations.d.ts +7 -0
  28. package/dist/store/kit-migrations.js +18 -0
  29. package/dist/store/migrations.js +14 -6
  30. package/dist/testing/test-caller.d.ts +2 -0
  31. package/dist/testing/test-caller.js +13 -0
  32. package/dist/testing/test-server.d.ts +2 -0
  33. package/dist/testing/test-server.js +15 -4
  34. package/dist/tool/contracts.js +13 -2
  35. package/dist/tool/record-extras.js +2 -1
  36. package/dist/tool/up/health.js +7 -1
  37. package/dist/worker/runs.d.ts +0 -1
  38. package/dist/worker/runs.js +3 -10
  39. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { scopeOf } from '../auth/token-check.js';
2
+ import {} from '../envelope/codes.js';
2
3
  import { ErrorEnvelopeSchema } from '../envelope/envelope.schema.js';
3
4
  import {} from '../manifest/manifest.schema.js';
4
5
  import {} from './routes.js';
@@ -11,44 +12,76 @@ const bare = (zod, io) => {
11
12
  };
12
13
  const json = (schema) => ({ 'application/json': { schema } });
13
14
  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'],
15
+ const STRING = { type: 'string' };
16
+ const okResponse = ({ output, etag }) => ({
17
+ ...content('the envelope', {
18
+ type: 'object',
19
+ properties: {
20
+ success: { type: 'boolean', const: true },
21
+ data: output ? bare(output, 'output') : {},
22
+ },
23
+ required: ['success', 'data'],
24
+ }),
25
+ ...(etag && { headers: { ETag: { schema: STRING } } }),
21
26
  });
22
- const INVALID = content('VALIDATION_ERROR', bare(ErrorEnvelopeSchema, 'input'));
27
+ const refusal = (code) => content(code, { $ref: '#/components/schemas/Error' });
23
28
  const inQuery = ({ method }) => method === 'get' || method === 'delete';
24
- const parameters = (entry) => {
25
- const path = [...entry.path.matchAll(/\{(\w+)\}/g)].map(([, name]) => ({
29
+ const fields = (zod) => bare(zod, 'input');
30
+ const pathParameters = ({ path, spec }) => {
31
+ const typed = spec.params ? (fields(spec.params).properties ?? {}) : {};
32
+ return [...path.matchAll(/\{(\w+)\}/g)].map(([, name = '']) => ({
26
33
  name,
27
34
  in: 'path',
28
35
  required: true,
29
- schema: { type: 'string' },
36
+ schema: typed[name] ?? STRING,
30
37
  }));
38
+ };
39
+ const queryParameters = (entry) => {
31
40
  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]) => ({
41
+ return [];
42
+ const { properties = {}, required = [] } = fields(entry.spec.input);
43
+ return Object.entries(properties).map(([name, schema]) => ({
35
44
  name,
36
45
  in: 'query',
37
46
  required: required.includes(name),
38
47
  schema,
39
48
  }));
40
- return [...path, ...query];
49
+ };
50
+ const IF_MATCH = { name: 'If-Match', in: 'header', required: false, schema: STRING };
51
+ const parameters = (entry) => [
52
+ ...pathParameters(entry),
53
+ ...queryParameters(entry),
54
+ ...(entry.spec.etag ? [IF_MATCH] : []),
55
+ ];
56
+ const responses = (entry) => {
57
+ const { input, params, scope, etag } = entry.spec;
58
+ return {
59
+ '200': okResponse(entry.spec),
60
+ ...((input || params) && { '400': refusal('VALIDATION_ERROR') }),
61
+ ...(scope !== 'public' && { '401': refusal('UNAUTHORIZED'), '403': refusal('FORBIDDEN') }),
62
+ ...(entry.path.includes('{') && { '404': refusal('NOT_FOUND') }),
63
+ // If-Match absent on a PUT overwrites (no 428); only a stale tag is refused.
64
+ ...(etag && { '412': refusal('PRECONDITION_FAILED') }),
65
+ };
66
+ };
67
+ const securityOf = (id, scope) => {
68
+ if (scope === 'public')
69
+ return [];
70
+ // The empty requirement lets a call through anonymous; a bearer sent must grant read.
71
+ if (scope === 'optional')
72
+ return [{}, { pat: [scopeOf(id, 'read')] }];
73
+ return [{ pat: [scopeOf(id, scope)] }];
41
74
  };
42
75
  const operation = (id, entry) => {
43
- const { summary, scope, input, output } = entry.spec;
76
+ const { summary, scope, input } = entry.spec;
44
77
  const params = parameters(entry);
45
78
  return {
46
79
  summary,
47
- security: scope === 'public' ? [] : [{ pat: [scopeOf(id, scope)] }],
80
+ security: securityOf(id, scope),
48
81
  ...(params.length > 0 && { parameters: params }),
49
82
  ...(input &&
50
83
  !inQuery(entry) && { requestBody: { required: true, content: json(bare(input, 'input')) } }),
51
- responses: { '200': okResponse(output), ...(input && { '400': INVALID }) },
84
+ responses: responses(entry),
52
85
  };
53
86
  };
54
87
  // The api's contract from its ctx.route declarations: what openapi.json must hold.
@@ -62,7 +95,10 @@ export const generatedOpenapi = (pkg, routes) => {
62
95
  return {
63
96
  openapi: '3.1.0',
64
97
  info: { title: id, version: pkg.version },
65
- components: { securitySchemes: { pat: { type: 'http', scheme: 'bearer' } } },
98
+ components: {
99
+ securitySchemes: { pat: { type: 'http', scheme: 'bearer' } },
100
+ schemas: { Error: bare(ErrorEnvelopeSchema, 'input') },
101
+ },
66
102
  paths,
67
103
  };
68
104
  };
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+ import { type Reply } from '../envelope/envelope.js';
3
+ export declare const MAX_LIMIT = 200;
4
+ export declare const PageQuerySchema: z.ZodObject<{
5
+ cursor: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
6
+ limit: z.ZodPipe<z.ZodDefault<z.ZodCoercedNumber<unknown>>, z.ZodTransform<number, number>>;
7
+ }, z.core.$strip>;
8
+ export interface Pagination {
9
+ limit: number;
10
+ nextCursor?: string;
11
+ }
12
+ export declare const pageOf: <T extends {
13
+ id: string | number;
14
+ }>(rows: readonly T[], limit: number) => Reply<T[]>;
@@ -0,0 +1,33 @@
1
+ import { z } from 'zod';
2
+ import { reply } from '../envelope/envelope.js';
3
+ // api-standards section 3: default 50, a limit above 200 is clamped, not refused.
4
+ export const MAX_LIMIT = 200;
5
+ const encode = (id) => Buffer.from(id).toString('base64url');
6
+ // The cursor is the last row's id, opaque on the wire; parsed back to that id here.
7
+ const CursorSchema = z
8
+ .string()
9
+ .regex(/^[A-Za-z0-9_-]{1,256}$/)
10
+ .transform((cursor, ctx) => {
11
+ const id = Buffer.from(cursor, 'base64url').toString();
12
+ if (id && encode(id) === cursor)
13
+ return id;
14
+ ctx.issues.push({ code: 'custom', message: 'Invalid cursor', input: cursor });
15
+ return z.NEVER;
16
+ });
17
+ export const PageQuerySchema = z.object({
18
+ cursor: CursorSchema.optional(),
19
+ limit: z.coerce
20
+ .number()
21
+ .int()
22
+ .min(1)
23
+ .default(50)
24
+ .describe(`page size; a limit above ${MAX_LIMIT} is clamped to ${MAX_LIMIT}`)
25
+ .transform((limit) => Math.min(limit, MAX_LIMIT)),
26
+ });
27
+ // rows: up to limit + 1 read after the cursor; the extra row says a next page exists.
28
+ export const pageOf = (rows, limit) => {
29
+ const items = rows.slice(0, limit);
30
+ const last = rows.length > limit ? items.at(-1) : undefined;
31
+ const pagination = { limit, ...(last && { nextCursor: encode(String(last.id)) }) };
32
+ return reply(items, { meta: { pagination } });
33
+ };
@@ -1,35 +1,45 @@
1
1
  import { type z } from 'zod';
2
2
  import { type Access, type Caller } from '../auth/token-check.js';
3
3
  import { type PartContext } from '../context/context.js';
4
+ import { type Reply } from '../envelope/envelope.js';
5
+ import { type WellKnownRegistrar } from './well-known.js';
4
6
  export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
5
7
  export type RouteMethod = (typeof ROUTE_METHODS)[number];
6
8
  type ObjectSchema = z.ZodObject;
7
- export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extends Access = Access> {
9
+ export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extends Access = Access, Q extends ObjectSchema = never> {
8
10
  summary: string;
9
11
  scope?: S;
10
12
  input?: I;
11
13
  output?: O;
14
+ params?: Q;
15
+ etag?: true;
12
16
  }
13
17
  export type ParamsOf<P extends string> = P extends `${string}{${infer N}}${infer R}` ? {
14
18
  [K in N]: string;
15
19
  } & ParamsOf<R> : Record<never, string>;
16
- export interface RouteRequest<I, P extends string, S extends Access = Access> {
20
+ export interface RouteRequest<I, P extends string, S extends Access = Access, Q = never> {
17
21
  input: I;
18
- params: ParamsOf<P>;
19
- caller: S extends 'public' ? Caller | null : Caller;
22
+ params: [Q] extends [never] ? ParamsOf<P> : Q;
23
+ caller: S extends 'public' | 'optional' ? Caller | null : Caller;
24
+ ifMatch?: string;
20
25
  }
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;
26
+ type Answer<T> = T | Reply<T>;
27
+ export type RouteHandler<I extends ObjectSchema, O extends z.ZodType, P extends string, S extends Access = Access, Q extends ObjectSchema = never> = (request: RouteRequest<z.output<I>, P, S, [Q] extends [never] ? never : z.output<Q>>) => Answer<z.input<O>> | Promise<Answer<z.input<O>>>;
28
+ 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', Q extends ObjectSchema = never>(method: RouteMethod, path: P, spec: RouteSpec<I, O, S, Q>, handler: RouteHandler<I, O, P, S, Q>) => void;
23
29
  export interface ApiContext extends PartContext {
24
30
  readonly route: RouteRegistrar;
31
+ readonly wellKnown: WellKnownRegistrar;
25
32
  }
33
+ type Params = Record<string, unknown>;
26
34
  export interface RouteEntry {
27
35
  method: RouteMethod;
28
36
  path: string;
29
- spec: RouteSpec<ObjectSchema, z.ZodType>;
30
- handler: (request: RouteRequest<Record<string, unknown>, string, 'public'>) => unknown;
37
+ spec: RouteSpec<ObjectSchema, z.ZodType, Access, ObjectSchema>;
38
+ handler: (request: RouteRequest<Record<string, unknown>, string, 'public', Params>) => unknown;
31
39
  }
32
40
  export declare const createRouteRegistry: () => {
41
+ wellKnown: WellKnownRegistrar;
42
+ documents: import("./well-known.js").WellKnownEntry[];
33
43
  route: RouteRegistrar;
34
44
  routes: RouteEntry[];
35
45
  };
@@ -1,9 +1,11 @@
1
1
  import {} from 'zod';
2
2
  import {} from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
+ import {} from '../envelope/envelope.js';
5
+ import { createWellKnownRegistry } from './well-known.js';
4
6
  export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
5
7
  const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
6
- const SCOPES = ['public', 'read', 'write', 'admin'];
8
+ const SCOPES = ['public', 'optional', 'read', 'write', 'admin'];
7
9
  const problemOf = (routes, { method, path, spec }) => {
8
10
  if (!ROUTE_METHODS.includes(method))
9
11
  return `method ${String(method)}: one of get, post, put, patch, delete`;
@@ -26,5 +28,5 @@ export const createRouteRegistry = () => {
26
28
  throw new Error(`route ${String(method).toUpperCase()} ${path} ${problem}`);
27
29
  routes.push(entry);
28
30
  };
29
- return { route, routes };
31
+ return { route, routes, ...createWellKnownRegistry() };
30
32
  };
@@ -0,0 +1,13 @@
1
+ export declare const WELL_KNOWN: readonly ["agentage.json", "mcp-registry-auth"];
2
+ export type WellKnownName = (typeof WELL_KNOWN)[number];
3
+ export type WellKnownDoc = Record<string, unknown> | string;
4
+ export type WellKnownRender = () => WellKnownDoc | Promise<WellKnownDoc>;
5
+ export type WellKnownRegistrar = (name: WellKnownName, render: WellKnownRender) => void;
6
+ export interface WellKnownEntry {
7
+ name: WellKnownName;
8
+ render: WellKnownRender;
9
+ }
10
+ export declare const createWellKnownRegistry: () => {
11
+ wellKnown: WellKnownRegistrar;
12
+ documents: WellKnownEntry[];
13
+ };
@@ -0,0 +1,13 @@
1
+ // api-standards section 1: the closed names an api part may serve under /.well-known/.
2
+ export const WELL_KNOWN = ['agentage.json', 'mcp-registry-auth'];
3
+ export const createWellKnownRegistry = () => {
4
+ const documents = [];
5
+ const wellKnown = (name, render) => {
6
+ if (!WELL_KNOWN.includes(name))
7
+ throw new Error(`well-known ${String(name)}: one of ${WELL_KNOWN.join(', ')}`);
8
+ if (documents.some((entry) => entry.name === name))
9
+ throw new Error(`well-known ${name} is registered twice`);
10
+ documents.push({ name, render });
11
+ };
12
+ return { wellKnown, documents };
13
+ };
@@ -1,4 +1,4 @@
1
- export type Access = 'public' | 'read' | 'write' | 'admin';
1
+ export type Access = 'public' | 'optional' | 'read' | 'write' | 'admin';
2
2
  export interface Caller {
3
3
  sub: string;
4
4
  scopes: readonly string[];
@@ -2,19 +2,23 @@ import { setTimeout as sleep } from 'node:timers/promises';
2
2
  const callers = new WeakMap();
3
3
  export const setCaller = (request, caller) => void callers.set(request, caller);
4
4
  export const callerOf = (request) => callers.get(request) ?? null;
5
- export const RANK = { public: 0, read: 1, write: 2, admin: 3 };
6
- export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access}`;
5
+ export const RANK = { public: 0, optional: 1, read: 2, write: 3, admin: 4 };
6
+ export const scopeOf = (id, access = 'read') => access === 'public' ? 'public' : `${id}:${access === 'optional' ? 'read' : access}`;
7
7
  export const strongest = (needed) => needed.reduce((top, access) => (RANK[access] > RANK[top] ? access : top), 'public');
8
8
  const VERB = /:(read|write|admin)$/;
9
- // OpenAPI security: [] is public, a scope names the verb; a route that declares nothing needs read.
9
+ const isAnonymous = (requirement) => typeof requirement === 'object' && requirement !== null && Object.keys(requirement).length === 0;
10
+ // OpenAPI security: [] is public, [{}, {pat}] optional, a scope names the verb; nothing declared needs read.
10
11
  export const accessOfSecurity = (security) => {
11
12
  if (Array.isArray(security) && security.length === 0)
12
13
  return 'public';
13
- const scopes = (Array.isArray(security) ? security : [])
14
+ const requirements = Array.isArray(security) ? security : [];
15
+ const scopes = requirements
14
16
  .flatMap((requirement) => Object.values(requirement ?? {}))
15
17
  .flat()
16
18
  .filter((scope) => typeof scope === 'string');
17
19
  const verbs = scopes.map((scope) => VERB.exec(scope)?.[1] ?? 'read');
20
+ if (requirements.some(isAnonymous))
21
+ return verbs.length === 0 ? 'public' : 'optional';
18
22
  return verbs.length === 0 ? 'read' : strongest(verbs);
19
23
  };
20
24
  // security.md: a failed read of the issuer is tried once more before it counts as an outage.
@@ -1,5 +1,5 @@
1
1
  import { type JWTVerifyGetKey } from 'jose';
2
- import { type TokenCheck } from './token-check.js';
2
+ import { type Access, type TokenCheck } from './token-check.js';
3
3
  export interface TokenCheckDeps {
4
4
  issuer: string;
5
5
  audience: string;
@@ -16,4 +16,5 @@ export declare const remoteKeys: (issuer: string) => {
16
16
  read: () => Promise<void>;
17
17
  held: () => boolean;
18
18
  };
19
+ export declare const grants: (scope: string, id: string, access: Access) => boolean;
19
20
  export declare const createTokenCheck: (deps: TokenCheckDeps) => TokenCheck;
@@ -49,12 +49,13 @@ const claimsOf = async (authorization, deps) => {
49
49
  throw invalid(deps.origin);
50
50
  return claims.data;
51
51
  };
52
- const grants = (scope, id, access) => {
52
+ export const grants = (scope, id, access) => {
53
53
  const held = new Set(scope.split(' '));
54
54
  return ['read', 'write', 'admin'].some((verb) => RANK[verb] >= RANK[access] && held.has(`${id}:${verb}`));
55
55
  };
56
56
  export const createTokenCheck = (deps) => async (authorization, access) => {
57
- if (access === 'public')
57
+ // optional: no bearer is anonymous, but a bearer sent is checked like read, never ignored.
58
+ if (access === 'public' || (access === 'optional' && !authorization))
58
59
  return null;
59
60
  if (!authorization)
60
61
  throw invalid(deps.origin, 'Missing token');
@@ -2,14 +2,20 @@ import { readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  export const SECRETS_DIR = '/run/secrets';
4
4
  export const camelName = (name) => name.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
5
- const valueOf = (file) => readFile(file, 'utf8').then((text) => text.replace(/\r?\n$/, ''), () => '');
5
+ // Only a missing file reads as no value; any other error stops the part with its code.
6
+ const valueOf = (file, refused) => readFile(file, 'utf8').then((text) => text.replace(/\r?\n$/, ''), (err) => {
7
+ if (err.code === 'ENOENT')
8
+ return '';
9
+ throw new Error(`${refused} cannot be read: ${err.code ?? 'unknown'}`);
10
+ });
6
11
  // Each declared name from its mounted file; a missing or empty file stops the part, named, never valued.
7
12
  export const readSecrets = async (names, dir, part) => {
8
- const read = names.map(async (name) => [name, await valueOf(join(dir, name))]);
13
+ const refused = (name) => `${part} refused to start: secret ${name}`;
14
+ const read = names.map(async (name) => [name, await valueOf(join(dir, name), refused(name))]);
9
15
  const pairs = await Promise.all(read);
10
16
  const missing = pairs.find(([, value]) => value === '');
11
17
  if (missing)
12
- throw new Error(`${part} refused to start: secret ${missing[0]} has no value`);
18
+ throw new Error(`${refused(missing[0])} has no value`);
13
19
  const secrets = Object.fromEntries(pairs.map(([name, value]) => [camelName(name), value]));
14
20
  return Object.freeze(secrets);
15
21
  };
@@ -1,4 +1,5 @@
1
1
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
+ import { type WellKnownRegistrar } from '../api/well-known.js';
2
3
  import { type CliContext } from '../command/command.types.js';
3
4
  import { type LogFields, type LogLevel } from '../log/log.js';
4
5
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
@@ -20,6 +21,7 @@ export interface TestContext extends PartContext {
20
21
  readonly tools: ToolEntry[];
21
22
  readonly route: RouteRegistrar;
22
23
  readonly routes: RouteEntry[];
24
+ readonly wellKnown: WellKnownRegistrar;
23
25
  readonly jobs: ScheduledJob[];
24
26
  runJob(name: string): Promise<JobRun | undefined>;
25
27
  }
@@ -1,4 +1,5 @@
1
1
  import { createRouteRegistry } from '../api/routes.js';
2
+ import {} from '../api/well-known.js';
2
3
  import {} from '../command/command.types.js';
3
4
  import { createOut } from '../command/out.js';
4
5
  import { messageOf } from '../log/log.js';
@@ -30,7 +30,19 @@ export interface FailOptions {
30
30
  retryAfter?: number;
31
31
  headers?: Record<string, string>;
32
32
  }
33
+ declare const REPLY: unique symbol;
34
+ export interface ReplyOptions {
35
+ meta?: Record<string, unknown>;
36
+ etag?: string;
37
+ }
38
+ export interface Reply<T> extends ReplyOptions {
39
+ readonly [REPLY]: true;
40
+ data: T;
41
+ }
42
+ export declare const reply: <T>(data: T, options?: ReplyOptions) => Reply<T>;
43
+ export declare const isReply: (value: unknown) => value is Reply<unknown>;
33
44
  export declare const ok: <T>(data: T, meta?: Record<string, unknown>) => OkEnvelope<T>;
34
45
  export declare const fail: (code: ErrorCode, message: string, options?: FailOptions) => Failure;
35
46
  export declare const isFailure: (err: unknown) => err is Failure;
36
47
  export declare const errorEnvelope: (failure: Failure, agcid: string) => ErrorEnvelope;
48
+ export {};
@@ -1,6 +1,14 @@
1
1
  import { DEFAULT_RETRY_AFTER_SECONDS, ERROR_STATUS, RETRY_AFTER_CODES, } from './codes.js';
2
2
  // A registry symbol, so a failure thrown through a second copy of the kit is still recognised.
3
3
  const FAILURE = Symbol.for('agentage.extension.failure');
4
+ const REPLY = Symbol.for('agentage.extension.reply');
5
+ // What a route returns when it answers with meta or an ETag; bare data stays the short form.
6
+ export const reply = (data, options = {}) => ({
7
+ [REPLY]: true,
8
+ data,
9
+ ...options,
10
+ });
11
+ export const isReply = (value) => typeof value === 'object' && value !== null && value[REPLY] === true;
4
12
  export const ok = (data, meta) => meta === undefined ? { success: true, data } : { success: true, data, meta };
5
13
  const retryAfterOf = (code, given) => {
6
14
  if (given !== undefined)
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { type ApiContext, type ParamsOf, type RouteHandler, type RouteMethod, type RouteRegistrar, type RouteRequest, type RouteSpec, } from './api/routes.js';
2
+ export { pageOf, PageQuerySchema, type Pagination } from './api/page.js';
3
+ export { type Access, type Caller } from './auth/token-check.js';
2
4
  export { type ArgValue } from './command/args.js';
3
5
  export { type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
4
6
  export { type Out } from './command/out.js';
@@ -8,7 +10,7 @@ export { createTestContext, type LogEntry, type ScheduledJob, type TestCommandCo
8
10
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from './discovery/discovery.schema.js';
9
11
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
10
12
  export { ERROR_CODES, ERROR_STATUS, type ErrorCode } from './envelope/codes.js';
11
- export { fail, isFailure, ok, type ErrorDetail, type ErrorEnvelope, type Failure, type FailOptions, type OkEnvelope, } from './envelope/envelope.js';
13
+ export { fail, isFailure, ok, reply, type ErrorDetail, type ErrorEnvelope, type Failure, type FailOptions, type OkEnvelope, type Reply, type ReplyOptions, } from './envelope/envelope.js';
12
14
  export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schema.js';
13
15
  export { parse, type ParseSchema } from './envelope/parse.js';
14
16
  export { HealthSchema, type HealthBody, type HealthStatus } from './health/health.schema.js';
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export {} from './api/routes.js';
2
+ export { pageOf, PageQuerySchema } from './api/page.js';
3
+ export {} from './auth/token-check.js';
2
4
  export {} from './command/args.js';
3
5
  export {} from './command/command.types.js';
4
6
  export {} from './command/out.js';
@@ -8,7 +10,7 @@ export { createTestContext, } from './context/test-context.js';
8
10
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, } from './discovery/discovery.schema.js';
9
11
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
10
12
  export { ERROR_CODES, ERROR_STATUS } from './envelope/codes.js';
11
- export { fail, isFailure, ok, } from './envelope/envelope.js';
13
+ export { fail, isFailure, ok, reply, } from './envelope/envelope.js';
12
14
  export { ErrorEnvelopeSchema, OkEnvelopeSchema } from './envelope/envelope.schema.js';
13
15
  export { parse } from './envelope/parse.js';
14
16
  export { HealthSchema } from './health/health.schema.js';
@@ -6,7 +6,7 @@ export interface ToolSpec<I extends ObjectSchema, O extends ObjectSchema> {
6
6
  description: string;
7
7
  input: I;
8
8
  output: O;
9
- scope?: Access;
9
+ scope?: Exclude<Access, 'optional'>;
10
10
  }
11
11
  export type ToolHandler<I extends ObjectSchema, O extends ObjectSchema> = (args: z.output<I>) => z.input<O> | Promise<z.input<O>>;
12
12
  export type ToolRegistrar = <I extends ObjectSchema, O extends ObjectSchema>(name: string, spec: ToolSpec<I, O>, handler: ToolHandler<I, O>) => void;
@@ -1,8 +1,11 @@
1
1
  import { type Express } from 'express';
2
+ import { type Env } from '../runtime/build-info.js';
2
3
  import { type PartAppBase } from '../server/app.js';
3
4
  import { type PagesSite } from './pages.js';
4
5
  export interface PagesAppOptions extends PartAppBase {
5
6
  site: PagesSite;
7
+ platform?: string[];
6
8
  }
9
+ export declare const platformSources: (env: Env) => string[];
7
10
  export declare const NOT_FOUND_PAGE = "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><title>Not found</title></head><body><p>Not found</p></body></html>\n";
8
11
  export declare const createPagesApp: (options: PagesAppOptions) => Express;
@@ -1,26 +1,51 @@
1
+ import { extname } from 'node:path';
1
2
  import {} from 'express';
2
3
  import { z } from 'zod';
4
+ import {} from '../runtime/build-info.js';
3
5
  import { createPartApp } from '../server/app.js';
4
6
  import {} from './pages.js';
7
+ // One host (a port allowed), or *. over at least two labels: never a whole top-level domain.
8
+ const AUDIENCE = /^(\*\.[a-z0-9-]+(\.[a-z0-9-]+)+|[a-z0-9-]+(\.[a-z0-9-]+)*)(:\d+)?$/;
9
+ const WEB = ['http:', 'https:'];
10
+ const webUrl = (url) => {
11
+ const parsed = url && URL.canParse(url) ? new URL(url) : undefined;
12
+ return parsed && WEB.includes(parsed.protocol) ? parsed : undefined;
13
+ };
14
+ // A shell page talks to auth and mounts widgets from its siblings: the platform's own hosts only.
15
+ export const platformSources = (env) => {
16
+ const issuer = webUrl(env['AGENTAGE_ISSUER'])?.origin;
17
+ const scheme = webUrl(env['AGENTAGE_ORIGIN'])?.protocol ?? 'https:';
18
+ const audience = env['AGENTAGE_AUDIENCE'] ?? '';
19
+ return [issuer, AUDIENCE.test(audience) ? `${scheme}//${audience}` : undefined].filter((source) => Boolean(source));
20
+ };
21
+ const TYPES = { '.js': 'js', '.mjs': 'js', '.css': 'css', '.json': 'json' };
5
22
  const SiteSchema = z.record(z.string().regex(/^\/[A-Za-z0-9._~/-]*$/), z.string());
6
23
  export const NOT_FOUND_PAGE = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><title>Not found</title></head><body><p>Not found</p></body></html>\n';
7
24
  const serve = (site) => (req, res, next) => {
8
25
  const html = site[req.path];
9
26
  if (html === undefined)
10
27
  return next();
11
- res.type('html').setHeader('Cache-Control', 'no-cache');
28
+ res.type(TYPES[extname(req.path)] ?? 'html').setHeader('Cache-Control', 'no-cache');
12
29
  res.send(html);
13
30
  };
14
31
  const missing = (_req, res) => {
15
32
  res.status(404).type('html').send(NOT_FOUND_PAGE);
16
33
  };
17
- // Everything the gateway does not reserve comes here: a page from the site map, or an HTML 404.
34
+ // Everything the gateway does not reserve comes here: a site map entry (typed by its extension), or an HTML 404.
18
35
  export const createPagesApp = (options) => {
19
36
  const site = SiteSchema.parse(options.site);
20
37
  return createPartApp({
21
38
  ...options,
22
39
  part: 'pages',
23
- helmet: { contentSecurityPolicy: { directives: { upgradeInsecureRequests: null } } },
40
+ helmet: {
41
+ contentSecurityPolicy: {
42
+ directives: {
43
+ scriptSrc: ["'self'", ...(options.platform ?? [])],
44
+ connectSrc: ["'self'", ...(options.platform ?? [])],
45
+ upgradeInsecureRequests: null,
46
+ },
47
+ },
48
+ },
24
49
  mount: (app) => {
25
50
  app.get(/.*/, serve(site));
26
51
  app.get(/.*/, missing);
@@ -8,7 +8,7 @@ import { hasStore } from '../manifest/parts.js';
8
8
  import {} from '../manifest/primitives.schema.js';
9
9
  import { createMcpApp } from '../mcp/mcp-app.js';
10
10
  import { createToolRegistry } from '../mcp/tools.js';
11
- import { createPagesApp } from '../pages/pages-app.js';
11
+ import { createPagesApp, platformSources } from '../pages/pages-app.js';
12
12
  import { createApiApp, createPartApp } from '../server/app.js';
13
13
  import { mountApi } from '../server/api-routes.js';
14
14
  import {} from './build-info.js';
@@ -20,10 +20,10 @@ import { createScheduler } from '../worker/scheduler.js';
20
20
  const callCreate = async (input, part, ctx) => (await loadCreate(input.dir, input.pkg, part, input.importModule))(ctx);
21
21
  const api = async (input) => {
22
22
  const ctx = input.ctx();
23
- const { router, routes } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
23
+ const { router, routes, documents } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
24
24
  // Declared routes guard at their own scope, whatever the committed file says.
25
25
  const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
26
- return { app: createApiApp({ ...input.base, router, openapi }) };
26
+ return { app: createApiApp({ ...input.base, router, openapi, wellKnown: documents }) };
27
27
  };
28
28
  const mcp = async (input) => {
29
29
  const registry = createToolRegistry();
@@ -34,7 +34,7 @@ const mcp = async (input) => {
34
34
  };
35
35
  const pages = async (input) => {
36
36
  const site = (await callCreate(input, 'pages', input.ctx()));
37
- return { app: createPagesApp({ ...input.base, site }) };
37
+ return { app: createPagesApp({ ...input.base, site, platform: platformSources(input.env) }) };
38
38
  };
39
39
  const ui = async (input) => ({
40
40
  app: createUiApp({
@@ -1,7 +1,9 @@
1
1
  import { type ApiContext, type RouteEntry } from '../api/routes.js';
2
+ import { type WellKnownEntry } from '../api/well-known.js';
2
3
  import { type PartContext } from '../context/context.js';
3
4
  import { type ApiHandler } from './part.types.js';
4
5
  export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<{
5
6
  router: ApiHandler;
6
7
  routes: RouteEntry[];
8
+ documents: WellKnownEntry[];
7
9
  }>;
@@ -1,7 +1,8 @@
1
1
  import { Router } from 'express';
2
2
  import { createRouteRegistry } from '../api/routes.js';
3
+ import {} from '../api/well-known.js';
3
4
  import {} from '../context/context.js';
4
- import { ok } from '../envelope/envelope.js';
5
+ import { isReply, ok, reply } from '../envelope/envelope.js';
5
6
  import { parse } from '../envelope/parse.js';
6
7
  import {} from './part.types.js';
7
8
  const inQuery = (method) => method === 'get' || method === 'delete';
@@ -12,12 +13,18 @@ const inputOf = ({ method, spec }, query, body) => {
12
13
  return parse(spec.input, query, 'Invalid query');
13
14
  return parse(spec.input, body ?? {}, 'Invalid body');
14
15
  };
15
- // Validated in, the handler's answer parsed by its output schema and sent in the envelope.
16
+ // Validated in, the handler's data (bare or a reply) parsed by its output schema and sent in the envelope.
16
17
  const handlerOf = (ctx, entry) => async (req, res) => {
17
18
  const input = inputOf(entry, req.query, req.body);
18
19
  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));
20
+ const { params: schema } = entry.spec;
21
+ const params = schema ? parse(schema, req.params, 'Invalid path') : req.params;
22
+ const ifMatch = req.get('if-match');
23
+ const answer = await entry.handler({ input, params, caller, ifMatch });
24
+ const { data, meta, etag } = isReply(answer) ? answer : reply(answer);
25
+ if (etag)
26
+ res.setHeader('ETag', etag);
27
+ res.json(ok(entry.spec.output ? entry.spec.output.parse(data) : data, meta));
21
28
  };
22
29
  // /items/{id} as Express writes it.
23
30
  const expressPath = (path) => path.replace(/\{(\w+)\}/g, ':$1');
@@ -39,7 +46,7 @@ const handlerFor = (ctx, routes, returned) => {
39
46
  };
40
47
  // Runs the api part's create(ctx) with ctx.route; the runtime and the test server mount alike.
41
48
  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 };
49
+ const { route, routes, wellKnown, documents } = createRouteRegistry();
50
+ const returned = await create({ ...ctx, route, wellKnown });
51
+ return { router: handlerFor(ctx, routes, returned), routes, documents };
45
52
  };
@@ -1,6 +1,7 @@
1
1
  import { type CorsOptions } from 'cors';
2
2
  import { type Express } from 'express';
3
3
  import { type HelmetOptions } from 'helmet';
4
+ import { type WellKnownEntry } from '../api/well-known.js';
4
5
  import { type TokenCheck } from '../auth/token-check.js';
5
6
  import { type BuildInfo } from '../discovery/discovery.js';
6
7
  import { type ExtensionRecord } from '../discovery/discovery.schema.js';
@@ -28,6 +29,7 @@ export interface PartAppOptions extends PartAppBase {
28
29
  export interface ApiAppOptions extends PartAppBase {
29
30
  router: ApiHandler;
30
31
  openapi?: Record<string, unknown> | null;
32
+ wellKnown?: WellKnownEntry[];
31
33
  }
32
34
  export declare const PUBLIC_CORS: CorsOptions;
33
35
  export declare const BODY_LIMIT = "1mb";
@@ -1,6 +1,7 @@
1
1
  import cors, {} from 'cors';
2
2
  import express, {} from 'express';
3
3
  import helmet, {} from 'helmet';
4
+ import {} from '../api/well-known.js';
4
5
  import { agcidMiddleware } from '../agcid/scope.js';
5
6
  import { routeAccess } from '../auth/route-access.js';
6
7
  import { setCaller } from '../auth/token-check.js';
@@ -61,6 +62,15 @@ export const createPartApp = (options) => {
61
62
  };
62
63
  // The committed OpenAPI document, bare JSON and anonymous like discovery (api-standards section 1).
63
64
  const openapiHandler = (doc) => (_req, res) => void res.json(doc);
65
+ // Public like discovery, cached briefly: crawlers and registries read these from the root.
66
+ const wellKnownHandler = (render) => async (_req, res) => {
67
+ const doc = await render();
68
+ res.setHeader('Cache-Control', 'public, max-age=300');
69
+ if (typeof doc === 'string')
70
+ res.type('text/plain').send(doc);
71
+ else
72
+ res.json(doc);
73
+ };
64
74
  // Before the body is read: each request checked for the access its OpenAPI operation declares.
65
75
  const routeGuard = (options) => async (req, res, next) => {
66
76
  if (!options.tokenCheck)
@@ -77,6 +87,8 @@ export const createApiApp = (options) => createPartApp({
77
87
  part: 'api',
78
88
  mount: (app) => {
79
89
  app.use('/api/v1', cors(PUBLIC_CORS));
90
+ for (const { name, render } of options.wellKnown ?? [])
91
+ app.get(`/.well-known/${name}`, wellKnownHandler(render));
80
92
  if (options.openapi)
81
93
  app.get('/api/v1/openapi.json', openapiHandler(options.openapi));
82
94
  const json = express.json({ limit: BODY_LIMIT });
@@ -0,0 +1,7 @@
1
+ export declare const KIT_PREFIX = "kit:";
2
+ export declare const JOB_RUNS_SQL = "create table if not exists agentage_job_runs (\n id bigint generated always as identity primary key,\n job text not null,\n started_at timestamptz not null,\n ended_at timestamptz not null,\n status text not null,\n log text not null,\n timeout_ms integer\n);\nalter table agentage_job_runs add column if not exists agcid text";
3
+ export declare const KIT_MIGRATIONS: readonly {
4
+ name: string;
5
+ sql: string;
6
+ }[];
7
+ export declare const KIT_TABLES: string[];
@@ -0,0 +1,18 @@
1
+ // Applied before the extension's own files; `kit:` never matches NNN-name.sql, so no name collides.
2
+ export const KIT_PREFIX = 'kit:';
3
+ // Defensive: a store from before 0.7 already holds the table its worker created lazily.
4
+ export const JOB_RUNS_SQL = `create table if not exists agentage_job_runs (
5
+ id bigint generated always as identity primary key,
6
+ job text not null,
7
+ started_at timestamptz not null,
8
+ ended_at timestamptz not null,
9
+ status text not null,
10
+ log text not null,
11
+ timeout_ms integer
12
+ );
13
+ alter table agentage_job_runs add column if not exists agcid text`;
14
+ export const KIT_MIGRATIONS = [
15
+ { name: `${KIT_PREFIX}001-job-runs`, sql: JOB_RUNS_SQL },
16
+ ];
17
+ // The kit's own tables: a store holding only these still counts as empty and gets the seeds.
18
+ export const KIT_TABLES = ['_migrations', 'agentage_job_runs'];
@@ -1,6 +1,7 @@
1
1
  import { readdir, readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { messageOf } from '../log/log.js';
4
+ import { KIT_MIGRATIONS, KIT_PREFIX, KIT_TABLES } from './kit-migrations.js';
4
5
  import {} from './store.types.js';
5
6
  export const SQL_FILE = /^[0-9]{3}-[a-z0-9-]+\.sql$/;
6
7
  // Filename order; anything else in the folder is refused, so a typo never silently skips a file.
@@ -29,16 +30,17 @@ export const SEEDS_OWED = 'seeds:owed';
29
30
  // Tables other than the kit's own: a store holding any (a restored dump) never gets the seeds.
30
31
  const USER_TABLES = `select count(*)::int as n from information_schema.tables
31
32
  where table_schema not in ('pg_catalog', 'information_schema')
32
- and table_name not in ('_migrations', 'agentage_job_runs')`;
33
- const isEmpty = async (store, done) => done.size === 0 && ((await store.query(USER_TABLES)).rows[0]?.n ?? 0) === 0;
33
+ and table_name not in (${KIT_TABLES.map((name) => `'${name}'`).join(', ')})`;
34
+ // Kit rows alone leave a store empty: an extension that adds its first migration later still seeds.
35
+ const isEmpty = async (store, done) => [...done].every((name) => name.startsWith(KIT_PREFIX)) &&
36
+ ((await store.query(USER_TABLES)).rows[0]?.n ?? 0) === 0;
34
37
  const appliedNames = async (store) => {
35
38
  await store.query(LEDGER);
36
39
  const { rows } = await store.query('select name from _migrations');
37
40
  return new Set(rows.map((row) => row.name));
38
41
  };
39
42
  // One string, one round trip: the file and its ledger row commit together or not at all.
40
- const applyFile = async (store, file, name) => {
41
- const sql = await readFile(file, 'utf8');
43
+ const applySql = async (store, sql, name) => {
42
44
  try {
43
45
  await store.query(`begin;\n${sql}\n;insert into _migrations (name) values ('${name}');\ncommit;`);
44
46
  }
@@ -54,23 +56,29 @@ const applyAll = async (store, dir, prefix, done) => {
54
56
  const name = `${prefix}${file}`;
55
57
  if (done.has(name))
56
58
  continue;
57
- await applyFile(store, join(dir, file), name);
59
+ await applySql(store, await readFile(join(dir, file), 'utf8'), name);
58
60
  count += 1;
59
61
  }
60
62
  return count;
61
63
  };
64
+ const applyKit = async (store, done) => {
65
+ for (const { name, sql } of KIT_MIGRATIONS)
66
+ if (!done.has(name))
67
+ await applySql(store, sql, name);
68
+ };
62
69
  const seedOnce = async (store, dir, done) => {
63
70
  const seeds = await applyAll(store, join(dir, 'seeds'), SEED, done);
64
71
  await store.query(`delete from _migrations where name = '${SEEDS_OWED}'`);
65
72
  return seeds;
66
73
  };
67
- // Migrations in order, each once; seeds once, only on a store with no ledger row and no user table.
74
+ // The kit's migrations, then the extension's in order, each once; seeds once, only on a store with no ledger row and no user table.
68
75
  export const migrate = async (store, dir, log) => {
69
76
  const done = await appliedNames(store);
70
77
  const empty = await isEmpty(store, done);
71
78
  if (empty)
72
79
  await store.query(`insert into _migrations (name) values ('${SEEDS_OWED}')`);
73
80
  const owed = empty || done.has(SEEDS_OWED);
81
+ await applyKit(store, done);
74
82
  const migrations = (await sqlFiles(join(dir, 'migrations'))).length;
75
83
  const applied = await applyAll(store, join(dir, 'migrations'), '', done);
76
84
  const seeds = owed ? await seedOnce(store, dir, done) : 0;
@@ -0,0 +1,2 @@
1
+ import { type Caller, type TokenCheck } from '../auth/token-check.js';
2
+ export declare const callerCheck: (id: string, caller: Caller | null) => TokenCheck;
@@ -0,0 +1,13 @@
1
+ import { scopeOf } from '../auth/token-check.js';
2
+ import { grants } from '../auth/verify-token.js';
3
+ import { fail } from '../envelope/envelope.js';
4
+ // As if every request carried caller's token (none when null): scopes enforced, no issuer.
5
+ export const callerCheck = (id, caller) => async (_authorization, access) => {
6
+ if (access === 'public' || (access === 'optional' && !caller))
7
+ return null;
8
+ if (!caller)
9
+ throw fail('UNAUTHORIZED', 'Missing token');
10
+ if (!grants(caller.scopes.join(' '), id, access))
11
+ throw fail('FORBIDDEN', `Needs ${scopeOf(id, access)}`);
12
+ return caller;
13
+ };
@@ -1,10 +1,12 @@
1
1
  import { type ApiContext } from '../api/routes.js';
2
+ import { type Caller } from '../auth/token-check.js';
2
3
  import { type PartContext } from '../context/context.js';
3
4
  import { type McpContext } from '../mcp/tools.js';
4
5
  import { type ApiCreate } from '../server/part.types.js';
5
6
  export interface TestServerOptions<C extends PartContext> {
6
7
  create: ApiCreate<C & ApiContext>;
7
8
  ctx?: C;
9
+ caller?: Caller | null;
8
10
  }
9
11
  export interface TestMcpOptions {
10
12
  create: (ctx: McpContext) => unknown;
@@ -1,6 +1,8 @@
1
1
  import {} from 'node:net';
2
2
  import {} from 'express';
3
+ import { generatedOpenapi } from '../api/openapi-doc.js';
3
4
  import {} from '../api/routes.js';
5
+ import { callerOf } from '../auth/token-check.js';
4
6
  import {} from '../context/context.js';
5
7
  import { createTestContext } from '../context/test-context.js';
6
8
  import {} from '../manifest/manifest.schema.js';
@@ -11,11 +13,13 @@ import { mountApi } from '../server/api-routes.js';
11
13
  import { createApiApp } from '../server/app.js';
12
14
  import {} from '../server/part.types.js';
13
15
  import { listen } from '../server/serve.js';
16
+ import { KIT_VERSION } from '../tool/kit-version.js';
17
+ import { callerCheck } from './test-caller.js';
14
18
  const TEST_BUILD = { commit: '0'.repeat(40), buildTime: '2026-01-01T00:00:00Z' };
15
19
  const testPackage = (ctx, parts) => ({
16
20
  name: `@agentage/extension-${ctx.extension.id}`,
17
21
  version: ctx.extension.version,
18
- engines: { agentage: '^0.3.0' },
22
+ engines: { agentage: KIT_VERSION },
19
23
  agentage: { id: ctx.extension.id, parts },
20
24
  });
21
25
  const startOn = async (app) => {
@@ -29,10 +33,17 @@ const startOn = async (app) => {
29
33
  };
30
34
  // Runs an api part's create(ctx) inside the kit's real app on 127.0.0.1, port chosen by the OS.
31
35
  export const startTestServer = async (options) => {
32
- const ctx = options.ctx ?? createTestContext();
33
- const { router } = await mountApi(ctx, (api) => options.create({ ...ctx, ...api }));
36
+ const given = options.ctx ?? createTestContext();
37
+ const checked = options.caller !== undefined;
38
+ const ctx = checked ? { ...given, auth: { caller: callerOf } } : given;
39
+ const mounted = await mountApi(ctx, (api) => options.create({ ...ctx, ...api }));
34
40
  const pkg = testPackage(ctx, { api: true });
35
- return startOn(createApiApp({ pkg, build: TEST_BUILD, router, log: ctx.log }));
41
+ const guard = checked && {
42
+ tokenCheck: callerCheck(ctx.extension.id, options.caller ?? null),
43
+ openapi: generatedOpenapi(pkg, mounted.routes),
44
+ };
45
+ const base = { pkg, build: TEST_BUILD, log: ctx.log, wellKnown: mounted.documents };
46
+ return startOn(createApiApp({ ...base, router: mounted.router, ...guard }));
36
47
  };
37
48
  // Runs an mcp part's create(ctx) inside the kit's real /mcp app: tools named {id}__{name}.
38
49
  export const startTestMcp = async (options) => {
@@ -14,8 +14,19 @@ import { registeredRoutes } from './record-extras.js';
14
14
  import { generatedMcp } from './rules/surface.js';
15
15
  import { exists } from './stage.js';
16
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));
17
+ // Only a parse failure (a file a run left half-written) reads as different: --write replaces it.
18
+ const parsed = (text) => {
19
+ try {
20
+ return text === undefined ? undefined : JSON.parse(text);
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ const sameJson = (text, value) => {
27
+ const old = parsed(text);
28
+ return old !== undefined && JSON.stringify(canonical(old)) === JSON.stringify(canonical(value));
29
+ };
19
30
  const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
20
31
  const writeMcp = async (dir, pkg) => {
21
32
  const file = `${pkg.agentage.id}.mcpc.json`;
@@ -38,7 +38,8 @@ export const registeredTools = async (create, pkg) => {
38
38
  // What an api part's create(ctx) registers with ctx.route, and what it returns.
39
39
  export const registeredRoutes = async (create, pkg) => {
40
40
  const registry = createRouteRegistry();
41
- const returned = await create({ ...recordingContext(pkg, 'api'), route: registry.route });
41
+ const { route, wellKnown } = registry;
42
+ const returned = await create({ ...recordingContext(pkg, 'api'), route, wellKnown });
42
43
  return { routes: registry.routes, returned };
43
44
  };
44
45
  export const toolsOf = async (dir, pkg) => {
@@ -28,9 +28,15 @@ const notOk = (data) => Object.entries(Object(data['checks']))
28
28
  .filter(([, status]) => status !== 'ok')
29
29
  .map(([name, status]) => `${name} ${String(status)}`)
30
30
  .join(' · ');
31
+ // A part that gives no answer is its own FAIL line: the exit code and the command's last line.
32
+ const noAnswer = (err) => {
33
+ const code = /exit code (\d+)/.exec(err.message)?.[1];
34
+ return `no answer${code ? ` (exit ${code})` : ''}: ${err.message.split('\n').at(-1) ?? ''}`;
35
+ };
31
36
  // Docker's healthy only says the probe answered; the body must name this build and this part.
32
37
  export const assertHealthBodies = async (run, target, parts, commit) => {
33
- const read = parts.map((part) => compose(run, target, ['exec', '-T', part, 'node', '-e', FETCH]));
38
+ const exec = (part) => compose(run, target, ['exec', '-T', part, 'node', '-e', FETCH]);
39
+ const read = parts.map((part) => exec(part).catch(noAnswer));
34
40
  const bodies = await Promise.all(read);
35
41
  const data = bodies.map(dataOf);
36
42
  const failed = parts.flatMap((part, i) => mismatch(part, commit, data[i], bodies[i] ?? '') ?? []);
@@ -13,7 +13,6 @@ export interface RunStore {
13
13
  last(job: string): Promise<JobRun | undefined>;
14
14
  }
15
15
  export declare const KEEP_RUNS = 50;
16
- export declare const RUNS_TABLE = "create table if not exists agentage_job_runs (\n id bigint generated always as identity primary key,\n job text not null,\n started_at timestamptz not null,\n ended_at timestamptz not null,\n status text not null,\n log text not null,\n timeout_ms integer\n)";
17
16
  export declare const storeRuns: (store: Store) => RunStore;
18
17
  export declare const memoryRuns: () => RunStore & {
19
18
  all(job: string): JobRun[];
@@ -1,14 +1,6 @@
1
+ import { JOB_RUNS_SQL } from '../store/kit-migrations.js';
1
2
  import {} from '../store/store.types.js';
2
3
  export const KEEP_RUNS = 50;
3
- export const RUNS_TABLE = `create table if not exists agentage_job_runs (
4
- id bigint generated always as identity primary key,
5
- job text not null,
6
- started_at timestamptz not null,
7
- ended_at timestamptz not null,
8
- status text not null,
9
- log text not null,
10
- timeout_ms integer
11
- )`;
12
4
  const INSERT = `insert into agentage_job_runs (job, started_at, ended_at, status, log, timeout_ms)
13
5
  values ($1, $2, $3, $4, $5, $6)`;
14
6
  const PRUNE = `delete from agentage_job_runs where job = $1 and id not in
@@ -33,7 +25,8 @@ const valuesOf = (run) => [
33
25
  // Runs live in the extension's own store, in a table the kit owns; the last 50 per job are kept.
34
26
  export const storeRuns = (store) => {
35
27
  let table;
36
- const ready = () => (table ??= store.query(RUNS_TABLE));
28
+ // Also here: a worker-only extension has no migrate job (only the api image runs it).
29
+ const ready = () => (table ??= store.query(JOB_RUNS_SQL));
37
30
  return {
38
31
  save: async (run) => {
39
32
  await ready();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",