@agentage/extension 0.14.0 → 0.15.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 (105) hide show
  1. package/README.md +3 -1
  2. package/dist/contracts/index.d.ts +1 -1
  3. package/dist/contracts/index.js +1 -1
  4. package/dist/discovery/discovery.d.ts +10 -25
  5. package/dist/discovery/discovery.js +7 -1
  6. package/dist/discovery/discovery.schema.d.ts +45 -0
  7. package/dist/discovery/discovery.schema.js +33 -4
  8. package/dist/discovery/served-extras.d.ts +8 -0
  9. package/dist/discovery/served-extras.js +10 -0
  10. package/dist/health/health.d.ts +2 -0
  11. package/dist/health/health.js +4 -2
  12. package/dist/health/health.schema.d.ts +9 -0
  13. package/dist/health/health.schema.js +3 -0
  14. package/dist/host/clock-rate.d.ts +1 -0
  15. package/dist/host/clock-rate.js +12 -0
  16. package/dist/host/daemon/add.js +29 -4
  17. package/dist/host/daemon/child-files.d.ts +20 -0
  18. package/dist/host/daemon/child-files.js +45 -0
  19. package/dist/host/daemon/child.d.ts +10 -4
  20. package/dist/host/daemon/child.js +68 -43
  21. package/dist/host/daemon/daemon-files.d.ts +3 -0
  22. package/dist/host/daemon/daemon-files.js +5 -1
  23. package/dist/host/daemon/daemon.d.ts +1 -0
  24. package/dist/host/daemon/daemon.js +21 -6
  25. package/dist/host/daemon/gate.d.ts +3 -0
  26. package/dist/host/daemon/gate.js +19 -0
  27. package/dist/host/daemon/guard.d.ts +2 -1
  28. package/dist/host/daemon/guard.js +16 -4
  29. package/dist/host/daemon/health-routes.d.ts +17 -0
  30. package/dist/host/daemon/health-routes.js +61 -0
  31. package/dist/host/daemon/host-token.d.ts +6 -0
  32. package/dist/host/daemon/host-token.js +28 -0
  33. package/dist/host/daemon/last-words.d.ts +2 -0
  34. package/dist/host/daemon/last-words.js +28 -0
  35. package/dist/host/daemon/limits.d.ts +4 -0
  36. package/dist/host/daemon/limits.js +7 -0
  37. package/dist/host/daemon/ops.js +4 -1
  38. package/dist/host/daemon/pending.d.ts +1 -1
  39. package/dist/host/daemon/proxy.d.ts +1 -1
  40. package/dist/host/daemon/proxy.js +16 -8
  41. package/dist/host/daemon/redact-stream.d.ts +4 -0
  42. package/dist/host/daemon/redact-stream.js +24 -0
  43. package/dist/host/daemon/reload-marker.d.ts +8 -0
  44. package/dist/host/daemon/reload-marker.js +56 -0
  45. package/dist/host/daemon/reload-route.d.ts +4 -0
  46. package/dist/host/daemon/reload-route.js +21 -0
  47. package/dist/host/daemon/reload.d.ts +10 -0
  48. package/dist/host/daemon/reload.js +73 -0
  49. package/dist/host/daemon/restart.d.ts +14 -0
  50. package/dist/host/daemon/restart.js +59 -0
  51. package/dist/host/daemon/routes.d.ts +2 -10
  52. package/dist/host/daemon/routes.js +13 -31
  53. package/dist/host/daemon/run-lock.d.ts +1 -0
  54. package/dist/host/daemon/run-lock.js +15 -0
  55. package/dist/host/daemon/seal-reach.d.ts +2 -0
  56. package/dist/host/daemon/seal-reach.js +38 -0
  57. package/dist/host/daemon/seal.d.ts +16 -0
  58. package/dist/host/daemon/seal.js +71 -0
  59. package/dist/host/daemon/start-checks.d.ts +7 -0
  60. package/dist/host/daemon/start-checks.js +29 -0
  61. package/dist/host/daemon/supervisor.d.ts +9 -3
  62. package/dist/host/daemon/supervisor.js +33 -40
  63. package/dist/host/data-lock.d.ts +2 -1
  64. package/dist/host/data-lock.js +25 -6
  65. package/dist/host/host-env.d.ts +1 -0
  66. package/dist/host/host-env.js +2 -0
  67. package/dist/host/host-extension.d.ts +6 -0
  68. package/dist/host/host-extension.js +28 -44
  69. package/dist/host/host-parts.d.ts +25 -0
  70. package/dist/host/host-parts.js +82 -0
  71. package/dist/host/host-store.d.ts +3 -0
  72. package/dist/host/host-store.js +21 -2
  73. package/dist/host/main.js +2 -0
  74. package/dist/host/part-checks.d.ts +2 -0
  75. package/dist/host/part-checks.js +19 -0
  76. package/dist/host/serve-host.js +10 -6
  77. package/dist/manifest/parts.d.ts +3 -0
  78. package/dist/manifest/parts.js +3 -0
  79. package/dist/mcp/mcp-app.d.ts +4 -0
  80. package/dist/mcp/mcp-app.js +11 -11
  81. package/dist/runtime/part-mounts.d.ts +31 -0
  82. package/dist/runtime/part-mounts.js +57 -0
  83. package/dist/runtime/part-runners.d.ts +2 -15
  84. package/dist/runtime/part-runners.js +13 -58
  85. package/dist/server/app.d.ts +5 -3
  86. package/dist/server/app.js +16 -17
  87. package/dist/tool/build.d.ts +1 -0
  88. package/dist/tool/build.js +3 -2
  89. package/dist/tool/check.d.ts +3 -1
  90. package/dist/tool/check.js +25 -9
  91. package/dist/tool/container-parts.d.ts +1 -1
  92. package/dist/tool/container-parts.js +6 -6
  93. package/dist/tool/format.d.ts +1 -0
  94. package/dist/tool/format.js +17 -8
  95. package/dist/tool/kit-version.d.ts +2 -0
  96. package/dist/tool/kit-version.js +12 -0
  97. package/dist/tool/record-extras.js +5 -12
  98. package/dist/worker/clock.d.ts +6 -0
  99. package/dist/worker/clock.js +21 -0
  100. package/dist/worker/scheduler.d.ts +1 -0
  101. package/dist/worker/scheduler.js +6 -2
  102. package/package.json +1 -1
  103. package/schemas/extension-discovery.schema.json +61 -34
  104. package/schemas/extension-record.schema.json +1 -1
  105. package/schemas/health.schema.json +17 -0
@@ -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) => [grant, real(grant)].some((path) => configs.some((config) => exposes(path, 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[];
@@ -0,0 +1,71 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, parse, sep } from 'node:path';
4
+ import { assertReach, real } from './seal-reach.js';
5
+ // C2: the permission model with the bypass fixes of D2; the same rule as e2e sealFloorMet.
6
+ export const SEAL_FLOOR = 'Node 22.22.2 or 24.14.1';
7
+ const versionOf = (version) => version.split('.').map(Number);
8
+ const atLeast = (version, major, minor, patch) => {
9
+ const [a = 0, b = 0, c = 0] = versionOf(version);
10
+ return a === major && (b > minor || (b === minor && c >= patch));
11
+ };
12
+ // An odd major has no known fix release: off; an even major above 24 is on.
13
+ export const sealOf = (version) => {
14
+ const [major = 0] = versionOf(version);
15
+ if (major === 22)
16
+ return atLeast(version, 22, 22, 2) ? 'on' : 'off';
17
+ if (major === 24)
18
+ return atLeast(version, 24, 14, 1) ? 'on' : 'off';
19
+ return major > 24 && major % 2 === 0 ? 'on' : 'off';
20
+ };
21
+ // --permission is a stable flag from 22.13.0 and 23.5.0: below the floor it still limits, seal off.
22
+ export const permissionFlag = (version) => {
23
+ const [major = 0] = versionOf(version);
24
+ return major >= 24 || atLeast(version, 22, 13, 0) || atLeast(version, 23, 5, 0);
25
+ };
26
+ export const sealOffReason = (version) => `seal off: ${SEAL_FLOOR} needed, this is Node ${version}`;
27
+ const NODE_MODULES = `${sep}node_modules${sep}`;
28
+ // The folder that holds the node_modules a path sits in (a tree of the cli); else the path itself.
29
+ export const treeOf = (dir) => {
30
+ const at = dir.lastIndexOf(NODE_MODULES);
31
+ return at < 0 ? dir : dir.slice(0, at);
32
+ };
33
+ const hasWorkspaces = (dir) => {
34
+ try {
35
+ return 'workspaces' in JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ };
41
+ // The folders from start up, never above the user's home nor the root.
42
+ const upward = (start) => {
43
+ const found = [start];
44
+ for (let dir = start; dir !== homedir() && dir !== parse(dir).root;)
45
+ found.push((dir = dirname(dir)));
46
+ return found;
47
+ };
48
+ // The nearest folder with a package.json; none: the folder of the file.
49
+ const packageRoot = (file) => upward(dirname(file)).find((dir) => existsSync(join(dir, 'package.json'))) ?? dirname(file);
50
+ // Installed: the node_modules that holds the kit. A checkout: its package and its workspace root.
51
+ export const kitReadDirs = (main) => {
52
+ const at = main.lastIndexOf(NODE_MODULES);
53
+ if (at >= 0)
54
+ return [main.slice(0, at + NODE_MODULES.length - 1)];
55
+ const root = packageRoot(main);
56
+ return [...new Set([root, upward(root).find(hasWorkspaces) ?? root])];
57
+ };
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 }) => {
60
+ const both = (paths) => [...new Set(paths.flatMap((path) => [path, real(path)]))];
61
+ const writes = both([runDir, dataDir]);
62
+ const kit = both([...kitReadDirs(main), treeOf(dir)]);
63
+ assertReach(kit, writes, configDir, id);
64
+ const reads = [...new Set([...kit, ...writes])];
65
+ return [
66
+ '--permission',
67
+ '--no-experimental-sqlite',
68
+ ...reads.map((path) => `--allow-fs-read=${path}`),
69
+ ...writes.map((path) => `--allow-fs-write=${path}`),
70
+ ];
71
+ };
@@ -0,0 +1,7 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ export declare const NEEDS_SECRET = "NEEDS_SECRET";
3
+ export declare const assertSecrets: (pkg: ExtensionPackage, secrets: Record<string, string>) => void;
4
+ export declare const needsSecret: (err: unknown) => boolean;
5
+ export declare const healthy: (port: number, ms: number) => Promise<void>;
6
+ export declare const maskedForms: (secrets: Record<string, string>) => string[];
7
+ export declare const redact: (text: string, secrets: Record<string, string>) => string;
@@ -0,0 +1,29 @@
1
+ import {} from '../../manifest/manifest.schema.js';
2
+ import { hostParts, mountedIn } from '../../manifest/parts.js';
3
+ export const NEEDS_SECRET = 'NEEDS_SECRET';
4
+ // C6: a declared secret of a server part with no value; the daemon checks it before the fork.
5
+ export const assertSecrets = (pkg, secrets) => {
6
+ const names = new Set(hostParts(pkg).flatMap((part) => mountedIn(pkg, part)));
7
+ const missing = [...names].find((name) => !secrets[name]);
8
+ if (missing)
9
+ throw Object.assign(new Error(`needs secret ${missing}`), { code: NEEDS_SECRET });
10
+ };
11
+ export const needsSecret = (err) => err?.code === NEEDS_SECRET;
12
+ // Healthy before it gets the route: the child's own /health answers 200.
13
+ export const healthy = async (port, ms) => {
14
+ const signal = AbortSignal.timeout(ms);
15
+ const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
16
+ if (err.name === 'TimeoutError')
17
+ throw new Error(`health did not answer in ${ms} ms`);
18
+ const cause = err.cause?.code ?? err.message;
19
+ throw new Error(`health could not be reached (${cause})`);
20
+ });
21
+ if (res.status !== 200)
22
+ throw new Error(`health answered ${res.status}`);
23
+ };
24
+ // Each value raw and as it shows inside a JSON log row (quotes, backslashes escaped).
25
+ export const maskedForms = (secrets) => [...new Set(Object.values(secrets).flatMap((v) => [v, JSON.stringify(v).slice(1, -1)]))]
26
+ .filter((value) => value.length >= 4)
27
+ .sort((a, b) => b.length - a.length);
28
+ // A secret value this child was given never reaches error, /health, the list or the log.
29
+ export const redact = (text, secrets) => maskedForms(secrets).reduce((out, value) => out.split(value).join('***'), text);
@@ -5,7 +5,9 @@ import { type Lane } from './lane.js';
5
5
  import { type Limits } from './limits.js';
6
6
  import { type PendingChanges } from './pending.js';
7
7
  import { type Queue } from './queue.js';
8
+ import { type Retry } from './restart.js';
8
9
  import { type Stopping } from './stopping.js';
10
+ export { halt, hold } from './gate.js';
9
11
  export interface InstallSpec {
10
12
  id: string;
11
13
  version?: string;
@@ -26,6 +28,9 @@ export interface Entry {
26
28
  error?: string;
27
29
  lane?: Lane;
28
30
  gate?: Promise<void>;
31
+ exits?: number[];
32
+ restarts?: number;
33
+ retry?: Retry;
29
34
  }
30
35
  export interface Values {
31
36
  settings: Record<string, unknown>;
@@ -48,7 +53,8 @@ export interface SupervisorDeps extends Limits {
48
53
  unsynced: Set<string>;
49
54
  }
50
55
  export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
51
- export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
52
- export declare const hold: (entry: Entry) => (() => void);
56
+ export declare const launchFor: (deps: SupervisorDeps, entry: Entry, install: InstallEntry, values: Values, given?: string) => Promise<Lane>;
57
+ export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<Error | undefined>;
58
+ export declare const restore: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
59
+ export declare const startFailed: (entry: Entry, err: unknown) => import("../../envelope/envelope.js").Failure;
53
60
  export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next, undo?: () => Promise<unknown>) => Promise<void>;
54
- export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
@@ -4,12 +4,16 @@ import { readManifest } from '../../manifest/read-manifest.js';
4
4
  import {} from './child.js';
5
5
  import { dataDirOf, readValues } from './daemon-files.js';
6
6
  import {} from './installation.js';
7
- import { laneOf, retire } from './lane.js';
7
+ import { halt } from './gate.js';
8
+ import { laneOf } from './lane.js';
8
9
  import {} from './limits.js';
9
10
  import { runInstaller } from './installer-call.js';
10
11
  import {} from './pending.js';
11
12
  import {} from './queue.js';
13
+ import { crashed, healthyFor, reasonOf, resetRestarts } from './restart.js';
14
+ import { assertSecrets, healthy, redact } from './start-checks.js';
12
15
  import {} from './stopping.js';
16
+ export { halt, hold } from './gate.js';
13
17
  export const valuesOf = async (configDir, id) => ({
14
18
  settings: await readValues(configDir, 'settings', id),
15
19
  secrets: (await readValues(configDir, 'secrets', id)),
@@ -24,82 +28,77 @@ const dirOf = async (deps, entry, install, given) => {
24
28
  return entry.dir;
25
29
  return (await runInstaller(deps, { id: entry.id, version: install.version })).dir;
26
30
  };
27
- // Healthy before it gets the route: the child's own /health answers 200.
28
- const healthy = async (port, ms) => {
29
- const signal = AbortSignal.timeout(ms);
30
- const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
31
- if (err.name === 'TimeoutError')
32
- throw new Error(`health did not answer in ${ms} ms`);
33
- const cause = err.cause?.code ?? err.message;
34
- throw new Error(`health could not be reached (${cause})`);
35
- });
36
- if (res.status !== 200)
37
- throw new Error(`health answered ${res.status}`);
38
- };
39
31
  // A new child for install with values, healthy; the entry learns the version the package has.
40
- const launchFor = async (deps, entry, install, values, given) => {
32
+ export const launchFor = async (deps, entry, install, values, given) => {
41
33
  const dir = await dirOf(deps, entry, install, given);
42
34
  const pkg = await readManifest(dir);
35
+ assertSecrets(pkg, values.secrets);
43
36
  const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...values };
44
- const child = await deps.launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs });
37
+ const child = await deps
38
+ .launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs })
39
+ .catch((err) => Promise.reject(Object.assign(err, { message: redact(err.message, values.secrets) })));
45
40
  await healthy(child.port, deps.healthMs).catch(async (err) => {
46
41
  await child.stop();
47
42
  throw err;
48
43
  });
49
44
  Object.assign(entry, { dir, version: pkg.version });
50
45
  const lane = laneOf(child);
51
- void child.exited.then((how) => exitedEarly(deps, entry, lane, how));
46
+ const words = (how) => redact(reasonOf(how), values.secrets);
47
+ void child.exited.then((how) => exitedEarly(deps, entry, lane, words(how)));
48
+ healthyFor(deps, entry, lane);
52
49
  return lane;
53
50
  };
54
- // A child that exits while it is the route is failed; a retired one was detached first.
55
- const exitedEarly = (deps, entry, lane, how) => {
51
+ // A child that exits while it is the route restarts (C6); a retired one was detached first.
52
+ const exitedEarly = (deps, entry, lane, why) => {
56
53
  if (entry.lane !== lane)
57
54
  return;
58
- const why = how.signal ? `signal ${how.signal}` : `code ${how.code}`;
59
- Object.assign(entry, { lane: undefined, state: 'failed', error: `the process exited (${why})` });
60
- deps.log.warn('extension process exited', { id: entry.id });
55
+ entry.lane = undefined;
56
+ crashed(deps, entry, why, () => restartEntry(deps, entry));
61
57
  };
62
58
  const failed = (deps, entry, err) => {
63
59
  Object.assign(entry, { state: 'failed', error: err.message });
64
60
  deps.log.warn('extension failed to start', { id: entry.id, reason: entry.error });
65
61
  };
66
- // The install and values of installation.json, as they are on disk.
62
+ // The install and values of installation.json, as they are on disk; the error when it failed.
67
63
  export const startEntry = async (deps, entry) => {
68
64
  entry.state = 'starting';
69
65
  try {
70
66
  const values = await valuesOf(deps.configDir, entry.id);
71
67
  entry.lane = await launchFor(deps, entry, entry.install, values);
72
68
  Object.assign(entry, { state: 'running', error: undefined });
69
+ return undefined;
73
70
  }
74
71
  catch (err) {
75
72
  failed(deps, entry, err);
73
+ return err;
76
74
  }
77
75
  };
78
- // New requests of the extension wait here (the proxy gives up after gateMs) until release.
79
- export const hold = (entry) => {
80
- let release = () => undefined;
81
- entry.gate = new Promise((resolve) => (release = resolve));
82
- return () => {
83
- entry.gate = undefined;
84
- release();
85
- };
76
+ // A restart that does not start counts as one more exit.
77
+ const restartEntry = async (deps, entry) => {
78
+ const err = await startEntry(deps, entry);
79
+ if (err)
80
+ crashed(deps, entry, err.message, () => restartEntry(deps, entry));
86
81
  };
87
82
  // The old install again after a refused change; a disabled one stays stopped.
88
- const restore = async (deps, entry) => {
83
+ export const restore = async (deps, entry) => {
89
84
  if (entry.install.enabled === false)
90
85
  entry.state = 'disabled';
91
86
  else
92
87
  await startEntry(deps, entry);
93
88
  };
94
- const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
95
- code: 'START_FAILED',
96
- });
89
+ // C6: the envelope of a refused start; reason is the child's own words.
90
+ export const startFailed = (entry, err) => {
91
+ const reason = err.message;
92
+ const details = { code: 'START_FAILED', reason };
93
+ return fail('VALIDATION_ERROR', `${entry.id} failed to start: ${reason}`, { details });
94
+ };
97
95
  // One writer per data folder (the caller holds the gate): stop the old child, start the new one.
98
96
  export const swap = async (deps, entry, to, undo = async () => undefined) => {
99
97
  try {
100
98
  await halt(entry, deps.drainMs);
101
99
  entry.lane = await launchFor(deps, entry, to.install, to.values, to.dir);
102
100
  Object.assign(entry, { state: 'running', error: undefined });
101
+ resetRestarts(entry);
103
102
  }
104
103
  catch (err) {
105
104
  await undo();
@@ -107,9 +106,3 @@ export const swap = async (deps, entry, to, undo = async () => undefined) => {
107
106
  throw startFailed(entry, err);
108
107
  }
109
108
  };
110
- // Detached first, so its exit is not a failure; then drained and stopped.
111
- export const halt = async (entry, drainMs) => {
112
- const lane = entry.lane;
113
- entry.lane = undefined;
114
- await retire(lane, drainMs);
115
- };
@@ -1,3 +1,4 @@
1
1
  export declare const DATA_DIR_LOCKED = "DATA_DIR_LOCKED";
2
2
  export declare const EMPTY_LOCK_MS = 1000;
3
- export declare const lockDataDir: (dataDir: string) => Promise<() => Promise<void>>;
3
+ export declare const clearOldLock: (lock: string) => Promise<void>;
4
+ export declare const lockDataDir: (dataDir: string, lock?: string) => Promise<() => Promise<void>>;
@@ -1,13 +1,25 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { rmSync } from 'node:fs';
2
+ import { readFileSync, rmSync } from 'node:fs';
3
3
  import { link, readFile, unlink, writeFile } from 'node:fs/promises';
4
4
  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) => {
10
+ if (process.platform !== 'linux')
11
+ return false;
12
+ try {
13
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
14
+ return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ };
8
20
  const alive = (pid) => {
9
21
  try {
10
- return process.kill(pid, 0);
22
+ return process.kill(pid, 0) && !zombie(pid);
11
23
  }
12
24
  catch (err) {
13
25
  return err.code === 'EPERM';
@@ -27,7 +39,7 @@ const holder = async (file) => {
27
39
  return Number(pid);
28
40
  };
29
41
  const live = (lock, pid) => pid === process.pid ? held.has(lock) : pid > 0 && alive(pid);
30
- const locked = (lock, pid) => Object.assign(new Error(`${lock.slice(0, -5)} is open in process ${pid}`), {
42
+ const locked = (lock, pid) => Object.assign(new Error(`${lock.replace(/[/\\]?(store)?\.lock$/, '')} is open in process ${pid}`), {
31
43
  code: DATA_DIR_LOCKED,
32
44
  pid,
33
45
  });
@@ -99,6 +111,14 @@ const inTurn = (lock, fn) => {
99
111
  void tail.then(() => turns.get(lock) === tail && turns.delete(lock));
100
112
  return run;
101
113
  };
114
+ // A lock of an older kit (beside the folder, out of a sealed child's reach): dead is removed, live refuses.
115
+ export const clearOldLock = async (lock) => {
116
+ const pid = await holder(lock);
117
+ if (pid > 0 && live(lock, pid))
118
+ throw locked(lock, pid);
119
+ if (pid > 0)
120
+ await unlink(lock).catch(() => undefined);
121
+ };
102
122
  const acquire = async (lock) => {
103
123
  if (await take(lock))
104
124
  return;
@@ -109,9 +129,8 @@ const acquire = async (lock) => {
109
129
  if (!(await take(lock)))
110
130
  throw locked(lock, await holder(lock));
111
131
  };
112
- // PGlite has one writer per folder: <dataDir>.lock holds the pid; a dead holder's lock is taken over.
113
- export const lockDataDir = async (dataDir) => {
114
- const lock = `${dataDir}.lock`;
132
+ // PGlite has one writer per folder: the lock (<dataDir>.lock unless given) holds the pid; a dead holder's lock is taken over.
133
+ export const lockDataDir = async (dataDir, lock = `${dataDir}.lock`) => {
115
134
  await inTurn(lock, () => acquire(lock));
116
135
  // Sync, so no other taker in this process sees the file without its entry in held.
117
136
  return async () => {
@@ -6,6 +6,7 @@ export declare const hostEnvOf: (env: Env) => {
6
6
  port: number;
7
7
  bind: string;
8
8
  dataDir: string;
9
+ runDir: string;
9
10
  settings: Record<string, unknown>;
10
11
  secretsDir: string;
11
12
  origin: string;
@@ -21,6 +21,8 @@ export const hostEnvOf = (env) => {
21
21
  port,
22
22
  bind: env['AGENTAGE_HOST_BIND'] === 'all' ? '0.0.0.0' : '127.0.0.1',
23
23
  dataDir: env['AGENTAGE_DATA_DIR'] ?? '',
24
+ // C2: the daemon's run/{id}; the store lock goes there (a sealed child cannot write beside data/{id}).
25
+ runDir: env['AGENTAGE_RUN_DIR'] ?? '',
24
26
  settings: env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {},
25
27
  secretsDir: env['AGENTAGE_SECRETS_DIR'] || SECRETS_DIR,
26
28
  origin: env['AGENTAGE_ORIGIN'] || `http://127.0.0.1${port ? `:${port}` : ''}`,