@agentage/extension 0.14.0 → 0.15.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 (89) hide show
  1. package/README.md +3 -1
  2. package/dist/health/health.d.ts +2 -0
  3. package/dist/health/health.js +4 -2
  4. package/dist/health/health.schema.d.ts +9 -0
  5. package/dist/health/health.schema.js +3 -0
  6. package/dist/host/clock-rate.d.ts +1 -0
  7. package/dist/host/clock-rate.js +12 -0
  8. package/dist/host/daemon/add.js +24 -3
  9. package/dist/host/daemon/child-files.d.ts +20 -0
  10. package/dist/host/daemon/child-files.js +45 -0
  11. package/dist/host/daemon/child.d.ts +10 -4
  12. package/dist/host/daemon/child.js +63 -37
  13. package/dist/host/daemon/daemon-files.d.ts +3 -0
  14. package/dist/host/daemon/daemon-files.js +5 -1
  15. package/dist/host/daemon/daemon.d.ts +1 -0
  16. package/dist/host/daemon/daemon.js +21 -6
  17. package/dist/host/daemon/gate.d.ts +3 -0
  18. package/dist/host/daemon/gate.js +19 -0
  19. package/dist/host/daemon/guard.d.ts +2 -1
  20. package/dist/host/daemon/guard.js +16 -4
  21. package/dist/host/daemon/health-routes.d.ts +17 -0
  22. package/dist/host/daemon/health-routes.js +61 -0
  23. package/dist/host/daemon/host-token.d.ts +6 -0
  24. package/dist/host/daemon/host-token.js +28 -0
  25. package/dist/host/daemon/last-words.d.ts +2 -0
  26. package/dist/host/daemon/last-words.js +28 -0
  27. package/dist/host/daemon/limits.d.ts +4 -0
  28. package/dist/host/daemon/limits.js +7 -0
  29. package/dist/host/daemon/ops.js +4 -1
  30. package/dist/host/daemon/pending.d.ts +1 -1
  31. package/dist/host/daemon/proxy.d.ts +1 -1
  32. package/dist/host/daemon/proxy.js +16 -8
  33. package/dist/host/daemon/reload-marker.d.ts +8 -0
  34. package/dist/host/daemon/reload-marker.js +56 -0
  35. package/dist/host/daemon/reload-route.d.ts +4 -0
  36. package/dist/host/daemon/reload-route.js +21 -0
  37. package/dist/host/daemon/reload.d.ts +10 -0
  38. package/dist/host/daemon/reload.js +73 -0
  39. package/dist/host/daemon/restart.d.ts +14 -0
  40. package/dist/host/daemon/restart.js +59 -0
  41. package/dist/host/daemon/routes.d.ts +2 -10
  42. package/dist/host/daemon/routes.js +13 -31
  43. package/dist/host/daemon/run-lock.d.ts +1 -0
  44. package/dist/host/daemon/run-lock.js +15 -0
  45. package/dist/host/daemon/seal-reach.d.ts +2 -0
  46. package/dist/host/daemon/seal-reach.js +38 -0
  47. package/dist/host/daemon/seal.d.ts +16 -0
  48. package/dist/host/daemon/seal.js +71 -0
  49. package/dist/host/daemon/start-checks.d.ts +6 -0
  50. package/dist/host/daemon/start-checks.js +28 -0
  51. package/dist/host/daemon/supervisor.d.ts +9 -3
  52. package/dist/host/daemon/supervisor.js +33 -40
  53. package/dist/host/data-lock.d.ts +2 -1
  54. package/dist/host/data-lock.js +25 -6
  55. package/dist/host/host-env.d.ts +1 -0
  56. package/dist/host/host-env.js +2 -0
  57. package/dist/host/host-extension.d.ts +4 -0
  58. package/dist/host/host-extension.js +23 -43
  59. package/dist/host/host-parts.d.ts +25 -0
  60. package/dist/host/host-parts.js +75 -0
  61. package/dist/host/host-store.d.ts +3 -0
  62. package/dist/host/host-store.js +21 -2
  63. package/dist/host/main.js +2 -0
  64. package/dist/host/part-checks.d.ts +2 -0
  65. package/dist/host/part-checks.js +19 -0
  66. package/dist/host/serve-host.js +6 -3
  67. package/dist/manifest/parts.d.ts +3 -0
  68. package/dist/manifest/parts.js +3 -0
  69. package/dist/mcp/mcp-app.d.ts +4 -0
  70. package/dist/mcp/mcp-app.js +11 -11
  71. package/dist/runtime/part-mounts.d.ts +29 -0
  72. package/dist/runtime/part-mounts.js +52 -0
  73. package/dist/runtime/part-runners.d.ts +2 -15
  74. package/dist/runtime/part-runners.js +13 -58
  75. package/dist/server/app.d.ts +3 -0
  76. package/dist/server/app.js +16 -16
  77. package/dist/tool/check.d.ts +2 -0
  78. package/dist/tool/check.js +23 -8
  79. package/dist/tool/container-parts.d.ts +1 -1
  80. package/dist/tool/container-parts.js +6 -6
  81. package/dist/tool/format.js +15 -8
  82. package/dist/tool/kit-version.d.ts +2 -0
  83. package/dist/tool/kit-version.js +12 -0
  84. package/dist/worker/clock.d.ts +6 -0
  85. package/dist/worker/clock.js +21 -0
  86. package/dist/worker/scheduler.d.ts +1 -0
  87. package/dist/worker/scheduler.js +6 -2
  88. package/package.json +1 -1
  89. package/schemas/health.schema.json +17 -0
@@ -0,0 +1,28 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import {} from 'node:http';
3
+ import {} from 'express';
4
+ import { fail } from '../../envelope/envelope.js';
5
+ // D11: a new token at each daemon start, in daemon.json (0600); a sealed child cannot read it.
6
+ export const newHostToken = () => randomBytes(32).toString('base64url');
7
+ const bearerOf = (headers) => {
8
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(headers.authorization ?? '');
9
+ return match?.[1];
10
+ };
11
+ // Digests first: timingSafeEqual needs equal lengths, and the length of the token stays unseen.
12
+ const sameToken = (given, token) => timingSafeEqual(createHash('sha256').update(given).digest(), createHash('sha256').update(token).digest());
13
+ // True when the request carries the host token: the proxy then keeps it from the child.
14
+ export const carriesHostToken = (headers, token) => {
15
+ const given = bearerOf(headers);
16
+ return given !== undefined && sameToken(given, token);
17
+ };
18
+ // A cli that sends no token was made before the host token (C3): the fix is a newer cli or a restart.
19
+ export const NO_TOKEN = 'host token required: this cli is older than the daemon, update @agentage/cli or run "agentage daemon restart"';
20
+ // Every /host/* route: 401 with no bearer, 403 with another one.
21
+ export const requireHostToken = (token) => (req, _res, next) => {
22
+ const given = bearerOf(req.headers);
23
+ if (given === undefined)
24
+ throw fail('UNAUTHORIZED', NO_TOKEN);
25
+ if (!sameToken(given, token))
26
+ throw fail('FORBIDDEN', 'The host token is not valid');
27
+ next();
28
+ };
@@ -0,0 +1,2 @@
1
+ import { type Exit } from './child.js';
2
+ export declare const lastWords: (tail: string, how: Exit) => string;
@@ -0,0 +1,28 @@
1
+ import {} from './child.js';
2
+ // Lines that never say why: blanks, stack frames, error properties, the Node version, the hint.
3
+ const NOISE = [
4
+ /^\s*$/,
5
+ /^\s+at /,
6
+ /^\s*[{}]\s*$/,
7
+ /^\s+[\w$'"]+: /,
8
+ /^Node\.js v\d/,
9
+ /^\(Use `node/,
10
+ ];
11
+ // A log row below error (listening, a request, a warning) is not why a child exited.
12
+ const QUIET = /^\{.*"level":"(warn|info|debug|trace)"/;
13
+ const msgOf = (line) => {
14
+ try {
15
+ return String(JSON.parse(line).msg ?? line);
16
+ }
17
+ catch {
18
+ return line;
19
+ }
20
+ };
21
+ // The last line that says why (an error line, a log row's msg, or the thrown text): from stderr.
22
+ export const lastWords = (tail, how) => {
23
+ const lines = tail.split('\n').map((l) => l.trimEnd());
24
+ const line = lines.reverse().find((l) => !QUIET.test(l) && !NOISE.some((re) => re.test(l)));
25
+ if (line)
26
+ return msgOf(line).replace(/^[A-Za-z]*Error(?: \[[A-Z_]+\])?: /, '');
27
+ return `exited with ${how.signal ? `signal ${how.signal}` : `code ${how.code}`}`;
28
+ };
@@ -6,6 +6,10 @@ export declare const LIMITS: {
6
6
  gateMs: number;
7
7
  answerMs: number;
8
8
  installMs: number;
9
+ backoffMs: number[];
10
+ crashLimit: number;
11
+ crashWindowMs: number;
12
+ healthyResetMs: number;
9
13
  };
10
14
  export type Limits = typeof LIMITS;
11
15
  export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -15,6 +15,13 @@ export const LIMITS = {
15
15
  // One Installer call (POST, PATCH, each entry at boot), and a change queued behind others:
16
16
  // above the cli's npm bound (10 min), below its client wait (12 min).
17
17
  installMs: 660_000,
18
+ // C6: the waits before each restart of a child that exited; the last one repeats.
19
+ backoffMs: [1_000, 2_000, 4_000, 8_000, 16_000],
20
+ // C6: this many exits inside crashWindowMs is failed, with no more restarts.
21
+ crashLimit: 5,
22
+ crashWindowMs: 600_000,
23
+ // A child healthy this long has its restart count and exits reset.
24
+ healthyResetMs: 600_000,
18
25
  };
19
26
  export const limitsOf = (given) => {
20
27
  const keys = Object.keys(LIMITS);
@@ -3,7 +3,8 @@ import { z } from 'zod';
3
3
  import { fail } from '../../envelope/envelope.js';
4
4
  import { parse } from '../../envelope/parse.js';
5
5
  import { SecretNameSchema } from '../../manifest/primitives.schema.js';
6
- import { purgeData } from './daemon-files.js';
6
+ import { clearRunDir, purgeData } from './daemon-files.js';
7
+ import { unmarkReload } from './reload-marker.js';
7
8
  import { entryOf, summary } from './entries.js';
8
9
  import { unsynced, writeAll } from './write-all.js';
9
10
  import { runInstaller } from './installer-call.js';
@@ -83,6 +84,8 @@ export const removeExtension = async (deps, entries, id, purge) => {
83
84
  await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
84
85
  entries.delete(id);
85
86
  await halt(entry, deps.drainMs);
87
+ await unmarkReload(deps.configDir, id);
88
+ await clearRunDir(deps.configDir, id);
86
89
  if (purge)
87
90
  await purgeData(deps.configDir, id);
88
91
  return { id };
@@ -1,4 +1,4 @@
1
- export type PendingOp = 'install' | 'update' | 'remove';
1
+ export type PendingOp = 'install' | 'update' | 'remove' | 'reload';
2
2
  export interface Pending {
3
3
  op: PendingOp;
4
4
  id?: string;
@@ -3,4 +3,4 @@ import { type RequestHandler } from 'express';
3
3
  import { type Entries } from './entries.js';
4
4
  import { type Limits } from './limits.js';
5
5
  export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
6
- export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">) => RequestHandler;
6
+ export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">, hostToken?: string) => RequestHandler;
@@ -2,6 +2,7 @@ import { request, } from 'node:http';
2
2
  import { setTimeout as sleep } from 'node:timers/promises';
3
3
  import {} from 'express';
4
4
  import { fail } from '../../envelope/envelope.js';
5
+ import { carriesHostToken } from './host-token.js';
5
6
  import { enter } from './lane.js';
6
7
  import {} from './entries.js';
7
8
  import {} from './limits.js';
@@ -44,9 +45,16 @@ const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did no
44
45
  status: 504,
45
46
  retryAfter: undefined,
46
47
  });
47
- const requestTo = (req, lane) => {
48
- const { method, originalUrl: path } = req;
48
+ // D11: the host token is for the daemon; a child never sees it, also when a client sends it here.
49
+ const forChild = (req, hostToken) => {
49
50
  const headers = endToEnd(req.headers);
51
+ if (hostToken && carriesHostToken(req.headers, hostToken))
52
+ delete headers['authorization'];
53
+ return headers;
54
+ };
55
+ const requestTo = (req, lane, hostToken) => {
56
+ const { method, originalUrl: path } = req;
57
+ const headers = forChild(req, hostToken);
50
58
  const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
51
59
  return request(options);
52
60
  };
@@ -68,10 +76,9 @@ const relay = (upstream, res, next, ms) => {
68
76
  });
69
77
  return () => clearTimeout(timer);
70
78
  };
71
- // Streams the request to the child as it came (path and query kept), no pooled connection.
72
- const forward = (req, res, next, to, ms) => {
79
+ const forward = (req, res, next, { to, ms, hostToken }) => {
73
80
  const { lane, leave } = to;
74
- const upstream = requestTo(req, lane);
81
+ const upstream = requestTo(req, lane, hostToken);
75
82
  const stop = relay(upstream, res, next, ms);
76
83
  upstream.on('error', leave);
77
84
  // A client that went away aborts the request to the child too.
@@ -83,7 +90,8 @@ const forward = (req, res, next, to, ms) => {
83
90
  });
84
91
  req.pipe(upstream);
85
92
  };
86
- export const proxyTo = (entries, limits) => async (req, res, next) => {
87
- const taken = await laneFor(entries, String(req.params['id']), limits.gateMs);
88
- forward(req, res, next, taken, limits.answerMs);
93
+ // ANY /api/{id}/* and /mcp/{id} (C1): the same lane, the same refusals (404 unknown, 503 not running).
94
+ export const proxyTo = (entries, limits, hostToken) => async (req, res, next) => {
95
+ const to = await laneFor(entries, String(req.params['id']), limits.gateMs);
96
+ forward(req, res, next, { to, ms: limits.answerMs, hostToken });
89
97
  };
@@ -0,0 +1,8 @@
1
+ import { type Log } from '../../log/log.js';
2
+ import { type Entry } from './supervisor.js';
3
+ export declare const markReload: (configDir: string, id: string, dir: string) => Promise<void>;
4
+ export declare const unmarkReload: (configDir: string, id: string) => Promise<void>;
5
+ export declare const swapIn: (dir: string) => Promise<boolean>;
6
+ export declare const swapBack: (dir: string) => Promise<void>;
7
+ export declare const confirmReload: (configDir: string, id: string, dir: string) => Promise<void>;
8
+ export declare const repairReload: (configDir: string, entry: Entry, log: Log) => Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import {} from '../../log/log.js';
5
+ import {} from './supervisor.js';
6
+ // D14 (revised): the child runs dist/; dist.next/ is the watcher's tree and stays; dist.prev/ is the last good.
7
+ const DIST = 'dist';
8
+ const NEXT = 'dist.next';
9
+ const PREV = 'dist.prev';
10
+ const markerOf = (configDir, id) => join(configDir, 'run', id, 'reload.json');
11
+ const gone = (path) => rm(path, { recursive: true, force: true });
12
+ // Written once a stale dist.prev is gone: marker and dist.prev together mean a swap not confirmed.
13
+ export const markReload = async (configDir, id, dir) => {
14
+ await gone(join(dir, PREV));
15
+ const marker = markerOf(configDir, id);
16
+ await mkdir(join(marker, '..'), { recursive: true });
17
+ await writeFile(marker, JSON.stringify({ id, dir, complete: false, at: new Date().toISOString() }));
18
+ };
19
+ export const unmarkReload = (configDir, id) => gone(markerOf(configDir, id));
20
+ // dist to dist.prev, a copy of dist.next to dist; false when there is no new build (a plain restart).
21
+ export const swapIn = async (dir) => {
22
+ if (!existsSync(join(dir, NEXT)))
23
+ return false;
24
+ if (existsSync(join(dir, DIST)))
25
+ await rename(join(dir, DIST), join(dir, PREV));
26
+ await cp(join(dir, NEXT), join(dir, DIST), { recursive: true });
27
+ return true;
28
+ };
29
+ // The copied build goes, the last good one comes back; with no dist.prev, dist is never touched.
30
+ export const swapBack = async (dir) => {
31
+ if (!existsSync(join(dir, PREV)))
32
+ return;
33
+ await gone(join(dir, DIST));
34
+ await rename(join(dir, PREV), join(dir, DIST));
35
+ };
36
+ // The new build is healthy: the marker first, then the old build.
37
+ export const confirmReload = async (configDir, id, dir) => {
38
+ await unmarkReload(configDir, id);
39
+ await gone(join(dir, PREV));
40
+ };
41
+ const markedDir = async (configDir, id) => {
42
+ const text = await readFile(markerOf(configDir, id), 'utf8');
43
+ return JSON.parse(text).dir;
44
+ };
45
+ // At boot: a marker of this row's folder with a dist.prev is a cut reload, put back to the last good build.
46
+ export const repairReload = async (configDir, entry, log) => {
47
+ const dir = entry.install.source;
48
+ if (!dir || !existsSync(markerOf(configDir, entry.id)))
49
+ return;
50
+ const ours = (await markedDir(configDir, entry.id).catch(() => undefined)) === dir;
51
+ if (ours && existsSync(join(dir, PREV))) {
52
+ await swapBack(dir);
53
+ log.warn('a cut reload was put back to the last good build', { id: entry.id });
54
+ }
55
+ await unmarkReload(configDir, entry.id);
56
+ };
@@ -0,0 +1,4 @@
1
+ import { type Express } from 'express';
2
+ import { type Entries } from './entries.js';
3
+ import { type SupervisorDeps } from './supervisor.js';
4
+ export declare const reloadRoute: (app: Express, deps: SupervisorDeps, entries: Entries, readable: () => Promise<void>) => void;
@@ -0,0 +1,21 @@
1
+ import express, {} from 'express';
2
+ import { ok } from '../../envelope/envelope.js';
3
+ import { BODY_LIMIT } from '../../server/app.js';
4
+ import {} from './entries.js';
5
+ import { waitAtMost } from './queue.js';
6
+ import { reloadExtension } from './reload.js';
7
+ import { stopsNow } from './stopping.js';
8
+ import {} from './supervisor.js';
9
+ // In the change queue (a second reload waits); refused like every change while installation.json is unreadable.
10
+ export const reloadRoute = (app, deps, entries, readable) => {
11
+ app.post('/host/extensions/:id/reload', express.json({ limit: BODY_LIMIT }), async (req, res) => {
12
+ const id = String(req.params['id']);
13
+ const run = () => waitAtMost(deps.queue, deps.installMs, async () => {
14
+ if (deps.stopping.signal.aborted)
15
+ throw stopsNow();
16
+ await readable();
17
+ return reloadExtension(deps, entries, id, req.body);
18
+ });
19
+ res.json(ok(await deps.pending.track({ op: 'reload', id }, run)));
20
+ });
21
+ };
@@ -0,0 +1,10 @@
1
+ import { type Entries } from './entries.js';
2
+ import { type SupervisorDeps } from './supervisor.js';
3
+ export declare const reloadExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
4
+ refused?: string | undefined;
5
+ reloaded: boolean;
6
+ pid?: number | undefined;
7
+ id: string;
8
+ version: string;
9
+ state: import("./supervisor.js").State;
10
+ }>;
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import { parse } from '../../envelope/parse.js';
4
+ import { entryOf } from './entries.js';
5
+ import { confirmReload, markReload, swapBack, swapIn, unmarkReload } from './reload-marker.js';
6
+ import { resetRestarts } from './restart.js';
7
+ import { halt, hold, startEntry } from './supervisor.js';
8
+ const ReloadSchema = z.strictObject({});
9
+ // Only a linked working copy has a build to reload; a disabled one stays stopped.
10
+ const folderOf = (entry) => {
11
+ const dir = entry.install.source;
12
+ if (!dir)
13
+ throw fail('VALIDATION_ERROR', `${entry.id} is not a folder: only a linked folder reloads`);
14
+ if (entry.install.enabled === false)
15
+ throw fail('CONFLICT', `${entry.id} is disabled: enable it first`);
16
+ return dir;
17
+ };
18
+ const answer = (entry, refused) => ({
19
+ id: entry.id,
20
+ version: entry.version,
21
+ state: entry.state,
22
+ ...(entry.lane && { pid: entry.lane.child.pid }),
23
+ reloaded: refused === undefined,
24
+ ...(refused !== undefined && { refused }),
25
+ });
26
+ // Not healthy: the copied build goes, the last good build starts again.
27
+ const restoreLast = async (deps, entry, dir, swapped) => {
28
+ if (swapped)
29
+ await swapBack(dir);
30
+ await unmarkReload(deps.configDir, entry.id);
31
+ if (swapped)
32
+ await startEntry(deps, entry);
33
+ };
34
+ // The new child runs: what is left to clean is best-effort, never a second start.
35
+ const settle = async (deps, entry, dir) => {
36
+ await confirmReload(deps.configDir, entry.id, dir).catch((err) => deps.log.warn('a reload left dist.prev or its marker', { id: entry.id, reason: err.message }));
37
+ resetRestarts(entry);
38
+ return answer(entry);
39
+ };
40
+ const tryNew = async (deps, entry, dir) => {
41
+ await markReload(deps.configDir, entry.id, dir);
42
+ const swapped = await swapIn(dir);
43
+ const err = await startEntry(deps, entry);
44
+ if (!err)
45
+ return settle(deps, entry, dir);
46
+ await restoreLast(deps, entry, dir, swapped);
47
+ return answer(entry, err.message.split('\n')[0]);
48
+ };
49
+ // A file step failed (EPERM, EBUSY): the last good build runs again, the answer says why.
50
+ const fileFailed = async (deps, entry, dir, err) => {
51
+ await swapBack(dir).catch((again) => deps.log.warn('a reload could not put the last good build back', { reason: again.message }));
52
+ await unmarkReload(deps.configDir, entry.id).catch(() => undefined);
53
+ await startEntry(deps, entry);
54
+ return answer(entry, err.message.split('\n')[0]);
55
+ };
56
+ // D14: stop and wait for the exit (one writer on the store), swap the builds, start, wait healthy.
57
+ const reloadIn = async (deps, entry, dir) => {
58
+ await halt(entry, deps.drainMs);
59
+ return tryNew(deps, entry, dir).catch((err) => fileFailed(deps, entry, dir, err));
60
+ };
61
+ // POST /host/extensions/{id}/reload, body {}: requests wait at the gate and go to the new child.
62
+ export const reloadExtension = async (deps, entries, id, body) => {
63
+ parse(ReloadSchema, body ?? {}, 'Invalid body');
64
+ const entry = entryOf(entries, id);
65
+ const dir = folderOf(entry);
66
+ const release = hold(entry);
67
+ try {
68
+ return await reloadIn(deps, entry, dir);
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ };
@@ -0,0 +1,14 @@
1
+ import { type Exit } from './child.js';
2
+ import { type Lane } from './lane.js';
3
+ import { type Entry, type SupervisorDeps } from './supervisor.js';
4
+ export interface Retry {
5
+ timer: NodeJS.Timeout;
6
+ }
7
+ type Again = () => Promise<void>;
8
+ export declare const restartsOf: (entry: Entry) => number;
9
+ export declare const cancelRestart: (entry: Entry) => void;
10
+ export declare const resetRestarts: (entry: Entry) => void;
11
+ export declare const healthyFor: (deps: SupervisorDeps, entry: Entry, lane: Lane) => void;
12
+ export declare const reasonOf: (how: Exit) => string;
13
+ export declare const crashed: (deps: SupervisorDeps, entry: Entry, why: string, again: Again) => void;
14
+ export {};
@@ -0,0 +1,59 @@
1
+ import {} from './child.js';
2
+ import {} from './lane.js';
3
+ import {} from './supervisor.js';
4
+ // C6: the restarts since the last enable, update, configure or reload (/health reads it).
5
+ export const restartsOf = (entry) => entry.restarts ?? 0;
6
+ export const cancelRestart = (entry) => {
7
+ if (entry.retry)
8
+ clearTimeout(entry.retry.timer);
9
+ entry.retry = undefined;
10
+ };
11
+ // A new start the owner asked for: the exits and the backoff begin again.
12
+ export const resetRestarts = (entry) => {
13
+ cancelRestart(entry);
14
+ Object.assign(entry, { exits: [], restarts: 0 });
15
+ };
16
+ // Healthy for healthyResetMs on the same child: the past exits no longer count.
17
+ export const healthyFor = (deps, entry, lane) => {
18
+ const reset = () => entry.lane === lane && Object.assign(entry, { exits: [], restarts: 0 });
19
+ setTimeout(reset, deps.healthyResetMs).unref();
20
+ };
21
+ export const reasonOf = (how) => how.words || `the process exited (${how.signal ? `signal ${how.signal}` : `code ${how.code}`})`;
22
+ // The backoff grows with each restart since the reset; the last value repeats.
23
+ const delayOf = (deps, restarts) => deps.backoffMs[Math.min(restarts, deps.backoffMs.length - 1)] ?? 0;
24
+ const giveUp = (deps, entry, why) => {
25
+ const min = Math.round(deps.crashWindowMs / 60_000);
26
+ const error = `exited ${deps.crashLimit} times in ${min} min: ${why}`;
27
+ Object.assign(entry, { state: 'failed', error });
28
+ deps.log.warn('extension failed: too many exits', { id: entry.id, reason: why });
29
+ };
30
+ // In the queue, so it never runs inside a change; a change, remove, reload or stop since cancels it.
31
+ const run = async (deps, entry, retry, again) => {
32
+ if (entry.retry !== retry || entry.lane || deps.stopping.signal.aborted)
33
+ return;
34
+ entry.retry = undefined;
35
+ if (entry.install.enabled === false)
36
+ return;
37
+ entry.restarts = restartsOf(entry) + 1;
38
+ deps.log.info('extension restarts', { id: entry.id, restarts: entry.restarts });
39
+ await again();
40
+ };
41
+ const schedule = (deps, entry, ms, again) => {
42
+ const retry = {};
43
+ const fire = () => void deps.queue(() => run(deps, entry, retry, again)).catch(() => undefined);
44
+ retry.timer = setTimeout(fire, ms);
45
+ retry.timer.unref();
46
+ entry.retry = retry;
47
+ };
48
+ // A child that was the route exited (or a restart did not start): restart after the backoff, or failed.
49
+ export const crashed = (deps, entry, why, again) => {
50
+ const now = Date.now();
51
+ const exits = [...(entry.exits ?? []), now].filter((at) => at > now - deps.crashWindowMs);
52
+ entry.exits = exits;
53
+ if (exits.length >= deps.crashLimit)
54
+ return giveUp(deps, entry, why);
55
+ const ms = delayOf(deps, restartsOf(entry));
56
+ Object.assign(entry, { state: 'starting', error: `${why}: restart in ${ms} ms` });
57
+ deps.log.warn('extension process exited', { id: entry.id, reason: why, restartMs: ms });
58
+ schedule(deps, entry, ms, again);
59
+ };
@@ -1,13 +1,5 @@
1
1
  import { type Express } from 'express';
2
2
  import { type Entries } from './entries.js';
3
+ import { type DaemonInfo } from './health-routes.js';
3
4
  import { type SupervisorDeps } from './supervisor.js';
4
- interface DaemonInfo {
5
- version: string;
6
- pid: number;
7
- protocol: number;
8
- invalid: boolean;
9
- unreadable?: string;
10
- notJson?: boolean;
11
- }
12
- export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo) => Express;
13
- export {};
5
+ export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo, hostToken: string) => Express;
@@ -5,44 +5,23 @@ import { BODY_LIMIT } from '../../server/app.js';
5
5
  import { errorHandler, notFound } from '../../server/errors.js';
6
6
  import { localOnly } from './guard.js';
7
7
  import { addExtension } from './add.js';
8
- import { listed, summary } from './entries.js';
8
+ import { listed } from './entries.js';
9
+ import { healthRoutes } from './health-routes.js';
10
+ import { requireHostToken } from './host-token.js';
9
11
  import { assertReadable } from './installation.js';
10
12
  import { changeExtension, removeExtension } from './ops.js';
11
13
  import {} from './pending.js';
12
14
  import { waitAtMost } from './queue.js';
13
15
  import { proxyTo } from './proxy.js';
16
+ import { reloadRoute } from './reload-route.js';
14
17
  import { stopsNow } from './stopping.js';
15
18
  import {} from './supervisor.js';
16
- // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
17
- const DAEMON_SERVICE = 'agentage-daemon';
18
- const installationOf = ({ invalid, unreadable, notJson }) => {
19
- if (unreadable)
20
- return { installation: 'unreadable', installationError: unreadable };
21
- return invalid || notJson ? { installation: 'invalid' } : {};
22
- };
23
19
  const reasonOf = (err) => err.details?.reason;
24
20
  // A refusal for a file that turned not JSON shows in /health until a change reads the file again.
25
21
  const checkReadable = (deps, info) => assertReadable(deps.configDir, info.unreadable).then(() => void (info.notJson = false), (err) => {
26
22
  info.notJson = reasonOf(err) === 'not JSON';
27
23
  throw err;
28
24
  });
29
- const healthOf = (deps, entries, info) => {
30
- const all = [...entries.values()];
31
- const settled = all.every((e) => e.state === 'running' || e.state === 'disabled');
32
- const synced = !deps.unsynced.size;
33
- const clean = !info.invalid && !info.unreadable && !info.notJson;
34
- const status = settled && synced && clean ? 'ok' : 'degraded';
35
- const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
36
- const extensions = all.map(summary);
37
- const changing = deps.pending.list();
38
- const busy = changing.length ? { pending: changing } : {};
39
- const marks = {
40
- ...busy,
41
- ...(!synced && { unsynced: [...deps.unsynced] }),
42
- ...installationOf(info),
43
- };
44
- return { status, version: info.version, ...self, extensions, ...marks };
45
- };
46
25
  // What a POST body names, for /health: the id, or the folder.
47
26
  const named = (body) => {
48
27
  const { id, source } = (body ?? {});
@@ -82,16 +61,19 @@ const hostRoutes = (app, deps, entries, info, p) => {
82
61
  app.post('/host/extensions', json, add);
83
62
  app.patch('/host/extensions/:id', json, change);
84
63
  app.delete('/host/extensions/:id', remove);
64
+ reloadRoute(app, deps, entries, () => checkReadable(deps, info));
85
65
  };
86
- // C5: /health, /host/extensions, and /api/{id}/* to the child of that id; Host and Origin first.
87
- export const daemonApp = (deps, entries, port, info) => {
66
+ // C5 and C1: /health, discovery, /host/* (host token), /api/{id}/* and /mcp/{id} to the child; Host and Origin first.
67
+ export const daemonApp = (deps, entries, port, info, hostToken) => {
88
68
  const app = express();
89
- const pending = deps.pending;
69
+ const proxy = proxyTo(entries, deps, hostToken);
90
70
  app.disable('x-powered-by');
91
71
  app.use(agcidMiddleware, localOnly(port));
92
- app.use('/api/:id', proxyTo(entries, deps));
93
- app.get('/health', (_req, res) => void res.set('Cache-Control', 'no-store').json(healthOf(deps, entries, info)));
94
- hostRoutes(app, deps, entries, info, pending);
72
+ app.use('/api/:id', proxy);
73
+ app.use('/mcp/:id', proxy);
74
+ healthRoutes(app, deps, entries, info);
75
+ app.use('/host', requireHostToken(hostToken));
76
+ hostRoutes(app, deps, entries, info, deps.pending);
95
77
  app.use(notFound);
96
78
  app.use(errorHandler(deps.log));
97
79
  return app;
@@ -0,0 +1 @@
1
+ export declare const clearRunLock: (lock: string, runDir: string) => Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { readFile, unlink } from 'node:fs/promises';
2
+ const pidIn = (lock) => readFile(lock, 'utf8').then(Number, () => 0);
3
+ // Linux: a child of this run folder has it in its env; a reused pid or a zombie does not.
4
+ const childOf = async (pid, runDir) => {
5
+ if (process.platform !== 'linux')
6
+ return true;
7
+ const env = await readFile(`/proc/${pid}/environ`, 'utf8').catch(() => '');
8
+ return env.split('\0').includes(`AGENTAGE_RUN_DIR=${runDir}`);
9
+ };
10
+ // The daemon starts one child per id at a time: a lock not held by a child of this id is left over.
11
+ export const clearRunLock = async (lock, runDir) => {
12
+ const pid = await pidIn(lock);
13
+ if (pid > 0 && !(await childOf(pid, runDir)))
14
+ await unlink(lock).catch(() => undefined);
15
+ };
@@ -0,0 +1,2 @@
1
+ export declare const real: (path: string) => string;
2
+ export declare const assertReach: (reads: string[], writes: string[], configDir: string, id: string) => void;
@@ -0,0 +1,38 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
+ import { fail } from '../../envelope/envelope.js';
4
+ // A path is checked as given and modules load from the real path: a symlinked folder needs both.
5
+ export const real = (path) => {
6
+ try {
7
+ return realpathSync(path);
8
+ }
9
+ catch {
10
+ return path;
11
+ }
12
+ };
13
+ // True when path is folder or inside it.
14
+ const within = (path, folder) => {
15
+ const rel = relative(folder, path);
16
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
17
+ };
18
+ // The tree folders the cli installs into: the shared 0.51 tree, or one tree per id@version.
19
+ const ownTree = (grant, configDir, id) => {
20
+ const [first, second, third] = relative(join(configDir, 'extensions'), grant).split(sep);
21
+ if (first === 'trees')
22
+ return !!second && !second.startsWith('.');
23
+ const name = first === 'packages' && second === 'trees' ? third : undefined;
24
+ return !!name && name.startsWith(`${id}@`) && name.length > id.length + 1;
25
+ };
26
+ // Inside the config dir only the extension's own tree holds no secret, row or other id's folder.
27
+ const exposes = (grant, configDir, id) => within(configDir, grant) || (within(grant, configDir) && !ownTree(grant, configDir, id));
28
+ const refused = (path, why) => fail('VALIDATION_ERROR', `seal: the folder ${path} ${why}`);
29
+ // Node reads a * in a grant as a wildcard; a read grant on the config dir (or above it) shows daemon.json and secrets.json.
30
+ export const assertReach = (reads, writes, configDir, id) => {
31
+ const star = [...reads, ...writes].find((path) => path.includes('*'));
32
+ if (star)
33
+ throw refused(star, 'has a * that Node reads as a wildcard');
34
+ const configs = [configDir, real(configDir)];
35
+ const open = reads.find((grant) => configs.some((config) => exposes(grant, config, id)));
36
+ if (open)
37
+ throw refused(open, 'would expose the agentage config folder');
38
+ };
@@ -0,0 +1,16 @@
1
+ export type Seal = 'on' | 'off';
2
+ export declare const SEAL_FLOOR = "Node 22.22.2 or 24.14.1";
3
+ export declare const sealOf: (version: string) => Seal;
4
+ export declare const permissionFlag: (version: string) => boolean;
5
+ export declare const sealOffReason: (version: string) => string;
6
+ export declare const treeOf: (dir: string) => string;
7
+ export declare const kitReadDirs: (main: string) => string[];
8
+ export interface SealAt {
9
+ id: string;
10
+ main: string;
11
+ dir: string;
12
+ configDir: string;
13
+ runDir: string;
14
+ dataDir: string;
15
+ }
16
+ export declare const sealFlags: ({ id, main, dir, configDir, runDir, dataDir }: SealAt) => string[];