@agentage/extension 0.12.2 → 0.13.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 (96) hide show
  1. package/README.md +5 -0
  2. package/dist/api/openapi-doc.js +2 -1
  3. package/dist/api/routes.js +1 -1
  4. package/dist/context/context.d.ts +1 -0
  5. package/dist/context/context.js +3 -3
  6. package/dist/context/package-extension.d.ts +2 -0
  7. package/dist/context/package-extension.js +5 -4
  8. package/dist/context/secrets.d.ts +5 -2
  9. package/dist/context/secrets.js +22 -6
  10. package/dist/context/settings.d.ts +4 -0
  11. package/dist/context/settings.js +6 -5
  12. package/dist/context/test-context.js +3 -2
  13. package/dist/discovery/discovery.d.ts +1 -0
  14. package/dist/discovery/discovery.js +7 -3
  15. package/dist/discovery/discovery.schema.d.ts +6 -0
  16. package/dist/discovery/discovery.schema.js +23 -6
  17. package/dist/discovery/openapi.d.ts +2 -1
  18. package/dist/discovery/openapi.js +3 -1
  19. package/dist/host/daemon/child.d.ts +21 -0
  20. package/dist/host/daemon/child.js +92 -0
  21. package/dist/host/daemon/daemon-files.d.ts +19 -0
  22. package/dist/host/daemon/daemon-files.js +23 -0
  23. package/dist/host/daemon/daemon.d.ts +18 -0
  24. package/dist/host/daemon/daemon.js +84 -0
  25. package/dist/host/daemon/guard.d.ts +2 -0
  26. package/dist/host/daemon/guard.js +15 -0
  27. package/dist/host/daemon/installation.d.ts +23 -0
  28. package/dist/host/daemon/installation.js +48 -0
  29. package/dist/host/daemon/installer-call.d.ts +7 -0
  30. package/dist/host/daemon/installer-call.js +22 -0
  31. package/dist/host/daemon/json-file.d.ts +3 -0
  32. package/dist/host/daemon/json-file.js +51 -0
  33. package/dist/host/daemon/lane.d.ts +11 -0
  34. package/dist/host/daemon/lane.js +29 -0
  35. package/dist/host/daemon/ops.d.ts +36 -0
  36. package/dist/host/daemon/ops.js +149 -0
  37. package/dist/host/daemon/proxy.d.ts +5 -0
  38. package/dist/host/daemon/proxy.js +67 -0
  39. package/dist/host/daemon/queue.d.ts +2 -0
  40. package/dist/host/daemon/queue.js +8 -0
  41. package/dist/host/daemon/routes.d.ts +11 -0
  42. package/dist/host/daemon/routes.js +48 -0
  43. package/dist/host/daemon/secret-names.d.ts +1 -0
  44. package/dist/host/daemon/secret-names.js +14 -0
  45. package/dist/host/daemon/setting-values.d.ts +1 -0
  46. package/dist/host/daemon/setting-values.js +26 -0
  47. package/dist/host/daemon/supervisor.d.ts +52 -0
  48. package/dist/host/daemon/supervisor.js +116 -0
  49. package/dist/host/data-lock.d.ts +2 -0
  50. package/dist/host/data-lock.js +81 -0
  51. package/dist/host/host-env.d.ts +17 -0
  52. package/dist/host/host-env.js +36 -0
  53. package/dist/host/host-extension.d.ts +25 -0
  54. package/dist/host/host-extension.js +86 -0
  55. package/dist/host/host-store.d.ts +4 -0
  56. package/dist/host/host-store.js +35 -0
  57. package/dist/host/index.d.ts +3 -0
  58. package/dist/host/index.js +3 -0
  59. package/dist/host/main.d.ts +2 -0
  60. package/dist/host/main.js +10 -0
  61. package/dist/host/serve-host.d.ts +16 -0
  62. package/dist/host/serve-host.js +61 -0
  63. package/dist/manifest/manifest.schema.d.ts +9 -1
  64. package/dist/manifest/manifest.schema.js +13 -2
  65. package/dist/manifest/parts.d.ts +6 -0
  66. package/dist/manifest/parts.js +8 -0
  67. package/dist/manifest/primitives.schema.d.ts +7 -0
  68. package/dist/manifest/primitives.schema.js +2 -0
  69. package/dist/runtime/part-runners.d.ts +1 -0
  70. package/dist/runtime/part-runners.js +10 -1
  71. package/dist/runtime/run-part.js +3 -2
  72. package/dist/server/app.d.ts +4 -0
  73. package/dist/server/app.js +28 -18
  74. package/dist/server/request-line.d.ts +1 -1
  75. package/dist/server/request-line.js +4 -4
  76. package/dist/server/serve.js +11 -3
  77. package/dist/store/pglite-store.d.ts +25 -0
  78. package/dist/store/pglite-store.js +59 -0
  79. package/dist/store/test-store.d.ts +2 -3
  80. package/dist/store/test-store.js +3 -38
  81. package/dist/testing/test-server.d.ts +2 -0
  82. package/dist/testing/test-server.js +1 -1
  83. package/dist/tool/record-extras.js +2 -2
  84. package/dist/tool/rules/surface.js +6 -6
  85. package/dist/tool/up/compose.js +3 -2
  86. package/dist/tool/up/gateway.d.ts +6 -2
  87. package/dist/tool/up/gateway.js +10 -7
  88. package/dist/tool/up/local-record.d.ts +1 -0
  89. package/dist/tool/up/secrets.js +2 -1
  90. package/dist/tool/up/token.js +1 -1
  91. package/dist/tool/up/up.js +2 -2
  92. package/dist/vendor/logs/events-client.js +1 -1
  93. package/package.json +5 -1
  94. package/schemas/extension-discovery.schema.json +1 -1
  95. package/schemas/extension-package.schema.json +35 -3
  96. package/schemas/extension-record.schema.json +21 -1
@@ -89,6 +89,8 @@ const inputFor = async (options, start) => {
89
89
  base,
90
90
  openapi,
91
91
  importModule: options.importModule,
92
+ // The old prefix as a second mount, so next stays green; it goes in phase 4.
93
+ apiAliases: ['/api/v1'],
92
94
  };
93
95
  };
94
96
  let running;
@@ -99,8 +101,7 @@ export const runPart = async (options) => {
99
101
  const part = partOf(pkg, options.part);
100
102
  const log = createLog({ extension: pkg.agentage.id, part, version: pkg.version });
101
103
  running = log;
102
- const names = part === 'ui' ? [] : (pkg.agentage.secrets ?? []);
103
- const secrets = await readSecrets(names, options.secretsDir ?? SECRETS_DIR, part);
104
+ const secrets = await readSecrets(pkg, part, options.secretsDir ?? SECRETS_DIR);
104
105
  const start = { pkg, part, env: options.env, log, secrets };
105
106
  const { app, stop } = await RUNNERS[part](await inputFor(options, start));
106
107
  if (stop)
@@ -20,6 +20,9 @@ export interface PartAppBase {
20
20
  checks?: Record<string, HealthCheck>;
21
21
  tokenCheck?: TokenCheck;
22
22
  resource?: Record<string, unknown>;
23
+ onExit?: () => void;
24
+ instance?: string;
25
+ startedAt?: number;
23
26
  }
24
27
  export interface PartAppOptions extends PartAppBase {
25
28
  part: ImagePartKind;
@@ -34,6 +37,7 @@ export interface ApiAppOptions extends PartAppBase {
34
37
  method: string;
35
38
  path: string;
36
39
  }[];
40
+ aliases?: string[];
37
41
  }
38
42
  export declare const PUBLIC_CORS: CorsOptions;
39
43
  export declare const BODY_LIMIT = "1mb";
@@ -7,6 +7,7 @@ import { routeAccess, sameShape } from '../auth/route-access.js';
7
7
  import { setCaller } from '../auth/token-check.js';
8
8
  import { discoveryDocument, recordOf, } from '../discovery/discovery.js';
9
9
  import {} from '../discovery/discovery.schema.js';
10
+ import { apiPrefix } from '../discovery/openapi.js';
10
11
  import { createHealthHandler } from '../health/health.js';
11
12
  import {} from '../log/log.js';
12
13
  import {} from '../manifest/manifest.schema.js';
@@ -49,6 +50,8 @@ const healthHandler = (options) => createHealthHandler({
49
50
  build: options.build,
50
51
  checks: options.checks,
51
52
  log: options.log,
53
+ instance: options.instance,
54
+ startedAt: options.startedAt,
52
55
  });
53
56
  // The kit app every part image runs: agcid, headers, /health, discovery, the part, the envelope.
54
57
  export const createPartApp = (options) => {
@@ -58,7 +61,7 @@ export const createPartApp = (options) => {
58
61
  app.use(dropCookie, agcidMiddleware, helmet(options.helmet));
59
62
  app.get('/health', healthHandler(options));
60
63
  // After /health: it is probed every few seconds and never gets a request line.
61
- app.use(requestLine(options.log));
64
+ app.use(requestLine(options.log, options.onExit));
62
65
  if (options.part !== 'worker') {
63
66
  app.use('/.well-known', cors(PUBLIC_CORS));
64
67
  app.get('/.well-known/agentage-extension.json', discoveryHandler(options));
@@ -83,30 +86,37 @@ const wellKnownHandler = (render) => async (_req, res) => {
83
86
  res.json(doc);
84
87
  };
85
88
  // Before the body is read: each request checked for the access its OpenAPI operation declares.
86
- const routeGuard = (options) => async (req, res, next) => {
87
- const { routes } = options;
88
- const known = routes?.find((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
89
- if (known)
90
- res.locals['route'] = `/api/v1${known.path}`;
91
- if (!options.tokenCheck || (routes?.length && !known))
92
- return next();
93
- const access = routeAccess(options.openapi, req.method, `/api/v1${req.path}`);
94
- const caller = await options.tokenCheck(req.get('authorization'), access);
95
- if (caller)
96
- res.setHeader('Cache-Control', 'no-store');
97
- setCaller(req, caller);
98
- next();
89
+ const routeGuard = (options) => {
90
+ const prefix = apiPrefix(options.pkg.agentage.id);
91
+ return async (req, res, next) => {
92
+ const { routes } = options;
93
+ const known = routes?.find((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
94
+ // The mount as called (an alias too), so the row counts the callers of each prefix.
95
+ if (known)
96
+ res.locals['route'] = `${req.baseUrl.toLowerCase()}${known.path}`;
97
+ if (!options.tokenCheck || (routes?.length && !known))
98
+ return next();
99
+ const access = routeAccess(options.openapi, req.method, `${prefix}${req.path}`);
100
+ const caller = await options.tokenCheck(req.get('authorization'), access);
101
+ if (caller)
102
+ res.setHeader('Cache-Control', 'no-store');
103
+ setCaller(req, caller);
104
+ next();
105
+ };
99
106
  };
100
107
  export const createApiApp = (options) => createPartApp({
101
108
  ...options,
102
109
  part: 'api',
103
110
  mount: (app) => {
104
- app.use('/api/v1', cors(PUBLIC_CORS));
111
+ const prefixes = [apiPrefix(options.pkg.agentage.id), ...(options.aliases ?? [])];
112
+ app.use(prefixes, cors(PUBLIC_CORS));
105
113
  for (const { name, render } of options.wellKnown ?? [])
106
114
  app.get(`/.well-known/${name}`, wellKnownHandler(render));
107
- if (options.openapi)
108
- app.get('/api/v1/openapi.json', openapiHandler(options.openapi));
115
+ const { openapi } = options;
116
+ if (openapi)
117
+ for (const at of prefixes)
118
+ app.get(`${at}/openapi.json`, openapiHandler(openapi));
109
119
  const json = express.json({ limit: BODY_LIMIT });
110
- app.use('/api/v1', routeGuard(options), json, options.router);
120
+ app.use(prefixes, routeGuard(options), json, options.router);
111
121
  },
112
122
  });
@@ -1,4 +1,4 @@
1
1
  import { type Request, type RequestHandler, type Response } from 'express';
2
2
  import { type Log } from '../log/log.js';
3
3
  export declare const routeOf: (req: Request, res?: Response) => string;
4
- export declare const requestLine: (log: Log) => RequestHandler;
4
+ export declare const requestLine: (log: Log, onExit?: () => void) => RequestHandler;
@@ -1,7 +1,7 @@
1
1
  import {} from 'express';
2
2
  import { requestScope, sigtermOnce } from '../agcid/current.js';
3
3
  import {} from '../log/log.js';
4
- const MOUNTS = ['/api/v1', '/mcp', '/.well-known', '/ui'];
4
+ const MOUNT = /^\/(?:api\/[^/]+|mcp|\.well-known|ui)(?=\/|$)/;
5
5
  const ASSET = /\.(m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf)$/i;
6
6
  // The matched route template, never the raw URL, so no id or query string reaches the log.
7
7
  export const routeOf = (req, res) => {
@@ -9,7 +9,7 @@ export const routeOf = (req, res) => {
9
9
  if (typeof known === 'string')
10
10
  return known;
11
11
  const url = req.originalUrl?.split('?')[0] ?? '';
12
- const prefix = MOUNTS.find((m) => url === m || url.startsWith(`${m}/`)) ?? '';
12
+ const prefix = MOUNT.exec(url)?.[0] ?? '';
13
13
  const path = req.route?.path;
14
14
  if (typeof path !== 'string')
15
15
  return '(unmatched)';
@@ -22,7 +22,7 @@ const localOf = (res, key) => {
22
22
  return typeof value === 'string' ? value : undefined;
23
23
  };
24
24
  // One http row per request on finish; a ctx.exit() asked for in it shuts the part down after.
25
- export const requestLine = (log) => (req, res, next) => {
25
+ export const requestLine = (log, onExit = sigtermOnce) => (req, res, next) => {
26
26
  const start = performance.now();
27
27
  const scope = requestScope.getStore();
28
28
  res.on('finish', () => {
@@ -38,7 +38,7 @@ export const requestLine = (log) => (req, res, next) => {
38
38
  clientInfo: localOf(res, 'clientInfo'),
39
39
  });
40
40
  if (scope?.exit)
41
- sigtermOnce();
41
+ onExit();
42
42
  });
43
43
  next();
44
44
  };
@@ -7,6 +7,16 @@ export const listen = (app, port, host) => new Promise((resolve, reject) => {
7
7
  const done = (err) => (err ? reject(err) : resolve(server));
8
8
  const server = host === undefined ? app.listen(port, done) : app.listen(port, host, done);
9
9
  });
10
+ // Open requests are answered; a keep-alive connection is closed once idle, not at its timeout.
11
+ const drain = (server, exit) => {
12
+ const idle = setInterval(() => server.closeIdleConnections(), 100).unref();
13
+ server.close((err) => {
14
+ clearInterval(idle);
15
+ exit(err ? 1 : 0);
16
+ });
17
+ server.closeIdleConnections();
18
+ setTimeout(() => exit(1), GRACE_MS).unref();
19
+ };
10
20
  // SIGTERM drains; a close error or a drain past the grace period exits 1; a second Ctrl-C at once.
11
21
  export const shutdownOn = (server, options) => {
12
22
  const exitWith = options.exit ?? ((code) => process.exit(code));
@@ -24,9 +34,7 @@ export const shutdownOn = (server, options) => {
24
34
  return;
25
35
  stopping = true;
26
36
  options.log.info('shutting down');
27
- server.close((err) => exit(err ? 1 : 0));
28
- server.closeIdleConnections();
29
- setTimeout(() => exit(1), GRACE_MS).unref();
37
+ drain(server, exit);
30
38
  };
31
39
  for (const signal of options.signals ?? ['SIGTERM', 'SIGINT'])
32
40
  process.on(signal, () => stop(signal));
@@ -0,0 +1,25 @@
1
+ import { type Row, type Store } from './store.types.js';
2
+ interface PGliteLike {
3
+ query<R>(text: string, params?: unknown[]): Promise<{
4
+ rows: R[];
5
+ }>;
6
+ exec(text: string): Promise<{
7
+ rows: Row[];
8
+ }[]>;
9
+ close(): Promise<void>;
10
+ }
11
+ export interface PgliteStore extends Store {
12
+ close(): Promise<void>;
13
+ }
14
+ export interface StoreAt {
15
+ dataDir?: string;
16
+ from?: string;
17
+ }
18
+ type PGliteModule = {
19
+ PGlite: new (dataDir?: string) => PGliteLike;
20
+ };
21
+ export declare const PGLITE = "@electric-sql/pglite";
22
+ export declare const pgliteMissing: (tried: string[]) => string;
23
+ export declare const loadPglite: (from?: string, kitCopy?: () => Promise<unknown>) => Promise<PGliteModule>;
24
+ export declare const createPgliteStore: (prepare: (store: Store) => Promise<unknown>, at?: StoreAt) => PgliteStore;
25
+ export {};
@@ -0,0 +1,59 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import {} from './store.types.js';
5
+ export const PGLITE = '@electric-sql/pglite';
6
+ export const pgliteMissing = (tried) => `${PGLITE} is not installed (looked in ${tried.join(', then ')}): the host brings it, npm install ${PGLITE}`;
7
+ const notFound = (err) => ['ERR_MODULE_NOT_FOUND', 'MODULE_NOT_FOUND'].includes(String(err.code));
8
+ const fromPackage = async (from) => {
9
+ const file = createRequire(join(from, 'package.json')).resolve(PGLITE);
10
+ return (await import(pathToFileURL(file).href));
11
+ };
12
+ // The host's own copy first (the kit's resolution), then the hosted package's; only a missing one is reworded.
13
+ export const loadPglite = async (from, kitCopy = () => import(PGLITE)) => {
14
+ try {
15
+ return (await kitCopy());
16
+ }
17
+ catch (err) {
18
+ if (!notFound(err))
19
+ throw err;
20
+ if (!from)
21
+ throw new Error(pgliteMissing(['the kit']), { cause: err });
22
+ return fromPackage(from).catch((again) => {
23
+ if (!notFound(again))
24
+ throw again;
25
+ throw new Error(pgliteMissing(['the kit', from]), { cause: again });
26
+ });
27
+ }
28
+ };
29
+ // Like pg: a parameterless query may hold several statements (migrations), the last one answers.
30
+ const bound = (db) => ({
31
+ query: async (text, params) => {
32
+ if (params && params.length > 0)
33
+ return db.query(text, params);
34
+ const results = await db.exec(text);
35
+ return { rows: (results.at(-1)?.rows ?? []) };
36
+ },
37
+ });
38
+ const opened = async (prepare, at) => {
39
+ const { PGlite } = await loadPglite(at.from);
40
+ const db = new PGlite(at.dataDir);
41
+ const store = bound(db);
42
+ await prepare(store).catch(async (err) => {
43
+ await db.close();
44
+ throw err;
45
+ });
46
+ return { ...store, db };
47
+ };
48
+ // In-process Postgres (WASM), prepared once on first use; a failed prepare leaves no open database.
49
+ export const createPgliteStore = (prepare, at = {}) => {
50
+ let ready;
51
+ const start = () => opened(prepare, at);
52
+ return {
53
+ query: async (text, params) => (await (ready ??= start())).query(text, params),
54
+ close: async () => {
55
+ if (ready)
56
+ await (await ready).db.close();
57
+ },
58
+ };
59
+ };
@@ -1,5 +1,4 @@
1
+ import { type PgliteStore } from './pglite-store.js';
1
2
  import { type Store } from './store.types.js';
2
- export interface TestStore extends Store {
3
- close(): Promise<void>;
4
- }
3
+ export type TestStore = PgliteStore;
5
4
  export declare const createTestStore: (prepare: (store: Store) => Promise<unknown>) => TestStore;
@@ -1,39 +1,4 @@
1
+ import { createPgliteStore } from './pglite-store.js';
1
2
  import {} from './store.types.js';
2
- const open = async () => {
3
- try {
4
- const { PGlite } = (await import('@electric-sql/pglite'));
5
- return new PGlite();
6
- }
7
- catch {
8
- throw new Error('a test store needs @electric-sql/pglite: npm install -D @electric-sql/pglite');
9
- }
10
- };
11
- // Like pg: a parameterless query may hold several statements (migrations), the last one answers.
12
- const bound = (db) => ({
13
- query: async (text, params) => {
14
- if (params && params.length > 0)
15
- return db.query(text, params);
16
- const results = await db.exec(text);
17
- return { rows: (results.at(-1)?.rows ?? []) };
18
- },
19
- });
20
- // In-process Postgres (WASM): a throwaway store of the same kind, prepared once on first use.
21
- export const createTestStore = (prepare) => {
22
- let ready;
23
- const start = async () => {
24
- const db = await open();
25
- const store = bound(db);
26
- await prepare(store);
27
- return { ...store, db };
28
- };
29
- return {
30
- query: async (text, params) => {
31
- ready ??= start();
32
- return (await ready).query(text, params);
33
- },
34
- close: async () => {
35
- if (ready)
36
- await (await ready).db.close();
37
- },
38
- };
39
- };
3
+ // A throwaway in-memory store of the same kind, prepared once on first use.
4
+ export const createTestStore = (prepare) => createPgliteStore(prepare);
@@ -1,3 +1,4 @@
1
+ import { type Express } from 'express';
1
2
  import { type ApiContext } from '../api/routes.js';
2
3
  import { type Caller } from '../auth/token-check.js';
3
4
  import { type PartContext } from '../context/context.js';
@@ -20,5 +21,6 @@ export interface TestServer {
20
21
  export interface TestMcp extends TestServer {
21
22
  call(name: string, args?: Record<string, unknown>): Promise<unknown>;
22
23
  }
24
+ export declare const startOn: (app: Express) => Promise<TestServer>;
23
25
  export declare const startTestServer: <C extends PartContext = PartContext>(options: TestServerOptions<C>) => Promise<TestServer>;
24
26
  export declare const startTestMcp: (options: TestMcpOptions) => Promise<TestMcp>;
@@ -22,7 +22,7 @@ const testPackage = (ctx, parts) => ({
22
22
  engines: { agentage: KIT_VERSION },
23
23
  agentage: { id: ctx.extension.id, parts },
24
24
  });
25
- const startOn = async (app) => {
25
+ export const startOn = async (app) => {
26
26
  const server = await listen(app, 0, '127.0.0.1');
27
27
  const url = `http://127.0.0.1:${server.address().port}`;
28
28
  return {
@@ -5,7 +5,7 @@ import { scopeOf } from '../auth/token-check.js';
5
5
  import { createContext } from '../context/context.js';
6
6
  import {} from '../discovery/discovery.js';
7
7
  import { WidgetSchema } from '../discovery/discovery.schema.js';
8
- import { OPENAPI_PATH, readOpenapi } from '../discovery/openapi.js';
8
+ import { openapiPath, readOpenapi } from '../discovery/openapi.js';
9
9
  import { createLog } from '../log/log.js';
10
10
  import { loadCreate } from '../manifest/entry.js';
11
11
  import { readJsonIfExists } from '../manifest/read-manifest.js';
@@ -66,7 +66,7 @@ export const recordExtras = async (dir, pkg) => {
66
66
  if (code.ui)
67
67
  extras.widgets = await widgetsOf(dir);
68
68
  if (code.api && (await readOpenapi(dir)))
69
- extras.openapi = OPENAPI_PATH;
69
+ extras.openapi = openapiPath(pkg.agentage.id);
70
70
  if (migratesStore(pkg))
71
71
  extras.migrations = (await sqlFiles(join(dir, 'migrations'))).length;
72
72
  return extras;
@@ -1,7 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { generatedOpenapi, schemaOf } from '../../api/openapi-doc.js';
3
3
  import {} from '../../api/routes.js';
4
- import { OPENAPI_FILE, readOpenapi } from '../../discovery/openapi.js';
4
+ import { apiPrefix, OPENAPI_FILE, readOpenapi } from '../../discovery/openapi.js';
5
5
  import { loadCreate } from '../../manifest/entry.js';
6
6
  import {} from '../../manifest/manifest.schema.js';
7
7
  import { normalizeParts } from '../../manifest/parts.js';
@@ -11,17 +11,17 @@ import { prefixed } from '../../mcp/tools.js';
11
11
  import {} from '../check.js';
12
12
  import { registeredRoutes, registeredTools } from '../record-extras.js';
13
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])));
14
- const routeKeys = ({ path, stack }) => [path].flat().flatMap((one) => {
15
- const at = `/api/v1${String(one).replace(/:(\w+)/g, '{$1}')}`;
14
+ const routeKeys = (prefix, { path, stack }) => [path].flat().flatMap((one) => {
15
+ const at = `${prefix}${String(one).replace(/:(\w+)/g, '{$1}')}`;
16
16
  // router.all names no method, so it has no operation to compare.
17
17
  return stack.flatMap(({ method }) => (method ? [`${method.toUpperCase()} ${at}`] : []));
18
18
  });
19
19
  // Express routes (of a Router or an express() app) as OpenAPI keys; a sub-router hides its routes, so it never matches one.
20
- const servedRoutes = (app) => {
20
+ const servedRoutes = (prefix, app) => {
21
21
  const { stack, router } = (app ?? {});
22
22
  return (stack ?? router?.stack ?? []).flatMap(({ name, route, handle }) => {
23
23
  if (route)
24
- return routeKeys(route);
24
+ return routeKeys(prefix, route);
25
25
  return handle?.stack ? [`${name} sub-router`] : [];
26
26
  });
27
27
  };
@@ -58,7 +58,7 @@ const routeProblems = (pkg, doc, routes, returned) => {
58
58
  return diff.length > 0 ? [`differs from the generated contract (${diff.join(', ')})`] : [];
59
59
  };
60
60
  const routerProblems = (pkg, doc, returned) => doc
61
- ? apiProblems(doc, servedRoutes(returned), pkg.version)
61
+ ? apiProblems(doc, servedRoutes(apiPrefix(pkg.agentage.id), returned), pkg.version)
62
62
  : ['is missing: the api part commits its contract'];
63
63
  const apiSurface = async ({ dir, pkg }) => {
64
64
  const create = await loadCreate(dir, pkg, 'api').catch(() => null);
@@ -1,5 +1,5 @@
1
1
  import {} from '../../manifest/manifest.schema.js';
2
- import { hasStore, imageParts } from '../../manifest/parts.js';
2
+ import { hasStore, imageParts, mountedIn } from '../../manifest/parts.js';
3
3
  import {} from '../../manifest/primitives.schema.js';
4
4
  import { DEV_AUDIENCE, DEV_ISSUER, UP_ISSUER } from './dev-issuer-app.js';
5
5
  import { GATEWAY_PORT, ISSUER_PORT, PART_PORT, TRAEFIK_COMMAND, TRAEFIK_IMAGE } from './gateway.js';
@@ -33,11 +33,12 @@ const dependsOn = (pkg, part) => ({
33
33
  ...(hasStore(pkg, 'postgres') && part !== 'ui' ? { store: HEALTHY } : {}),
34
34
  ...(part === 'api' || part === 'mcp' ? { issuer: HEALTHY } : {}),
35
35
  });
36
+ const withSecrets = (names) => (names.length ? { secrets: names } : {});
36
37
  const partService = (input, part) => ({
37
38
  image: input.tags[part],
38
39
  environment: partEnv(input.pkg, part),
39
40
  volumes: [`${input.recordFile}:${RECORD_TARGET}:ro`],
40
- ...(part !== 'ui' && input.secretFiles ? { secrets: Object.keys(input.secretFiles) } : {}),
41
+ ...withSecrets(mountedIn(input.pkg, part, Object.keys(input.secretFiles ?? {}))),
41
42
  depends_on: dependsOn(input.pkg, part),
42
43
  });
43
44
  const secretsOf = (files) => Object.fromEntries(Object.entries(files).map(([name, file]) => [name, { file }]));
@@ -10,8 +10,12 @@ export declare const PART_PATHS: {
10
10
  mcp: string;
11
11
  };
12
12
  type RoutedPart = keyof typeof PART_PATHS;
13
- export declare const partPath: (part: RoutedPart, version: string) => string;
14
- export declare const gatewayConfig: (parts: ImagePartKind[], version: string) => {
13
+ export interface PathOf {
14
+ id: string;
15
+ version: string;
16
+ }
17
+ export declare const partPath: (part: RoutedPart, { id, version }: PathOf) => string;
18
+ export declare const gatewayConfig: (parts: ImagePartKind[], of: PathOf) => {
15
19
  http: {
16
20
  middlewares: {
17
21
  'gateway-headers': {
@@ -6,11 +6,11 @@ export const TRAEFIK_IMAGE = 'traefik:v3.7.17@sha256:68ae5fe5b64ca166704b746a9e8
6
6
  // The URL layout of api-standards section 1, as the estate's gateway renders it.
7
7
  const RESERVED = 'PathPrefix(`/api/`) || Path(`/mcp`) || PathPrefix(`/mcp/`) || PathPrefix(`/ui/`) || PathPrefix(`/.well-known/`) || PathPrefix(`/git/`) || Path(`/health`)';
8
8
  // Each routed part's path, in the order `up` prints them; /mcp is exact, the rest are prefixes.
9
- export const PART_PATHS = { pages: '/', ui: '/ui/{version}/', api: '/api/v1/', mcp: '/mcp' };
9
+ export const PART_PATHS = { pages: '/', ui: '/ui/{version}/', api: '/api/{id}/', mcp: '/mcp' };
10
10
  // In this order, so the first present serves /.well-known/ (api-standards section 1).
11
11
  const ROUTED = ['api', 'mcp', 'pages', 'ui'];
12
- export const partPath = (part, version) => PART_PATHS[part].replace('{version}', version);
13
- const ruleOf = (part, version) => part === 'mcp' ? 'Path(`/mcp`)' : `PathPrefix(\`${partPath(part, version)}\`)`;
12
+ export const partPath = (part, { id, version }) => PART_PATHS[part].replace('{version}', version).replace('{id}', id);
13
+ const ruleOf = (part, of) => part === 'mcp' ? 'Path(`/mcp`)' : `PathPrefix(\`${partPath(part, of)}\`)`;
14
14
  const router = (rule, priority, service) => ({
15
15
  rule,
16
16
  priority,
@@ -18,16 +18,19 @@ const router = (rule, priority, service) => ({
18
18
  entryPoints: ['web'],
19
19
  middlewares: ['gateway-headers'],
20
20
  });
21
- const partRouters = (routed, version) => {
21
+ const partRouters = (routed, of) => {
22
22
  const routers = {};
23
23
  for (const part of routed)
24
- routers[part] = router(ruleOf(part, version), part === 'pages' ? 1 : 100, part);
24
+ routers[part] = router(ruleOf(part, of), part === 'pages' ? 1 : 100, part);
25
+ // The old api prefix, as runPart serves it, until phase 4.
26
+ if (routed.includes('api'))
27
+ routers['api-v1'] = router('PathPrefix(`/api/v1/`)', 100, 'api');
25
28
  if (routed[0])
26
29
  routers['well-known'] = router('PathPrefix(`/.well-known/`)', 100, routed[0]);
27
30
  return routers;
28
31
  };
29
32
  // Traefik's file provider: a reserved-prefix miss is Traefik's own 404, like the estate gateway.
30
- export const gatewayConfig = (parts, version) => {
33
+ export const gatewayConfig = (parts, of) => {
31
34
  const routed = ROUTED.filter((part) => parts.includes(part));
32
35
  const services = {
33
36
  'gateway-miss': { loadBalancer: { servers: [{ url: 'http://127.0.0.1:8081' }] } },
@@ -36,7 +39,7 @@ export const gatewayConfig = (parts, version) => {
36
39
  services[part] = { loadBalancer: { servers: [{ url: `http://${part}:${PART_PORT}` }] } };
37
40
  const routers = {
38
41
  reserved: router(RESERVED, 50, 'gateway-miss'),
39
- ...partRouters(routed, version),
42
+ ...partRouters(routed, of),
40
43
  };
41
44
  if (!routed.includes('pages'))
42
45
  routers['host'] = router('PathPrefix(`/`)', 1, 'gateway-miss');
@@ -33,6 +33,7 @@ export declare const writeLocalRecord: (dir: string, pkg: ExtensionPackage, buil
33
33
  } | undefined;
34
34
  };
35
35
  secrets?: string[] | undefined;
36
+ secretParts?: Record<string, ("pages" | "api" | "mcp" | "worker")[]> | undefined;
36
37
  openapi?: string | undefined;
37
38
  tools?: {
38
39
  name: string;
@@ -1,6 +1,7 @@
1
1
  import { chmod, mkdir, writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import {} from '../../manifest/manifest.schema.js';
4
+ import { secretNames } from '../../manifest/parts.js';
4
5
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
5
6
  import {} from '../../runtime/build-info.js';
6
7
  import { LOCAL_DIR } from './local-record.js';
@@ -19,7 +20,7 @@ const valueOf = (name, env, file) => {
19
20
  };
20
21
  // Each value as a file compose mounts at /run/secrets/<name>; the env wins over the file.
21
22
  export const writeUpSecrets = async (dir, pkg, env) => {
22
- const names = pkg.agentage.secrets ?? [];
23
+ const names = secretNames(pkg);
23
24
  if (names.length === 0)
24
25
  return undefined;
25
26
  const file = await fileValues(dir);
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { TIMEOUTS } from '../timeouts.js';
3
3
  import { DEV_ISSUER } from './dev-issuer-app.js';
4
4
  const AnswerSchema = z.object({ token: z.string().startsWith('aga_') });
5
- // A token from the dev issuer of `up`, for calling /api/v1/ and /mcp by hand or from tests.
5
+ // A token from the dev issuer of `up`, for calling /api/{id}/ and /mcp by hand or from tests.
6
6
  export const token = async (options) => {
7
7
  const issuer = options.issuer ?? DEV_ISSUER;
8
8
  const res = await (options.fetch ?? fetch)(`${issuer}/token`, {
@@ -25,7 +25,7 @@ const renderFiles = async (s, recordFile, tags) => {
25
25
  const gatewayFile = join(s.dir, LOCAL_DIR, 'gateway.yml');
26
26
  const seeds = join(s.dir, 'seeds');
27
27
  const seedsDir = (await exists(seeds)) ? seeds : undefined;
28
- await jsonFile(gatewayFile, gatewayConfig(imageParts(s.pkg), s.pkg.version));
28
+ await jsonFile(gatewayFile, gatewayConfig(imageParts(s.pkg), { id: s.pkg.agentage.id, version: s.pkg.version }));
29
29
  const { pkg, secretFiles, target } = s;
30
30
  const project = target.project;
31
31
  await jsonFile(target.file, composeFile({ pkg, project, tags, recordFile, gatewayFile, seedsDir, secretFiles }));
@@ -53,7 +53,7 @@ const storeStep = async (s) => {
53
53
  };
54
54
  export const routesOf = (pkg) => Object.keys(PART_PATHS)
55
55
  .filter((part) => imageParts(pkg).includes(part))
56
- .map((part) => partPath(part, pkg.version));
56
+ .map((part) => partPath(part, { id: pkg.agentage.id, version: pkg.version }));
57
57
  const partsStep = async (s, commit) => {
58
58
  await compose(s.deps.run, s.target, ['up', '-d', '--remove-orphans'], TIMEOUTS.start);
59
59
  await waitHealthy(s.target, [...imageParts(s.pkg), 'gateway', 'issuer'], s.deps);
@@ -24,7 +24,7 @@ const fitting = (event) => {
24
24
  process.emitWarning(`@agentage/logs: dropped a ${event.kind} row over 900 KB`);
25
25
  return false;
26
26
  };
27
- // Each batch under 1 MB and at most 1000 rows (the ingest wire, C3).
27
+ // Each batch under 1 MB and at most 1000 rows (the ingest wire).
28
28
  export const batchesOf = (events) => {
29
29
  const batches = [];
30
30
  let batch = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.12.2",
3
+ "version": "0.13.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",
@@ -32,6 +32,10 @@
32
32
  "types": "./dist/contracts/index.d.ts",
33
33
  "default": "./dist/contracts/index.js"
34
34
  },
35
+ "./host": {
36
+ "types": "./dist/host/index.d.ts",
37
+ "default": "./dist/host/index.js"
38
+ },
35
39
  "./logs": {
36
40
  "types": "./dist/logs/index.d.ts",
37
41
  "default": "./dist/logs/index.js"
@@ -123,7 +123,7 @@
123
123
  },
124
124
  "openapi": {
125
125
  "type": "string",
126
- "pattern": "^\\/api\\/v[1-9][0-9]*\\/openapi\\.json$"
126
+ "pattern": "^\\/api\\/(?:v[0-9]+|[a-z][a-z0-9-]*)\\/openapi\\.json$"
127
127
  },
128
128
  "tools": {
129
129
  "minItems": 1,
@@ -288,9 +288,41 @@
288
288
  "secrets": {
289
289
  "type": "array",
290
290
  "items": {
291
- "type": "string",
292
- "maxLength": 48,
293
- "pattern": "^[a-z][a-z0-9-]*$"
291
+ "anyOf": [
292
+ {
293
+ "type": "string",
294
+ "maxLength": 48,
295
+ "pattern": "^[a-z][a-z0-9-]*$"
296
+ },
297
+ {
298
+ "type": "object",
299
+ "properties": {
300
+ "name": {
301
+ "type": "string",
302
+ "maxLength": 48,
303
+ "pattern": "^[a-z][a-z0-9-]*$"
304
+ },
305
+ "parts": {
306
+ "minItems": 1,
307
+ "type": "array",
308
+ "items": {
309
+ "type": "string",
310
+ "enum": [
311
+ "pages",
312
+ "api",
313
+ "mcp",
314
+ "worker"
315
+ ]
316
+ }
317
+ }
318
+ },
319
+ "required": [
320
+ "name",
321
+ "parts"
322
+ ],
323
+ "additionalProperties": false
324
+ }
325
+ ]
294
326
  }
295
327
  }
296
328
  },