@agentage/extension 0.17.0 → 0.18.2

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 (122) hide show
  1. package/README.md +3 -0
  2. package/dist/api/download.d.ts +14 -0
  3. package/dist/api/download.js +10 -0
  4. package/dist/api/openapi-doc.js +21 -12
  5. package/dist/api/routes.d.ts +4 -1
  6. package/dist/api/routes.js +12 -1
  7. package/dist/host/daemon/app-files.d.ts +13 -0
  8. package/dist/host/daemon/app-files.js +51 -0
  9. package/dist/host/daemon/app-header.d.ts +3 -0
  10. package/dist/host/daemon/app-header.js +12 -0
  11. package/dist/host/daemon/app-reload.d.ts +10 -0
  12. package/dist/host/daemon/app-reload.js +18 -0
  13. package/dist/host/daemon/child.d.ts +1 -0
  14. package/dist/host/daemon/child.js +1 -0
  15. package/dist/host/daemon/cli-user-watch.d.ts +9 -0
  16. package/dist/host/daemon/cli-user-watch.js +47 -0
  17. package/dist/host/daemon/cli-user.d.ts +2 -0
  18. package/dist/host/daemon/cli-user.js +42 -0
  19. package/dist/host/daemon/daemon.d.ts +1 -0
  20. package/dist/host/daemon/daemon.js +16 -2
  21. package/dist/host/daemon/health-routes.d.ts +2 -0
  22. package/dist/host/daemon/health-routes.js +16 -7
  23. package/dist/host/daemon/limits.d.ts +1 -0
  24. package/dist/host/daemon/limits.js +2 -0
  25. package/dist/host/daemon/routes.d.ts +2 -1
  26. package/dist/host/daemon/routes.js +25 -10
  27. package/dist/host/daemon/shell-events.d.ts +9 -0
  28. package/dist/host/daemon/shell-events.js +36 -0
  29. package/dist/host/daemon/shell-routes.d.ts +28 -0
  30. package/dist/host/daemon/shell-routes.js +63 -0
  31. package/dist/host/daemon/supervisor.d.ts +2 -0
  32. package/dist/host/daemon/supervisor.js +2 -1
  33. package/dist/host/data-lock.js +5 -5
  34. package/dist/host/host-env.js +14 -2
  35. package/dist/host/host-extension.js +3 -5
  36. package/dist/host/host-migrations.d.ts +1 -1
  37. package/dist/host/host-migrations.js +2 -2
  38. package/dist/host/host-store.d.ts +1 -0
  39. package/dist/host/host-store.js +1 -1
  40. package/dist/host/host-url-store.d.ts +2 -1
  41. package/dist/host/host-url-store.js +18 -15
  42. package/dist/host/open-store.d.ts +6 -0
  43. package/dist/host/open-store.js +6 -0
  44. package/dist/index.d.ts +2 -1
  45. package/dist/index.js +2 -1
  46. package/dist/manifest/manifest.schema.d.ts +13 -0
  47. package/dist/manifest/manifest.schema.js +16 -2
  48. package/dist/manifest/parts.d.ts +7 -0
  49. package/dist/manifest/parts.js +5 -0
  50. package/dist/manifest/primitives.schema.js +2 -2
  51. package/dist/mcp/mcp-app.d.ts +1 -0
  52. package/dist/mcp/mcp-app.js +1 -1
  53. package/dist/mcp/server.js +19 -5
  54. package/dist/mcp/tools.d.ts +19 -1
  55. package/dist/mcp/tools.js +12 -0
  56. package/dist/runtime/run-part.js +22 -6
  57. package/dist/server/api-routes.js +33 -8
  58. package/dist/server/send-download.d.ts +3 -0
  59. package/dist/server/send-download.js +29 -0
  60. package/dist/shell/dist/index.html +46 -0
  61. package/dist/shell/dist/shell.css +2 -0
  62. package/dist/shell/dist/shell.js +68 -0
  63. package/dist/shell/dist/vendor/app.js +1 -0
  64. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +14 -0
  65. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +14 -0
  66. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +14 -0
  67. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +1 -0
  68. package/dist/shell/dist/vendor/jsx-runtime.js +1 -0
  69. package/dist/shell/dist/vendor/react-dom-client.js +33 -0
  70. package/dist/shell/dist/vendor/react-dom.js +1 -0
  71. package/dist/shell/dist/vendor/react.js +1 -0
  72. package/dist/shell/package.json +5 -0
  73. package/dist/tool/app-build.d.ts +13 -0
  74. package/dist/tool/app-build.js +126 -0
  75. package/dist/tool/app-load.d.ts +4 -0
  76. package/dist/tool/app-load.js +34 -0
  77. package/dist/tool/build.js +5 -2
  78. package/dist/tool/check.js +10 -2
  79. package/dist/tool/container-recipe.d.ts +4 -0
  80. package/dist/tool/container-recipe.js +10 -6
  81. package/dist/tool/index.d.ts +1 -0
  82. package/dist/tool/index.js +1 -0
  83. package/dist/tool/main.d.ts +2 -0
  84. package/dist/tool/main.js +8 -1
  85. package/dist/tool/recipe.d.ts +1 -1
  86. package/dist/tool/recipe.js +16 -6
  87. package/dist/tool/rules/app-deps.d.ts +3 -0
  88. package/dist/tool/rules/app-deps.js +25 -0
  89. package/dist/tool/rules/folders.js +1 -1
  90. package/dist/tool/rules/sealing.js +4 -0
  91. package/dist/tool/stage.js +2 -2
  92. package/dist/tool/up/compose.d.ts +4 -0
  93. package/dist/tool/up/compose.js +41 -3
  94. package/dist/tool/up/gateway.js +16 -3
  95. package/dist/tool/up/secrets.d.ts +1 -0
  96. package/dist/tool/up/secrets.js +13 -1
  97. package/dist/tool/up/up.js +8 -5
  98. package/dist/vendor/app/api.d.ts +9 -0
  99. package/dist/vendor/app/api.js +63 -0
  100. package/dist/vendor/app/app.types.d.ts +79 -0
  101. package/dist/vendor/app/app.types.js +1 -0
  102. package/dist/vendor/app/boundary.d.ts +15 -0
  103. package/dist/vendor/app/boundary.js +17 -0
  104. package/dist/vendor/app/context.d.ts +5 -0
  105. package/dist/vendor/app/context.js +24 -0
  106. package/dist/vendor/app/index.d.ts +7 -0
  107. package/dist/vendor/app/index.js +6 -0
  108. package/dist/vendor/app/region.d.ts +6 -0
  109. package/dist/vendor/app/region.js +14 -0
  110. package/dist/vendor/app/split.d.ts +20 -0
  111. package/dist/vendor/app/split.js +38 -0
  112. package/dist/vendor/app/state-store.d.ts +3 -0
  113. package/dist/vendor/app/state-store.js +35 -0
  114. package/dist/vendor/app/test-host.d.ts +31 -0
  115. package/dist/vendor/app/test-host.js +68 -0
  116. package/dist/vendor/app/theme.css +32 -0
  117. package/dist/vendor/logs/events-client.js +38 -13
  118. package/package.json +39 -2
  119. package/schemas/extension-discovery.schema.json +1 -1
  120. package/schemas/extension-package.schema.json +28 -1
  121. package/schemas/extension-record.schema.json +1 -1
  122. package/schemas/health.schema.json +1 -1
@@ -0,0 +1,36 @@
1
+ import {} from 'express';
2
+ // A comment line now and then, so an idle connection is not cut by a proxy or a browser.
3
+ export const HEARTBEAT_MS = 25_000;
4
+ // A tab that does not read: after this many writes in a row that the socket refused, the stream is dropped.
5
+ export const STALLED_WRITES = 32;
6
+ export const shellEvents = (heartbeatMs = HEARTBEAT_MS) => {
7
+ const open = new Map();
8
+ const write = (res, frame) => {
9
+ const refused = res.write(frame) ? 0 : (open.get(res) ?? 0) + 1;
10
+ if (refused < STALLED_WRITES)
11
+ return void open.set(res, refused);
12
+ open.delete(res);
13
+ res.destroy();
14
+ };
15
+ const send = (event, data) => {
16
+ const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
17
+ for (const res of [...open.keys()])
18
+ write(res, frame);
19
+ };
20
+ // GET /shell/events: server-sent events; the daemon's stop closes every stream.
21
+ const stream = (req, res) => {
22
+ res.writeHead(200, {
23
+ 'content-type': 'text/event-stream',
24
+ 'cache-control': 'no-store',
25
+ connection: 'keep-alive',
26
+ });
27
+ res.write('retry: 1000\n\n');
28
+ open.set(res, 0);
29
+ const beat = setInterval(() => res.write(': beat\n\n'), heartbeatMs).unref();
30
+ req.on('close', () => {
31
+ clearInterval(beat);
32
+ open.delete(res);
33
+ });
34
+ };
35
+ return { send, stream };
36
+ };
@@ -0,0 +1,28 @@
1
+ import { type Express } from 'express';
2
+ import { type CliUser } from './cli-user-watch.js';
3
+ import { type Entries } from './entries.js';
4
+ import { type ShellEvents } from './shell-events.js';
5
+ export declare const kitShellDir: (base?: string) => string | undefined;
6
+ export interface Shell {
7
+ dir: string;
8
+ package: string;
9
+ version: string;
10
+ }
11
+ export declare const readShell: (dir: string) => Promise<Shell>;
12
+ type User = {
13
+ id: string;
14
+ email?: string;
15
+ name?: string;
16
+ };
17
+ export declare const sessionOf: ({ sub, text }: CliUser) => {
18
+ user: User | null;
19
+ host: "local";
20
+ };
21
+ export declare const shellRoutes: (app: Express, { shell, entries, events, user }: ShellDeps) => void;
22
+ export interface ShellDeps {
23
+ shell?: Shell;
24
+ entries: Entries;
25
+ events: ShellEvents;
26
+ user: CliUser;
27
+ }
28
+ export {};
@@ -0,0 +1,63 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import express, {} from 'express';
6
+ import { fail } from '../../envelope/envelope.js';
7
+ import { hasApp } from './app-files.js';
8
+ import {} from './cli-user-watch.js';
9
+ import {} from './entries.js';
10
+ import {} from './shell-events.js';
11
+ // The shell the kit carries (dist/shell, written by the kit build); none when run from src.
12
+ export const kitShellDir = (base = import.meta.url) => {
13
+ const dir = fileURLToPath(new URL('../../shell', base));
14
+ return existsSync(join(dir, 'package.json')) ? dir : undefined;
15
+ };
16
+ export const readShell = async (dir) => {
17
+ const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
18
+ if (typeof pkg.version !== 'string' || typeof pkg.name !== 'string')
19
+ throw new Error(`${dir}/package.json has no name or version: not a shell package`);
20
+ return { dir, package: pkg.name, version: pkg.version };
21
+ };
22
+ const textOf = (value) => (typeof value === 'string' ? value : undefined);
23
+ // K9: the user the children run as (issuer checked in cli-user.ts); email, name of its auth.json.
24
+ export const sessionOf = ({ sub, text }) => {
25
+ if (sub === undefined)
26
+ return { user: null, host: 'local' };
27
+ let shown = {};
28
+ try {
29
+ shown = JSON.parse(text ?? '').user ?? {};
30
+ }
31
+ catch {
32
+ // the sub alone
33
+ }
34
+ const email = textOf(shown['email']);
35
+ const name = textOf(shown['name']);
36
+ return { user: { id: sub, ...(email && { email }), ...(name && { name }) }, host: 'local' };
37
+ };
38
+ // First path segments that are daemon routes: an unknown path under them stays a JSON 404.
39
+ const OWN = new Set(['api', 'mcp', 'host', 'shell', 'app', 'health', '.well-known']);
40
+ const page = (shell, entries) => async (req, res, next) => {
41
+ const id = req.path.split('/')[1] ?? '';
42
+ if (req.method !== 'GET' || OWN.has(id) || req.accepts(['html', 'json']) !== 'html')
43
+ return next();
44
+ const known = id === '' || (await hasApp(entries, id));
45
+ res.status(known ? 200 : 404).set('Cache-Control', 'no-cache');
46
+ // The daemon names this path: a dot folder above it (~/.agentage) is allowed.
47
+ res.sendFile(join(shell.dir, 'dist', 'index.html'), { dotfiles: 'allow' }, (err) => err && next(err));
48
+ };
49
+ const notAFile = (req) => {
50
+ throw fail('NOT_FOUND', `${req.originalUrl} is not a shell file`);
51
+ };
52
+ // S1.2.1: /, /{id}/* (the shell page, 404 for an id with no app), /shell/*, the session, the events.
53
+ export const shellRoutes = (app, { shell, entries, events, user }) => {
54
+ app.get('/shell/session', async (_req, res) => {
55
+ res.set('Cache-Control', 'no-store').json(sessionOf(user));
56
+ });
57
+ app.get('/shell/events', events.stream);
58
+ if (!shell)
59
+ return;
60
+ const files = express.static(join(shell.dir, 'dist'), { index: false, dotfiles: 'deny' });
61
+ app.use('/shell', files, notAFile);
62
+ app.use(page(shell, entries));
63
+ };
@@ -1,5 +1,6 @@
1
1
  import { type Log } from '../../log/log.js';
2
2
  import { type Launch } from './child.js';
3
+ import { type CliUser } from './cli-user-watch.js';
3
4
  import { type InstallEntry } from './installation.js';
4
5
  import { type Lane } from './lane.js';
5
6
  import { type Limits } from './limits.js';
@@ -50,6 +51,7 @@ export interface SupervisorDeps extends Limits {
50
51
  pending: PendingChanges;
51
52
  stopping: Stopping;
52
53
  unsynced: Set<string>;
54
+ user: CliUser;
53
55
  }
54
56
  export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
55
57
  export declare const startEntry: (deps: SupervisorDeps, entry: Entry, fresh?: boolean) => Promise<Error | undefined>;
@@ -2,6 +2,7 @@ import { fail } from '../../envelope/envelope.js';
2
2
  import {} from '../../log/log.js';
3
3
  import { readManifest } from '../../manifest/read-manifest.js';
4
4
  import {} from './child.js';
5
+ import {} from './cli-user-watch.js';
5
6
  import { dataDirOf, readValues } from './daemon-files.js';
6
7
  import {} from './installation.js';
7
8
  import { halt } from './gate.js';
@@ -34,7 +35,7 @@ const launchFor = async (deps, entry, to, fresh) => {
34
35
  assertSecrets(pkg, to.values.secrets);
35
36
  const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...to.values };
36
37
  const child = await deps
37
- .launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs })
38
+ .launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs, userSub: deps.user.sub })
38
39
  .catch((err) => Promise.reject(Object.assign(err, { message: redact(err.message, to.values.secrets) })));
39
40
  await healthy(child.port, deps.healthMs).catch(async (err) => {
40
41
  await child.stop();
@@ -5,21 +5,21 @@ import { setTimeout as sleep } from 'node:timers/promises';
5
5
  export const DATA_DIR_LOCKED = 'DATA_DIR_LOCKED';
6
6
  // The locks of this process: our own pid in a lock not in here is stale (a container is pid 1 again).
7
7
  const held = new Set();
8
- // Linux: an exited child not reaped yet (state Z) answers kill(0) but holds nothing.
9
- const zombie = (pid) => {
8
+ // Linux: an exited child not reaped yet (state Z) answers kill(0) but holds nothing; a pid reaped since kill(0) is gone.
9
+ const gone = (pid) => {
10
10
  if (process.platform !== 'linux')
11
11
  return false;
12
12
  try {
13
13
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
14
14
  return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
15
15
  }
16
- catch {
17
- return false;
16
+ catch (err) {
17
+ return err.code === 'ENOENT';
18
18
  }
19
19
  };
20
20
  const alive = (pid) => {
21
21
  try {
22
- return process.kill(pid, 0) && !zombie(pid);
22
+ return process.kill(pid, 0) && !gone(pid);
23
23
  }
24
24
  catch (err) {
25
25
  return err.code === 'EPERM';
@@ -1,4 +1,5 @@
1
1
  import { declaredScopes, partAuth } from '../auth/part-auth.js';
2
+ import { scopeOf } from '../auth/token-check.js';
2
3
  import { SECRETS_DIR } from '../context/secrets.js';
3
4
  import { parseObject } from '../context/settings.js';
4
5
  import { readOpenapi } from '../discovery/openapi.js';
@@ -9,6 +10,7 @@ import { GRACE_MS } from '../server/serve.js';
9
10
  import { CONTAINER_PORT } from '../tool/container-recipe.js';
10
11
  import {} from './host-extension.js';
11
12
  import { STORE_OPEN_MS } from './host-store.js';
13
+ const LOCAL_VERBS = ['read', 'write'];
12
14
  export const BIND_REFUSED = 'AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off';
13
15
  const TOKEN_ENV = ['AGENTAGE_ISSUER', 'AGENTAGE_AUDIENCE', 'AGENTAGE_ORIGIN'];
14
16
  // A limit: a positive integer of ms, else the default.
@@ -32,9 +34,19 @@ export const hostEnvOf = (env) => {
32
34
  storeUrlFile: env['AGENTAGE_STORE_URL_FILE'] || undefined,
33
35
  };
34
36
  };
35
- // Loopback: no token check. Every address: the cloud part's check, or an explicit AGENTAGE_HOST_AUTH=off.
37
+ // The daemon's signed-in cli user: a loopback request acts as them with read and write; an admin
38
+ // route (logs reads, cloud apply, market admin) stays anonymous, as with no user.
39
+ const localUser = (sub) => async (pkg) => {
40
+ const caller = { sub, scopes: LOCAL_VERBS.map((verb) => scopeOf(pkg.agentage.id, verb)) };
41
+ return { tokenCheck: async (_bearer, access) => (access === 'admin' ? null : caller) };
42
+ };
43
+ // Loopback: no token check (the cli user when the daemon names one). Every address: the cloud
44
+ // part's check, or an explicit AGENTAGE_HOST_AUTH=off, never with a user.
36
45
  export const guardOf = (env, { bind, dir }) => {
37
- if (bind === '127.0.0.1' || env['AGENTAGE_HOST_AUTH'] === 'off')
46
+ const sub = env['AGENTAGE_USER_SUB'];
47
+ if (bind === '127.0.0.1')
48
+ return sub ? localUser(sub) : undefined;
49
+ if (env['AGENTAGE_HOST_AUTH'] === 'off')
38
50
  return undefined;
39
51
  if (TOKEN_ENV.some((key) => !env[key]))
40
52
  throw new Error(BIND_REFUSED);
@@ -14,10 +14,10 @@ import { buildInfoFromEnv } from '../runtime/build-info.js';
14
14
  import {} from '../server/app.js';
15
15
  import { hostClockRate } from '../worker/clock.js';
16
16
  import { localOnly } from './daemon/guard.js';
17
- import { openGitStore } from './host-git-store.js';
18
17
  import { hostPartsOf } from './host-parts.js';
19
18
  import { openHostStore, STORE_OPEN_MS } from './host-store.js';
20
- import { hostStoreChecks, openUrlStore } from './host-url-store.js';
19
+ import { hostStoreChecks } from './host-url-store.js';
20
+ import { openStore } from './open-store.js';
21
21
  const once = (fn) => {
22
22
  let done = false;
23
23
  return () => {
@@ -62,9 +62,7 @@ export const hostWith = async (dir, opts, extras) => {
62
62
  const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
63
63
  const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
64
64
  const at = { dir, dataDir: opts.dataDir, runDir: opts.runDir, openMs };
65
- const url = { dir, file: opts.storeUrlFile, openMs };
66
- const store = (await openGitStore(pkg, { ...at, file: opts.storeUrlFile }, log)) ??
67
- (await openUrlStore(pkg, url, log)) ??
65
+ const store = (await openStore(pkg, { ...at, file: opts.storeUrlFile }, log)) ??
68
66
  (await openHostStore(pkg, at, log));
69
67
  const onExit = once(opts.onExit ?? (() => undefined));
70
68
  const build = extras.build ?? (await hostBuildInfo({}, dir));
@@ -4,5 +4,5 @@ import { type Env } from '../runtime/build-info.js';
4
4
  import { type MigrateResult } from '../store/migrations.js';
5
5
  import { type Store } from '../store/store.types.js';
6
6
  export declare const pendingMigrations: (store: Store, dir: string) => Promise<string[]>;
7
- export declare const migrationsCheck: (store: Store, dir: string, log: Log) => HealthCheck;
7
+ export declare const migrationsCheck: (store: Store, dir: string, log: Log, pendingIs?: "unavailable" | "degraded") => HealthCheck;
8
8
  export declare const migrateHost: (env: Env, write?: (line: string) => undefined) => Promise<MigrateResult | undefined>;
@@ -25,7 +25,7 @@ export const pendingMigrations = async (store, dir) => {
25
25
  }
26
26
  };
27
27
  // checks["store:migrations"]: the serving host never migrates; ok once, it stays ok (one image, one set).
28
- export const migrationsCheck = (store, dir, log) => {
28
+ export const migrationsCheck = (store, dir, log, pendingIs = 'unavailable') => {
29
29
  let applied = false;
30
30
  let warned = false;
31
31
  return async () => {
@@ -36,7 +36,7 @@ export const migrationsCheck = (store, dir, log) => {
36
36
  if (!applied && !warned)
37
37
  log.warn('migrations not applied: run the migrate job', { pending: pending.join(', ') });
38
38
  warned ||= !applied;
39
- return applied ? 'ok' : 'unavailable';
39
+ return applied ? 'ok' : pendingIs;
40
40
  };
41
41
  };
42
42
  // `main.js migrate`: the one container as a one-shot job; the URL is never printed.
@@ -2,6 +2,7 @@ import { type Log } from '../log/log.js';
2
2
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
3
  import { type PgliteStore } from '../store/pglite-store.js';
4
4
  export declare const STORE_OPEN_MS = 120000;
5
+ export declare const within: <T>(work: Promise<T>, ms: number) => Promise<T | "late">;
5
6
  export declare const lockWithin: (dataDir: string, openMs: number, lock?: string) => Promise<() => Promise<void>>;
6
7
  export declare const lockOf: ({ dataDir, runDir }: Pick<StoreAt, "dataDir" | "runDir">) => string;
7
8
  interface StoreAt {
@@ -10,7 +10,7 @@ import { DATA_DIR_LOCKED, lockDataDir } from './data-lock.js';
10
10
  const unlocked = async () => undefined;
11
11
  // How long the host waits for the store to open (and to close); the daemon sets its healthMs.
12
12
  export const STORE_OPEN_MS = 120_000;
13
- const within = (work, ms) => Promise.race([
13
+ export const within = (work, ms) => Promise.race([
14
14
  work,
15
15
  new Promise((resolve) => setTimeout(() => resolve('late'), ms).unref()),
16
16
  ]);
@@ -14,9 +14,10 @@ export interface UrlStoreAt {
14
14
  dir: string;
15
15
  file?: string;
16
16
  openMs: number;
17
+ partImage?: boolean;
17
18
  }
18
19
  type Pool = (url: string, log: Log) => PoolStore;
19
- export declare const postgresStore: (url: string, dir: string, log: Log, pool?: Pool) => HostStore;
20
+ export declare const postgresStore: (url: string, at: Pick<UrlStoreAt, "dir" | "partImage">, log: Log, pool?: Pool) => Promise<HostStore>;
20
21
  export declare const openUrlStore: (pkg: ExtensionPackage, at: UrlStoreAt, log: Log) => Promise<HostStore | undefined>;
21
22
  export declare const hostStoreChecks: (store: HostStore | undefined) => Record<string, HealthCheck>;
22
23
  export {};
@@ -1,33 +1,36 @@
1
+ import { join } from 'node:path';
1
2
  import {} from '../health/health.js';
2
3
  import { messageOf } from '../log/log.js';
3
4
  import {} from '../manifest/manifest.schema.js';
4
5
  import { storeOf } from '../manifest/parts.js';
5
6
  import { createClickhouseStore } from '../store/clickhouse-store.js';
7
+ import { sqlFiles } from '../store/migrations.js';
6
8
  import { createStore, storeCheck } from '../store/store.js';
7
9
  import { isUrlStoreKind, readStoreUrl, STORE_URL_FILE_ENV, } from '../store/store-url.js';
8
10
  import {} from '../store/store.types.js';
9
11
  import { migrationsCheck } from './host-migrations.js';
12
+ import { within } from './host-store.js';
10
13
  const poolOf = (url, log) => createStore({ AGENTAGE_STORE_URL: url }, log);
11
14
  // The serving host never migrates (the migrate job does): /health is 503 until the ledger is current.
12
- export const postgresStore = (url, dir, log, pool = poolOf) => {
15
+ export const postgresStore = async (url, at, log, pool = poolOf) => {
13
16
  const parts = pool(url, log);
14
- return {
15
- kind: 'postgres',
16
- query: parts.query,
17
- close: () => parts.end(),
18
- checks: { 'store:migrations': migrationsCheck(parts, dir, log) },
19
- };
17
+ const store = { kind: 'postgres', query: parts.query, close: () => parts.end() };
18
+ if (at.partImage && (await sqlFiles(join(at.dir, 'migrations'))).length === 0)
19
+ return store;
20
+ const pending = at.partImage ? 'degraded' : 'unavailable';
21
+ return { ...store, checks: { 'store:migrations': migrationsCheck(parts, at.dir, log, pending) } };
20
22
  };
21
- const within = (work, ms) => Promise.race([work, new Promise((ok) => setTimeout(() => ok('late'), ms).unref())]);
22
- // The start waits up to openMs for the store; one that is down still starts, /health says 503.
23
- const firstUse = async (store, kind, openMs, log) => {
23
+ // The start waits up to openMs for the store (a part image: not at all); /health says 503 until it opens.
24
+ const firstUse = async (store, kind, at, log) => {
24
25
  const opened = store.query('select 1').then(() => 'ok', (err) => err);
25
- const result = await within(opened, openMs);
26
+ const result = at.partImage ? 'late' : await within(opened, at.openMs);
26
27
  if (result === 'ok')
27
28
  return log.info('store opened', { kind, from: STORE_URL_FILE_ENV });
28
- const reason = result === 'late' ? `not in ${openMs} ms` : messageOf(result);
29
- log.warn('the store did not open: /health says unavailable until it does', { kind, reason });
29
+ if (at.partImage)
30
+ return void opened.then((r) => r !== 'ok' && warnClosed(log, kind, messageOf(r)));
31
+ warnClosed(log, kind, result === 'late' ? `not in ${at.openMs} ms` : messageOf(result));
30
32
  };
33
+ const warnClosed = (log, kind, reason) => log.warn('the store did not open: /health says unavailable until it does', { kind, reason });
31
34
  const kindOf = (pkg, log) => {
32
35
  const kind = storeOf(pkg);
33
36
  if (isUrlStoreKind(kind))
@@ -43,8 +46,8 @@ export const openUrlStore = async (pkg, at, log) => {
43
46
  if (!kind)
44
47
  return undefined;
45
48
  const url = await readStoreUrl(at.file, kind);
46
- const store = kind === 'postgres' ? postgresStore(url, at.dir, log) : createClickhouseStore(url, log);
47
- await firstUse(store, kind, at.openMs, log);
49
+ const store = kind === 'postgres' ? await postgresStore(url, at, log) : createClickhouseStore(url, log);
50
+ await firstUse(store, kind, at, log);
48
51
  return store;
49
52
  };
50
53
  // Calls that overlap share one run: /health asks checks.store and store:<kind> in one probe.
@@ -0,0 +1,6 @@
1
+ import { type Log } from '../log/log.js';
2
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type GitStoreAt } from './host-git-store.js';
4
+ import { type HostStore, type UrlStoreAt } from './host-url-store.js';
5
+ export type OpenStoreAt = GitStoreAt & UrlStoreAt;
6
+ export declare const openStore: (pkg: ExtensionPackage, at: OpenStoreAt, log: Log) => Promise<HostStore | undefined>;
@@ -0,0 +1,6 @@
1
+ import {} from '../log/log.js';
2
+ import {} from '../manifest/manifest.schema.js';
3
+ import { openGitStore } from './host-git-store.js';
4
+ import { openUrlStore } from './host-url-store.js';
5
+ // The one opener of the daemon, the one container and the part image: git, else a store URL file.
6
+ export const openStore = async (pkg, at, log) => (await openGitStore(pkg, at, log)) ?? (await openUrlStore(pkg, at, log));
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { type ApiContext, type ParamsOf, type RouteHandler, type RouteMethod, type RouteRegistrar, type RouteRequest, type RouteSpec, } from './api/routes.js';
2
+ export { download, type DownloadAnswer, type DownloadBody, type DownloadOptions, } from './api/download.js';
2
3
  export { pageOf, PageQuerySchema, type Pagination } from './api/page.js';
3
4
  export { type Access, type Caller } from './auth/token-check.js';
4
5
  export { type ArgValue } from './command/args.js';
@@ -17,7 +18,7 @@ export { type HealthBody, type HealthStatus } from './health/health.schema.js';
17
18
  export { type Log, type LogFields } from './log/log.js';
18
19
  export { createEventsClient, EventSchema, parseLine, type Event, type EventsClientOptions, type PostEvent, } from './vendor/logs/index.js';
19
20
  export { type Span, type SpanRecord } from './log/span.js';
20
- export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, } from './mcp/tools.js';
21
+ export { toolResult, type McpContext, type TextContent, type ToolHandler, type ToolResult, type ToolResultOptions, type ToolRegistrar, type ToolSpec, } from './mcp/tools.js';
21
22
  export { versionPage, type PagesContext, type PagesEntry, type PagesSite } from './pages/pages.js';
22
23
  export { siteFromDir, type SiteFromDirOptions } from './pages/site-from-dir.js';
23
24
  export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export {} from './api/routes.js';
2
+ export { download, } from './api/download.js';
2
3
  export { pageOf, PageQuerySchema } from './api/page.js';
3
4
  export {} from './auth/token-check.js';
4
5
  export {} from './command/args.js';
@@ -18,7 +19,7 @@ export {} from './health/health.schema.js';
18
19
  export {} from './log/log.js';
19
20
  export { createEventsClient, EventSchema, parseLine, } from './vendor/logs/index.js';
20
21
  export {} from './log/span.js';
21
- export {} from './mcp/tools.js';
22
+ export { toolResult, } from './mcp/tools.js';
22
23
  export { versionPage } from './pages/pages.js';
23
24
  export { siteFromDir } from './pages/site-from-dir.js';
24
25
  export {} from './server/part.types.js';
@@ -9,6 +9,7 @@ declare const PartsSchema: z.ZodObject<{
9
9
  ui: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
10
10
  entry: z.ZodOptional<z.ZodString>;
11
11
  }, z.core.$strict>]>>;
12
+ app: z.ZodOptional<z.ZodBoolean>;
12
13
  api: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
13
14
  entry: z.ZodOptional<z.ZodString>;
14
15
  }, z.core.$strict>]>>;
@@ -50,6 +51,11 @@ declare const CommandSchema: z.ZodObject<{
50
51
  description: z.ZodOptional<z.ZodString>;
51
52
  }, z.core.$strict>>>;
52
53
  }, z.core.$strict>;
54
+ declare const AppMetaSchema: z.ZodObject<{
55
+ title: z.ZodString;
56
+ icon: z.ZodOptional<z.ZodString>;
57
+ order: z.ZodOptional<z.ZodInt>;
58
+ }, z.core.$strict>;
53
59
  export declare const PackageSchema: z.ZodObject<{
54
60
  name: z.ZodString;
55
61
  version: z.ZodString;
@@ -65,6 +71,7 @@ export declare const PackageSchema: z.ZodObject<{
65
71
  ui: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
66
72
  entry: z.ZodOptional<z.ZodString>;
67
73
  }, z.core.$strict>]>>;
74
+ app: z.ZodOptional<z.ZodBoolean>;
68
75
  api: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
69
76
  entry: z.ZodOptional<z.ZodString>;
70
77
  }, z.core.$strict>]>>;
@@ -91,6 +98,11 @@ export declare const PackageSchema: z.ZodObject<{
91
98
  }>;
92
99
  }, z.core.$strict>]>>;
93
100
  }, z.core.$strict>;
101
+ app: z.ZodOptional<z.ZodObject<{
102
+ title: z.ZodString;
103
+ icon: z.ZodOptional<z.ZodString>;
104
+ order: z.ZodOptional<z.ZodInt>;
105
+ }, z.core.$strict>>;
94
106
  commands: z.ZodOptional<z.ZodArray<z.ZodObject<{
95
107
  name: z.ZodString;
96
108
  summary: z.ZodString;
@@ -128,6 +140,7 @@ export declare const PackageSchema: z.ZodObject<{
128
140
  }, z.core.$strict>]>>>;
129
141
  }, z.core.$strict>;
130
142
  }, z.core.$loose>;
143
+ export type AppMeta = z.infer<typeof AppMetaSchema>;
131
144
  export type CodePart = z.infer<typeof CodePartSchema>;
132
145
  export type CommandSpec = z.infer<typeof CommandSchema>;
133
146
  export type Parts = z.infer<typeof PartsSchema>;
@@ -7,11 +7,12 @@ const CodePartSchema = z.union([
7
7
  const StorePartSchema = z.union([StoreKindSchema, z.strictObject({ kind: StoreKindSchema })], {
8
8
  error: `one of ${StoreKindSchema.options.join(', ')}`,
9
9
  });
10
- const ROUTED = ['pages', 'ui', 'api', 'mcp'];
10
+ const ROUTED = ['pages', 'ui', 'app', 'api', 'mcp'];
11
11
  const PartsSchema = z
12
12
  .strictObject({
13
13
  pages: CodePartSchema.optional(),
14
14
  ui: CodePartSchema.optional(),
15
+ app: z.boolean().optional(),
15
16
  api: CodePartSchema.optional(),
16
17
  mcp: CodePartSchema.optional(),
17
18
  worker: CodePartSchema.optional(),
@@ -19,7 +20,7 @@ const PartsSchema = z
19
20
  store: StorePartSchema.optional(),
20
21
  })
21
22
  .refine((parts) => ROUTED.some((kind) => isOn(parts[kind])), {
22
- message: 'at least one routed part (pages, ui, api or mcp)',
23
+ message: 'at least one routed part (pages, ui, app, api or mcp)',
23
24
  });
24
25
  const ArgTypeSchema = z.enum(['string', 'integer', 'number', 'boolean']);
25
26
  const CommandSchema = z.strictObject({
@@ -52,9 +53,20 @@ const SecretSchema = z.union([
52
53
  SecretNameSchema,
53
54
  z.strictObject({ name: SecretNameSchema, parts: z.array(SecretPartSchema).min(1) }),
54
55
  ]);
56
+ // The nav row of the app part; icon is a lucide icon name.
57
+ const AppMetaSchema = z.strictObject({
58
+ title: z.string().min(1).max(40),
59
+ icon: z
60
+ .string()
61
+ .max(64)
62
+ .regex(/^[a-z][a-z0-9-]*$/)
63
+ .optional(),
64
+ order: z.int().min(0).max(1000).optional(),
65
+ });
55
66
  const AgentageBaseSchema = z.strictObject({
56
67
  id: ExtensionIdSchema,
57
68
  parts: PartsSchema,
69
+ app: AppMetaSchema.optional(),
58
70
  commands: z.array(CommandSchema).min(1).optional(),
59
71
  settings: z.record(SettingKeySchema, SettingSchema).optional(),
60
72
  secrets: z.array(SecretSchema).optional(),
@@ -98,6 +110,8 @@ function crossFieldRules(manifest, ctx) {
98
110
  const ids = (manifest.secrets ?? []).map((s) => camelName(typeof s === 'string' ? s : s.name));
99
111
  if (new Set(ids).size !== ids.length)
100
112
  issue('secret names must be unique', ['secrets']);
113
+ if (isOn(manifest.parts.app) !== Boolean(manifest.app))
114
+ issue('the app part and agentage.app come together', manifest.app ? ['app'] : ['parts', 'app']);
101
115
  if (manifest.settings?.['mcp.listing'] && !isOn(manifest.parts.mcp)) {
102
116
  issue('mcp.listing needs the mcp part', ['settings', 'mcp.listing']);
103
117
  }
@@ -21,4 +21,11 @@ export declare const unmountedIn: (pkg: ExtensionPackage | undefined, part: Imag
21
21
  export declare const storeOf: (pkg: ExtensionPackage) => StoreKind | undefined;
22
22
  export declare const hasStore: (pkg: ExtensionPackage, kind: StoreKind) => boolean;
23
23
  export declare const migratesStore: (pkg: ExtensionPackage) => boolean;
24
+ export declare const APP_DIR = "dist/app";
25
+ export declare const APP_META_FILE = "app.json";
26
+ export declare const appOf: (pkg: ExtensionPackage) => {
27
+ title: string;
28
+ icon?: string | undefined;
29
+ order?: number | undefined;
30
+ } | undefined;
24
31
  export {};
@@ -40,3 +40,8 @@ export const migratesStore = (pkg) => {
40
40
  const kind = storeOf(pkg);
41
41
  return kind !== undefined && STORE_KINDS[kind].migrations;
42
42
  };
43
+ // dist/app/app.json names the hashed files of the last app build; the host reads it.
44
+ export const APP_DIR = 'dist/app';
45
+ export const APP_META_FILE = 'app.json';
46
+ // The app part: a browser bundle the host serves from dist/app, never an image or a child.
47
+ export const appOf = (pkg) => pkg.agentage.parts.app ? pkg.agentage.app : undefined;
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
- // Platform names and cli verbs, plus Windows device names: an id is a folder name on machines.
3
- const RESERVED_IDS = 'auth|www|api|sync|mail|mcp|ui|git|setup|status|update|extension|add|remove|help|con|prn|aux|nul|com[0-9]|lpt[0-9]';
2
+ // Platform names, the daemon's first path segments and cli verbs, plus Windows device names: an id is a folder name on machines.
3
+ const RESERVED_IDS = 'auth|www|api|sync|mail|mcp|ui|app|shell|host|health|git|setup|status|update|extension|add|remove|help|con|prn|aux|nul|com[0-9]|lpt[0-9]';
4
4
  export const ExtensionIdSchema = z
5
5
  .string()
6
6
  .max(32)
@@ -8,6 +8,7 @@ export interface McpAppOptions extends PartAppBase {
8
8
  bare?: boolean;
9
9
  paths?: string[];
10
10
  }
11
+ export declare const MCP_PATH = "/mcp";
11
12
  export declare const mcpPathOf: (id: string) => string;
12
13
  export declare const mountMcp: (app: Express, options: McpAppOptions) => void;
13
14
  export declare const createMcpApp: (options: McpAppOptions) => Express;
@@ -10,7 +10,7 @@ import { declaredType, printable } from '../log/who.js';
10
10
  import { BODY_LIMIT, createPartApp, PUBLIC_CORS, resourceDocAt, } from '../server/app.js';
11
11
  import { authInfoOf, serverFactory } from './server.js';
12
12
  import { nameOf } from './tools.js';
13
- const MCP_PATH = '/mcp';
13
+ export const MCP_PATH = '/mcp';
14
14
  // The endpoint of an extension on a host that runs many: the daemon routes it to its child.
15
15
  export const mcpPathOf = (id) => `${MCP_PATH}/${id}`;
16
16
  const MCP_HEADERS = ['Mcp-Protocol-Version', 'Mcp-Method', 'Mcp-Name', 'Accept'];
@@ -4,15 +4,18 @@ import {} from '../auth/token-check.js';
4
4
  import { currentAgcid } from '../agcid/current.js';
5
5
  import { fail, isFailure } from '../envelope/envelope.js';
6
6
  import {} from '../log/log.js';
7
- import { nameOf } from './tools.js';
7
+ import { isToolResult, nameOf, } from './tools.js';
8
8
  const text = (value) => [{ type: 'text', text: value }];
9
- // A failed tool: isError, the REST error shape, an agcid (minted outside a request); else INTERNAL.
10
- const errorResult = (err, log, tool) => {
9
+ // A failed tool: isError, else INTERNAL; with an output schema also the REST error shape and an agcid.
10
+ const errorResult = (entry, err, log, tool) => {
11
11
  const failure = isFailure(err) ? err : fail('INTERNAL', 'Internal error');
12
12
  if (failure.status >= 500)
13
13
  log.error(err, tool);
14
+ const content = text(failure.message);
15
+ if (!entry.spec.output)
16
+ return { isError: true, content };
14
17
  const error = { code: failure.code, message: failure.message, agcid: agcidOf(currentAgcid()) };
15
- return { isError: true, content: text(error.message), structuredContent: { error } };
18
+ return { isError: true, content, structuredContent: { error } };
16
19
  };
17
20
  // The kit, not the SDK, refuses bad arguments (C7): the SDK lists the schema, passes all through.
18
21
  const listedOnly = (input) => ({
@@ -25,8 +28,19 @@ const argsOf = (entry, args) => {
25
28
  const fields = new Set(parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'));
26
29
  throw fail('VALIDATION_ERROR', `Invalid arguments: ${[...fields].join(', ')}`);
27
30
  };
31
+ // The tool's own text; its structured part still meets the output schema.
32
+ const ownResultOf = (entry, { content, isError, structuredContent }) => {
33
+ if (isError)
34
+ return { isError, content };
35
+ if (!entry.spec.output)
36
+ return { content };
37
+ const output = entry.spec.output.parse(structuredContent);
38
+ return { content, structuredContent: output };
39
+ };
28
40
  // No output schema: the answer is text only, as a client of a tool with no outputSchema expects.
29
41
  const resultOf = (entry, value) => {
42
+ if (isToolResult(value))
43
+ return ownResultOf(entry, value);
30
44
  if (!entry.spec.output)
31
45
  return { content: text(JSON.stringify(value ?? null)) };
32
46
  const output = entry.spec.output.parse(value);
@@ -46,7 +60,7 @@ const callback = (entry, log, tool, caller) => async (args) => {
46
60
  catch (err) {
47
61
  // A 4xx is a rejection, not a failure: the row stays info.
48
62
  log.mcp({ tool, ms: ms(), ...(isFailure(err) && err.status < 500 ? {} : { error: err }) });
49
- return errorResult(err, log, tool);
63
+ return errorResult(entry, err, log, tool);
50
64
  }
51
65
  };
52
66
  // The caller the guard checked rides in authInfo, the SDK's own path to a per-request server.