@agentage/extension 0.16.0 → 0.18.1

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 (147) hide show
  1. package/dist/api/download.d.ts +14 -0
  2. package/dist/api/download.js +10 -0
  3. package/dist/api/files-registry.d.ts +17 -0
  4. package/dist/api/files-registry.js +10 -0
  5. package/dist/api/files.d.ts +8 -0
  6. package/dist/api/files.js +82 -0
  7. package/dist/api/openapi-doc.js +21 -12
  8. package/dist/api/routes.d.ts +10 -1
  9. package/dist/api/routes.js +15 -2
  10. package/dist/auth/token-check.d.ts +1 -1
  11. package/dist/auth/verify-token.js +9 -9
  12. package/dist/context/test-context.d.ts +5 -1
  13. package/dist/context/test-context.js +2 -1
  14. package/dist/host/daemon/app-files.d.ts +13 -0
  15. package/dist/host/daemon/app-files.js +51 -0
  16. package/dist/host/daemon/app-header.d.ts +3 -0
  17. package/dist/host/daemon/app-header.js +12 -0
  18. package/dist/host/daemon/app-reload.d.ts +10 -0
  19. package/dist/host/daemon/app-reload.js +18 -0
  20. package/dist/host/daemon/child.d.ts +1 -0
  21. package/dist/host/daemon/child.js +7 -4
  22. package/dist/host/daemon/cli-user-watch.d.ts +8 -0
  23. package/dist/host/daemon/cli-user-watch.js +43 -0
  24. package/dist/host/daemon/cli-user.d.ts +2 -0
  25. package/dist/host/daemon/cli-user.js +42 -0
  26. package/dist/host/daemon/daemon.d.ts +1 -0
  27. package/dist/host/daemon/daemon.js +13 -1
  28. package/dist/host/daemon/health-routes.d.ts +2 -0
  29. package/dist/host/daemon/health-routes.js +29 -15
  30. package/dist/host/daemon/limits.d.ts +1 -0
  31. package/dist/host/daemon/limits.js +2 -0
  32. package/dist/host/daemon/routes.js +25 -7
  33. package/dist/host/daemon/seal.d.ts +6 -2
  34. package/dist/host/daemon/seal.js +9 -2
  35. package/dist/host/daemon/shell-events.d.ts +9 -0
  36. package/dist/host/daemon/shell-events.js +36 -0
  37. package/dist/host/daemon/shell-routes.d.ts +28 -0
  38. package/dist/host/daemon/shell-routes.js +63 -0
  39. package/dist/host/daemon/supervisor.d.ts +2 -0
  40. package/dist/host/daemon/supervisor.js +2 -1
  41. package/dist/host/data-lock.js +5 -5
  42. package/dist/host/host-env.js +14 -2
  43. package/dist/host/host-extension.js +4 -3
  44. package/dist/host/host-git-store.d.ts +10 -0
  45. package/dist/host/host-git-store.js +36 -0
  46. package/dist/host/host-migrations.d.ts +1 -1
  47. package/dist/host/host-migrations.js +2 -2
  48. package/dist/host/host-parts.d.ts +2 -2
  49. package/dist/host/host-parts.js +1 -1
  50. package/dist/host/host-url-store.d.ts +4 -2
  51. package/dist/host/host-url-store.js +18 -15
  52. package/dist/host/open-store.d.ts +6 -0
  53. package/dist/host/open-store.js +6 -0
  54. package/dist/index.d.ts +3 -1
  55. package/dist/index.js +3 -1
  56. package/dist/manifest/manifest.schema.d.ts +13 -0
  57. package/dist/manifest/manifest.schema.js +16 -2
  58. package/dist/manifest/parts.d.ts +7 -0
  59. package/dist/manifest/parts.js +5 -0
  60. package/dist/manifest/primitives.schema.js +3 -3
  61. package/dist/mcp/connector.d.ts +4 -0
  62. package/dist/mcp/connector.js +11 -0
  63. package/dist/mcp/mcp-app.d.ts +4 -1
  64. package/dist/mcp/mcp-app.js +28 -18
  65. package/dist/mcp/server.d.ts +6 -3
  66. package/dist/mcp/server.js +70 -18
  67. package/dist/mcp/tools.d.ts +40 -4
  68. package/dist/mcp/tools.js +34 -12
  69. package/dist/runtime/part-mounts.js +12 -6
  70. package/dist/runtime/run-part.js +22 -6
  71. package/dist/server/api-routes.d.ts +5 -2
  72. package/dist/server/api-routes.js +41 -14
  73. package/dist/server/app.d.ts +3 -0
  74. package/dist/server/app.js +11 -1
  75. package/dist/server/send-download.d.ts +3 -0
  76. package/dist/server/send-download.js +29 -0
  77. package/dist/shell/dist/index.html +46 -0
  78. package/dist/shell/dist/shell.css +2 -0
  79. package/dist/shell/dist/shell.js +68 -0
  80. package/dist/shell/dist/vendor/app.js +1 -0
  81. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +14 -0
  82. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +14 -0
  83. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +14 -0
  84. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +1 -0
  85. package/dist/shell/dist/vendor/jsx-runtime.js +1 -0
  86. package/dist/shell/dist/vendor/react-dom-client.js +33 -0
  87. package/dist/shell/dist/vendor/react-dom.js +1 -0
  88. package/dist/shell/dist/vendor/react.js +1 -0
  89. package/dist/shell/package.json +5 -0
  90. package/dist/store/git-env.d.ts +11 -0
  91. package/dist/store/git-env.js +44 -0
  92. package/dist/store/store-url.d.ts +1 -1
  93. package/dist/store/store-url.js +2 -0
  94. package/dist/store/store.types.d.ts +3 -0
  95. package/dist/store/store.types.js +1 -1
  96. package/dist/testing/test-server.js +11 -12
  97. package/dist/tool/app-build.d.ts +13 -0
  98. package/dist/tool/app-build.js +126 -0
  99. package/dist/tool/app-load.d.ts +4 -0
  100. package/dist/tool/app-load.js +34 -0
  101. package/dist/tool/build.js +5 -2
  102. package/dist/tool/check.js +4 -2
  103. package/dist/tool/container-recipe.d.ts +9 -2
  104. package/dist/tool/container-recipe.js +14 -9
  105. package/dist/tool/container-stage.js +1 -1
  106. package/dist/tool/index.d.ts +1 -0
  107. package/dist/tool/index.js +1 -0
  108. package/dist/tool/main.d.ts +2 -0
  109. package/dist/tool/main.js +8 -1
  110. package/dist/tool/recipe.d.ts +1 -1
  111. package/dist/tool/recipe.js +16 -6
  112. package/dist/tool/record-extras.js +4 -3
  113. package/dist/tool/rules/folders.js +1 -1
  114. package/dist/tool/rules/sealing.js +4 -0
  115. package/dist/tool/rules/store.js +0 -3
  116. package/dist/tool/rules/surface.js +4 -1
  117. package/dist/tool/stage.js +2 -2
  118. package/dist/tool/up/compose.d.ts +4 -0
  119. package/dist/tool/up/compose.js +41 -3
  120. package/dist/tool/up/gateway.js +16 -3
  121. package/dist/tool/up/secrets.d.ts +1 -0
  122. package/dist/tool/up/secrets.js +13 -1
  123. package/dist/tool/up/up.js +8 -5
  124. package/dist/vendor/app/api.d.ts +9 -0
  125. package/dist/vendor/app/api.js +63 -0
  126. package/dist/vendor/app/app.types.d.ts +65 -0
  127. package/dist/vendor/app/app.types.js +1 -0
  128. package/dist/vendor/app/boundary.d.ts +15 -0
  129. package/dist/vendor/app/boundary.js +17 -0
  130. package/dist/vendor/app/context.d.ts +5 -0
  131. package/dist/vendor/app/context.js +22 -0
  132. package/dist/vendor/app/index.d.ts +7 -0
  133. package/dist/vendor/app/index.js +6 -0
  134. package/dist/vendor/app/region.d.ts +6 -0
  135. package/dist/vendor/app/region.js +14 -0
  136. package/dist/vendor/app/split.d.ts +20 -0
  137. package/dist/vendor/app/split.js +38 -0
  138. package/dist/vendor/app/state-store.d.ts +3 -0
  139. package/dist/vendor/app/state-store.js +35 -0
  140. package/dist/vendor/app/test-host.d.ts +29 -0
  141. package/dist/vendor/app/test-host.js +66 -0
  142. package/dist/vendor/app/theme.css +32 -0
  143. package/package.json +35 -2
  144. package/schemas/extension-discovery.schema.json +1 -1
  145. package/schemas/extension-package.schema.json +28 -1
  146. package/schemas/extension-record.schema.json +1 -1
  147. package/schemas/health.schema.json +1 -1
@@ -0,0 +1,42 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ // A segment the extension may use as a folder name (memory: <root>/<sub>/<vault>.git).
4
+ const SUB = /^[A-Za-z0-9_-]{1,128}$/;
5
+ const SESSION_MS = 3_000;
6
+ const objectOf = (value) => typeof value === 'object' && value !== null ? value : {};
7
+ const subOf = (value) => typeof value === 'string' && SUB.test(value) ? value : undefined;
8
+ const parsed = (text) => {
9
+ try {
10
+ return objectOf(JSON.parse(text));
11
+ }
12
+ catch {
13
+ return {};
14
+ }
15
+ };
16
+ // The platform token of the issuer (aga_<jwt>) names the sub, no network.
17
+ const tokenSub = (auth, issuer) => {
18
+ const token = String(objectOf(objectOf(auth['platformPats'])[issuer])['token'] ?? '');
19
+ return subOf(parsed(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString())['sub']);
20
+ };
21
+ // The session as the cli checks it (get-session with its bearer); any failure is no user.
22
+ const sessionSub = async (issuer, bearer) => {
23
+ if (typeof bearer !== 'string' || !bearer)
24
+ return undefined;
25
+ const url = `${issuer}/api/auth/mcp/get-session`;
26
+ const headers = { authorization: `Bearer ${bearer}` };
27
+ const signal = AbortSignal.timeout(SESSION_MS);
28
+ const res = await fetch(url, { headers, signal, redirect: 'error' }).catch(() => undefined);
29
+ if (!res?.ok)
30
+ return void (await res?.body?.cancel());
31
+ return subOf(objectOf(await res.json().catch(() => null))['userId']);
32
+ };
33
+ const isOrigin = (value) => typeof value === 'string' && URL.canParse(value) && new URL(value).origin === value;
34
+ // The user of an auth.json text: only of its own issuer; no issuer (a session before cli 0.50.1) is none.
35
+ export const cliUserOf = async (text) => {
36
+ const auth = parsed(text);
37
+ const issuer = auth['issuer'];
38
+ if (!isOrigin(issuer))
39
+ return undefined;
40
+ return tokenSub(auth, issuer) ?? sessionSub(issuer, objectOf(auth['tokens'])['accessToken']);
41
+ };
42
+ export const readCliAuth = (configDir) => readFile(join(configDir, 'auth.json'), 'utf8').catch(() => '');
@@ -8,6 +8,7 @@ export interface DaemonOptions extends Partial<Limits> {
8
8
  version: string;
9
9
  startedBy: string;
10
10
  clockRate?: number;
11
+ shellDir?: string;
11
12
  }
12
13
  export interface Daemon {
13
14
  port: number;
@@ -4,6 +4,7 @@ import {} from 'node:net';
4
4
  import { createLog } from '../../log/log.js';
5
5
  import { closeNow, listen } from '../../server/serve.js';
6
6
  import { forkLaunch } from './child.js';
7
+ import { syncCliUser, watchCliUser } from './cli-user-watch.js';
7
8
  import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
8
9
  import { assertNoOtherDaemon } from './daemon-owner.js';
9
10
  import { bootInstallation, updateInstallation } from './installation.js';
@@ -15,6 +16,7 @@ import { pendingChanges } from './pending.js';
15
16
  import { serialQueue } from './queue.js';
16
17
  import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
17
18
  import { daemonApp } from './routes.js';
19
+ import { kitShellDir, readShell } from './shell-routes.js';
18
20
  import { runInstaller } from './installer-call.js';
19
21
  import { repairReload } from './reload-marker.js';
20
22
  import { halt } from './gate.js';
@@ -90,6 +92,12 @@ const depsOf = (opts, launch, origin, stopping) => ({
90
92
  queue: serialQueue(),
91
93
  pending: pendingChanges(),
92
94
  unsynced: new Set(),
95
+ user: {},
96
+ });
97
+ // A broken shell install costs the page, never the extensions.
98
+ const shellOf = (deps, dir) => readShell(dir).catch((err) => {
99
+ deps.log.warn('the shell package is not readable: no page at /', { reason: err.message });
100
+ return undefined;
93
101
  });
94
102
  // No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
95
103
  export const startDaemon = async (opts, launch) => {
@@ -101,7 +109,9 @@ export const startDaemon = async (opts, launch) => {
101
109
  const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
102
110
  const { entries, ...file } = await loadEntries(deps);
103
111
  const self = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL };
104
- const info = { ...launchMarks(launch), ...self, ...file };
112
+ const shellDir = opts.shellDir ?? kitShellDir();
113
+ const shell = shellDir ? { shell: await shellOf(deps, shellDir) } : {};
114
+ const info = { ...launchMarks(launch), ...self, ...file, ...shell };
105
115
  const hostToken = newHostToken();
106
116
  const app = daemonApp(deps, entries, () => port, info, hostToken);
107
117
  const server = await listen(app, port, '127.0.0.1');
@@ -109,7 +119,9 @@ export const startDaemon = async (opts, launch) => {
109
119
  const stop = stopper(server, entries, deps, life);
110
120
  try {
111
121
  await announce(opts, port, hostToken);
122
+ await deps.queue(() => syncCliUser(deps, entries));
112
123
  await deps.queue(() => boot(deps, entries));
124
+ life.signal.addEventListener('abort', watchCliUser(deps, entries));
113
125
  }
114
126
  catch (err) {
115
127
  await stop();
@@ -1,6 +1,7 @@
1
1
  import { type Express } from 'express';
2
2
  import { type Entries } from './entries.js';
3
3
  import { type Seal } from './seal.js';
4
+ import { type Shell } from './shell-routes.js';
4
5
  import { type SupervisorDeps } from './supervisor.js';
5
6
  export interface DaemonInfo {
6
7
  version: string;
@@ -12,5 +13,6 @@ export interface DaemonInfo {
12
13
  clockRate?: number;
13
14
  seal?: Seal;
14
15
  sealError?: string;
16
+ shell?: Shell;
15
17
  }
16
18
  export declare const healthRoutes: (app: Express, deps: SupervisorDeps, entries: Entries, info: DaemonInfo) => void;
@@ -1,20 +1,27 @@
1
1
  import {} from 'express';
2
2
  import { hostParts } from '../../manifest/parts.js';
3
3
  import { readManifest } from '../../manifest/read-manifest.js';
4
+ import { appRowOf } from './app-files.js';
4
5
  import { summary } from './entries.js';
5
6
  import { restartsOf } from './restart.js';
6
- import {} from './seal.js';
7
+ import { sealOfEntry } from './seal.js';
8
+ import {} from './shell-routes.js';
7
9
  import {} from './supervisor.js';
8
10
  // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
9
11
  const DAEMON_SERVICE = 'agentage-daemon';
10
12
  // Read at each call: a reload can change the package in its folder.
11
- const partsOf = async ({ dir }) => dir ? readManifest(dir).then(hostParts, () => []) : [];
12
- const reported = async (entry, info) => ({
13
- ...summary(entry),
14
- parts: await partsOf(entry),
15
- seal: info.seal ?? 'off',
16
- restarts: restartsOf(entry),
17
- });
13
+ const pkgOf = async ({ dir }) => dir ? readManifest(dir).catch(() => undefined) : undefined;
14
+ const partsOf = async (entry) => {
15
+ const pkg = await pkgOf(entry);
16
+ return pkg ? hostParts(pkg) : [];
17
+ };
18
+ // PD2: a git store's child is on with a child-process grant: partial; the daemon's status stays ok.
19
+ const reported = async (entry, info) => {
20
+ const pkg = await pkgOf(entry);
21
+ const seal = sealOfEntry(info.seal ?? 'off', pkg);
22
+ const parts = pkg ? hostParts(pkg) : [];
23
+ return { ...summary(entry), parts, seal, restarts: restartsOf(entry) };
24
+ };
18
25
  const installationOf = ({ invalid, unreadable, notJson }) => {
19
26
  if (unreadable)
20
27
  return { installation: 'unreadable', installationError: unreadable };
@@ -40,15 +47,22 @@ const healthOf = async (deps, entries, info) => {
40
47
  const status = statusOf(deps, entries, info);
41
48
  return { status, version: info.version, ...self, extensions, ...marks };
42
49
  };
43
- // C10 (D10): where each running extension answers, and its parts; anonymous, bare JSON.
44
- const discoveryOf = async (entries) => {
45
- const running = [...entries.values()].filter((e) => e.state === 'running');
46
- const listed = running.map(async (e) => ({
50
+ const rowOf = async (e) => {
51
+ const app = await appRowOf(e);
52
+ return {
47
53
  id: e.id,
48
54
  version: e.version,
55
+ state: e.state,
49
56
  parts: await partsOf(e),
50
- }));
51
- return { host: 'local', extensions: await Promise.all(listed) };
57
+ ...(app && { app }),
58
+ };
59
+ };
60
+ // C10 (D10): each running extension and each enabled one with an app (a crashed child keeps its nav row), its state; the shell.
61
+ const discoveryOf = async (entries, { shell }) => {
62
+ const rows = await Promise.all([...entries.values()].map(rowOf));
63
+ const extensions = rows.filter((row) => row.state === 'running' || row.app);
64
+ const served = shell && { shell: { package: shell.package, version: shell.version } };
65
+ return { host: 'local', ...served, extensions };
52
66
  };
53
67
  const HOST_DISCOVERY_PATH = '/.well-known/agentage-host.json';
54
68
  export const healthRoutes = (app, deps, entries, info) => {
@@ -56,6 +70,6 @@ export const healthRoutes = (app, deps, entries, info) => {
56
70
  res.set('Cache-Control', 'no-store').json(await healthOf(deps, entries, info));
57
71
  });
58
72
  app.get(HOST_DISCOVERY_PATH, async (_req, res) => {
59
- res.set('Cache-Control', 'no-store').json(await discoveryOf(entries));
73
+ res.set('Cache-Control', 'no-store').json(await discoveryOf(entries, info));
60
74
  });
61
75
  };
@@ -10,6 +10,7 @@ export declare const LIMITS: {
10
10
  crashLimit: number;
11
11
  crashWindowMs: number;
12
12
  healthyResetMs: number;
13
+ userPollMs: number;
13
14
  };
14
15
  export type Limits = typeof LIMITS;
15
16
  export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -22,6 +22,8 @@ export const LIMITS = {
22
22
  crashWindowMs: 600_000,
23
23
  // A child healthy this long has its restart count and exits reset.
24
24
  healthyResetMs: 600_000,
25
+ // How often auth.json is read: a sign-in or sign-out restarts the running children.
26
+ userPollMs: 2_000,
25
27
  };
26
28
  export const limitsOf = (given) => {
27
29
  const keys = Object.keys(LIMITS);
@@ -4,6 +4,9 @@ import { ok } from '../../envelope/envelope.js';
4
4
  import { BODY_LIMIT } from '../../server/app.js';
5
5
  import { errorHandler, notFound } from '../../server/errors.js';
6
6
  import { localOnly } from './guard.js';
7
+ import { ownAppOnly } from './app-header.js';
8
+ import { appRoutes } from './app-files.js';
9
+ import { isAppReload, reloadApp } from './app-reload.js';
7
10
  import { addExtension } from './add.js';
8
11
  import { listed } from './entries.js';
9
12
  import { healthRoutes } from './health-routes.js';
@@ -14,6 +17,8 @@ import {} from './pending.js';
14
17
  import { waitAtMost } from './queue.js';
15
18
  import { proxyTo } from './proxy.js';
16
19
  import { reloadExtension } from './reload.js';
20
+ import { shellEvents } from './shell-events.js';
21
+ import { shellRoutes } from './shell-routes.js';
17
22
  import { stopsNow } from './stopping.js';
18
23
  import {} from './supervisor.js';
19
24
  const reasonOf = (err) => err.details?.reason;
@@ -37,8 +42,14 @@ const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(d
37
42
  return fn();
38
43
  }));
39
44
  const purge = (q) => q['purge'] === 'true';
40
- const changes = (deps, entries, info, p) => {
41
- const run = runner(deps, info, p);
45
+ // Each change that went through tells the open shell pages to read discovery again (K7).
46
+ const changes = (deps, entries, info, events) => {
47
+ const queued = runner(deps, info, deps.pending);
48
+ const run = async (what, fn) => {
49
+ const done = await queued(what, fn);
50
+ events.send('extensions', { op: what.op, ...(what.id && { id: what.id }) });
51
+ return done;
52
+ };
42
53
  const id = (params) => String(params['id']);
43
54
  const add = async (req, res) => {
44
55
  const what = { op: 'install', ...named(req.body) };
@@ -54,30 +65,37 @@ const changes = (deps, entries, info, p) => {
54
65
  };
55
66
  const reload = async ({ params, body }, res) => {
56
67
  const what = { op: 'reload', id: id(params) };
68
+ if (isAppReload(body))
69
+ return void res.json(ok(await queued(what, () => reloadApp(entries, what.id, events))));
57
70
  res.json(ok(await run(what, () => reloadExtension(deps, entries, what.id, body))));
58
71
  };
59
72
  return { add, change, remove, reload };
60
73
  };
61
- const hostRoutes = (app, deps, entries, info, p) => {
74
+ const hostRoutes = (app, deps, entries, info, events) => {
62
75
  app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
63
76
  const json = express.json({ limit: BODY_LIMIT });
64
- const { add, change, remove, reload } = changes(deps, entries, info, p);
77
+ const { add, change, remove, reload } = changes(deps, entries, info, events);
65
78
  app.post('/host/extensions', json, add);
66
79
  app.patch('/host/extensions/:id', json, change);
67
80
  app.delete('/host/extensions/:id', remove);
68
81
  app.post('/host/extensions/:id/reload', json, reload);
69
82
  };
70
- // C5 and C1: /health, discovery, /host/* (host token), /api/{id}/* and /mcp/{id} to the child; Host and Origin first.
83
+ // C5 and C1: /health, discovery, /host/* (host token); /api, /mcp, /connector, /files of {id} to the child; S1.2 the shell and /app.
71
84
  export const daemonApp = (deps, entries, port, info, hostToken) => {
72
85
  const app = express();
73
86
  const proxy = proxyTo(entries, deps, hostToken);
74
87
  app.disable('x-powered-by');
75
88
  app.use(agcidMiddleware, localOnly(port));
76
- app.use('/api/:id', proxy);
89
+ app.use('/api/:id', ownAppOnly, proxy);
77
90
  app.use('/mcp/:id', proxy);
91
+ app.use('/connector/:id', ownAppOnly, proxy);
92
+ app.use('/files/:id', ownAppOnly, proxy);
78
93
  healthRoutes(app, deps, entries, info);
79
94
  app.use('/host', requireHostToken(hostToken));
80
- hostRoutes(app, deps, entries, info, deps.pending);
95
+ const events = shellEvents();
96
+ hostRoutes(app, deps, entries, info, events);
97
+ appRoutes(app, entries);
98
+ shellRoutes(app, { shell: info.shell, entries, events, user: deps.user });
81
99
  app.use(notFound);
82
100
  app.use(errorHandler(deps.log));
83
101
  return app;
@@ -1,4 +1,7 @@
1
- export type Seal = 'on' | 'off';
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ export type Seal = 'on' | 'off' | 'partial';
3
+ export declare const spawnsGit: (pkg: ExtensionPackage) => boolean;
4
+ export declare const sealOfEntry: (seal: Seal, pkg: ExtensionPackage | undefined) => Seal;
2
5
  export declare const sealOf: (version: string) => Seal;
3
6
  export declare const permissionFlag: (version: string) => boolean;
4
7
  export declare const sealOffReason: (version: string) => string;
@@ -11,6 +14,7 @@ interface SealAt {
11
14
  configDir: string;
12
15
  runDir: string;
13
16
  dataDir: string;
17
+ childProcess?: boolean;
14
18
  }
15
- export declare const sealFlags: ({ id, main, dir, configDir, runDir, dataDir }: SealAt) => string[];
19
+ export declare const sealFlags: (at: SealAt) => string[];
16
20
  export {};
@@ -1,7 +1,12 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join, parse, sep } from 'node:path';
4
+ import {} from '../../manifest/manifest.schema.js';
5
+ import { hasStore } from '../../manifest/parts.js';
4
6
  import { assertReach, real } from './seal-reach.js';
7
+ // G6 (PD2): a git store spawns git for each operation; no other package gets a child process.
8
+ export const spawnsGit = (pkg) => hasStore(pkg, 'git');
9
+ export const sealOfEntry = (seal, pkg) => seal === 'on' && pkg && spawnsGit(pkg) ? 'partial' : seal;
5
10
  // C2: the permission model with the bypass fixes of D2; the same rule as e2e sealFloorMet.
6
11
  const SEAL_FLOOR = 'Node 22.22.2 or 24.14.1';
7
12
  const versionOf = (version) => version.split('.').map(Number);
@@ -55,8 +60,9 @@ export const kitReadDirs = (main) => {
55
60
  const root = packageRoot(main);
56
61
  return [...new Set([root, upward(root).find(hasWorkspaces) ?? root])];
57
62
  };
58
- // C2: read kit, tree, run/{id}, data/{id}; write the last two; no child process, worker, addon, WASI, sqlite.
59
- export const sealFlags = ({ id, main, dir, configDir, runDir, dataDir }) => {
63
+ // C2: read kit, tree, run/{id}, data/{id}; write the last two; no worker, addon, WASI, sqlite; a child process for git only.
64
+ export const sealFlags = (at) => {
65
+ const { id, main, dir, configDir, runDir, dataDir } = at;
60
66
  const both = (paths) => [...new Set(paths.flatMap((path) => [path, real(path)]))];
61
67
  const writes = both([runDir, dataDir]);
62
68
  const kit = both([...kitReadDirs(main), treeOf(dir)]);
@@ -65,6 +71,7 @@ export const sealFlags = ({ id, main, dir, configDir, runDir, dataDir }) => {
65
71
  return [
66
72
  '--permission',
67
73
  '--no-experimental-sqlite',
74
+ ...(at.childProcess ? ['--allow-child-process'] : []),
68
75
  ...reads.map((path) => `--allow-fs-read=${path}`),
69
76
  ...writes.map((path) => `--allow-fs-write=${path}`),
70
77
  ];
@@ -0,0 +1,9 @@
1
+ import { type RequestHandler } from 'express';
2
+ export type ShellEvent = 'extensions' | 'app';
3
+ export interface ShellEvents {
4
+ send(event: ShellEvent, data: unknown): void;
5
+ stream: RequestHandler;
6
+ }
7
+ export declare const HEARTBEAT_MS = 25000;
8
+ export declare const STALLED_WRITES = 32;
9
+ export declare const shellEvents: (heartbeatMs?: number) => ShellEvents;
@@ -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);
@@ -16,7 +16,8 @@ import { hostClockRate } from '../worker/clock.js';
16
16
  import { localOnly } from './daemon/guard.js';
17
17
  import { hostPartsOf } from './host-parts.js';
18
18
  import { openHostStore, STORE_OPEN_MS } from './host-store.js';
19
- import { hostStoreChecks, openUrlStore } from './host-url-store.js';
19
+ import { hostStoreChecks } from './host-url-store.js';
20
+ import { openStore } from './open-store.js';
20
21
  const once = (fn) => {
21
22
  let done = false;
22
23
  return () => {
@@ -61,8 +62,8 @@ export const hostWith = async (dir, opts, extras) => {
61
62
  const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
62
63
  const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
63
64
  const at = { dir, dataDir: opts.dataDir, runDir: opts.runDir, openMs };
64
- const url = { dir, file: opts.storeUrlFile, openMs };
65
- const store = (await openUrlStore(pkg, url, log)) ?? (await openHostStore(pkg, at, log));
65
+ const store = (await openStore(pkg, { ...at, file: opts.storeUrlFile }, log)) ??
66
+ (await openHostStore(pkg, at, log));
66
67
  const onExit = once(opts.onExit ?? (() => undefined));
67
68
  const build = extras.build ?? (await hostBuildInfo({}, dir));
68
69
  const h = { dir, pkg, log, opts, extras, store, onExit, build };
@@ -0,0 +1,10 @@
1
+ import { type Log } from '../log/log.js';
2
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type HostStore } from './host-url-store.js';
4
+ export interface GitStoreAt {
5
+ dataDir: string;
6
+ runDir?: string;
7
+ openMs: number;
8
+ file?: string;
9
+ }
10
+ export declare const openGitStore: (pkg: ExtensionPackage, at: GitStoreAt, log: Log) => Promise<HostStore | undefined>;