@agentage/extension 0.20.1 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/auth/part-auth.js +4 -5
  2. package/dist/context/context.d.ts +0 -1
  3. package/dist/host/child-env.d.ts +11 -0
  4. package/dist/host/child-env.js +12 -0
  5. package/dist/host/{daemon/guard.js → guard.js} +1 -1
  6. package/dist/host/host-extension.js +1 -1
  7. package/dist/host/host-main.d.ts +1 -0
  8. package/dist/host/host-main.js +3 -0
  9. package/dist/host/index.d.ts +1 -5
  10. package/dist/host/index.js +1 -5
  11. package/dist/host/kit-shell.d.ts +1 -0
  12. package/dist/host/kit-shell.js +8 -0
  13. package/dist/host/serve-host.js +1 -1
  14. package/dist/internal/index.d.ts +29 -0
  15. package/dist/internal/index.js +30 -0
  16. package/dist/runtime/part-mounts.d.ts +0 -1
  17. package/dist/runtime/part-mounts.js +1 -1
  18. package/dist/runtime/run-part.js +0 -2
  19. package/dist/server/app.d.ts +0 -1
  20. package/dist/server/app.js +4 -5
  21. package/dist/shell/dist/index.html +1 -1
  22. package/dist/shell/dist/shell.css +1 -1
  23. package/dist/tool/check.js +3 -0
  24. package/dist/tool/recipe.js +2 -2
  25. package/dist/tool/up/gateway.js +0 -3
  26. package/package.json +5 -1
  27. package/dist/host/daemon/add.d.ts +0 -11
  28. package/dist/host/daemon/add.js +0 -93
  29. package/dist/host/daemon/app-files.d.ts +0 -8
  30. package/dist/host/daemon/app-files.js +0 -34
  31. package/dist/host/daemon/app-header.d.ts +0 -2
  32. package/dist/host/daemon/app-header.js +0 -12
  33. package/dist/host/daemon/app-reload.d.ts +0 -10
  34. package/dist/host/daemon/app-reload.js +0 -18
  35. package/dist/host/daemon/child-files.d.ts +0 -20
  36. package/dist/host/daemon/child-files.js +0 -53
  37. package/dist/host/daemon/child.d.ts +0 -30
  38. package/dist/host/daemon/child.js +0 -126
  39. package/dist/host/daemon/cli-user-watch.d.ts +0 -9
  40. package/dist/host/daemon/cli-user-watch.js +0 -47
  41. package/dist/host/daemon/cli-user.d.ts +0 -2
  42. package/dist/host/daemon/cli-user.js +0 -42
  43. package/dist/host/daemon/daemon-files.d.ts +0 -20
  44. package/dist/host/daemon/daemon-files.js +0 -46
  45. package/dist/host/daemon/daemon-owner.d.ts +0 -1
  46. package/dist/host/daemon/daemon-owner.js +0 -32
  47. package/dist/host/daemon/daemon.d.ts +0 -19
  48. package/dist/host/daemon/daemon.js +0 -137
  49. package/dist/host/daemon/entries.d.ts +0 -21
  50. package/dist/host/daemon/entries.js +0 -24
  51. package/dist/host/daemon/gate.d.ts +0 -3
  52. package/dist/host/daemon/gate.js +0 -19
  53. package/dist/host/daemon/health-routes.d.ts +0 -18
  54. package/dist/host/daemon/health-routes.js +0 -75
  55. package/dist/host/daemon/host-token.d.ts +0 -6
  56. package/dist/host/daemon/host-token.js +0 -28
  57. package/dist/host/daemon/installation.d.ts +0 -35
  58. package/dist/host/daemon/installation.js +0 -90
  59. package/dist/host/daemon/installer-call.d.ts +0 -21
  60. package/dist/host/daemon/installer-call.js +0 -48
  61. package/dist/host/daemon/json-file.d.ts +0 -6
  62. package/dist/host/daemon/json-file.js +0 -90
  63. package/dist/host/daemon/lane.d.ts +0 -9
  64. package/dist/host/daemon/lane.js +0 -24
  65. package/dist/host/daemon/last-words.d.ts +0 -2
  66. package/dist/host/daemon/last-words.js +0 -28
  67. package/dist/host/daemon/limits.d.ts +0 -16
  68. package/dist/host/daemon/limits.js +0 -31
  69. package/dist/host/daemon/ops.d.ts +0 -12
  70. package/dist/host/daemon/ops.js +0 -94
  71. package/dist/host/daemon/patch-values.d.ts +0 -6
  72. package/dist/host/daemon/patch-values.js +0 -39
  73. package/dist/host/daemon/pending.d.ts +0 -15
  74. package/dist/host/daemon/pending.js +0 -18
  75. package/dist/host/daemon/proxy.d.ts +0 -11
  76. package/dist/host/daemon/proxy.js +0 -106
  77. package/dist/host/daemon/queue.d.ts +0 -3
  78. package/dist/host/daemon/queue.js +0 -27
  79. package/dist/host/daemon/redact-stream.d.ts +0 -4
  80. package/dist/host/daemon/redact-stream.js +0 -24
  81. package/dist/host/daemon/reload-marker.d.ts +0 -8
  82. package/dist/host/daemon/reload-marker.js +0 -57
  83. package/dist/host/daemon/reload.d.ts +0 -10
  84. package/dist/host/daemon/reload.js +0 -72
  85. package/dist/host/daemon/restart.d.ts +0 -14
  86. package/dist/host/daemon/restart.js +0 -59
  87. package/dist/host/daemon/routes.d.ts +0 -6
  88. package/dist/host/daemon/routes.js +0 -101
  89. package/dist/host/daemon/run-lock.d.ts +0 -1
  90. package/dist/host/daemon/run-lock.js +0 -15
  91. package/dist/host/daemon/seal-reach.d.ts +0 -2
  92. package/dist/host/daemon/seal-reach.js +0 -38
  93. package/dist/host/daemon/seal.d.ts +0 -20
  94. package/dist/host/daemon/seal.js +0 -93
  95. package/dist/host/daemon/shell-events.d.ts +0 -9
  96. package/dist/host/daemon/shell-events.js +0 -36
  97. package/dist/host/daemon/shell-routes.d.ts +0 -29
  98. package/dist/host/daemon/shell-routes.js +0 -68
  99. package/dist/host/daemon/sign-in-page.d.ts +0 -3
  100. package/dist/host/daemon/sign-in-page.js +0 -30
  101. package/dist/host/daemon/start-checks.d.ts +0 -6
  102. package/dist/host/daemon/start-checks.js +0 -29
  103. package/dist/host/daemon/stopping.d.ts +0 -10
  104. package/dist/host/daemon/stopping.js +0 -28
  105. package/dist/host/daemon/supervisor.d.ts +0 -59
  106. package/dist/host/daemon/supervisor.js +0 -107
  107. package/dist/host/daemon/write-all.d.ts +0 -8
  108. package/dist/host/daemon/write-all.js +0 -45
  109. /package/dist/host/{daemon/guard.d.ts → guard.d.ts} +0 -0
@@ -1,137 +0,0 @@
1
- import { mkdir } from 'node:fs/promises';
2
- import {} from 'node:http';
3
- import {} from 'node:net';
4
- import { createLog } from '../../log/log.js';
5
- import { closeNow, listen } from '../../server/serve.js';
6
- import { forkLaunch } from './child.js';
7
- import { syncCliUser, watchCliUser } from './cli-user-watch.js';
8
- import { shellEvents } from './shell-events.js';
9
- import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
10
- import { assertNoOtherDaemon } from './daemon-owner.js';
11
- import { bootInstallation, updateInstallation } from './installation.js';
12
- import {} from './entries.js';
13
- import { newHostToken } from './host-token.js';
14
- import { sealOffReason } from './seal.js';
15
- import { limitsOf } from './limits.js';
16
- import { pendingChanges } from './pending.js';
17
- import { serialQueue } from './queue.js';
18
- import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
19
- import { daemonApp } from './routes.js';
20
- import { KIT_VERSION } from '../../tool/kit-version.js';
21
- import { kitShellDir, readShell } from './shell-routes.js';
22
- import { runInstaller } from './installer-call.js';
23
- import { repairReload } from './reload-marker.js';
24
- import { halt } from './gate.js';
25
- import { startEntry } from './supervisor.js';
26
- export const DAEMON_PORT = 4243;
27
- const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
28
- // The valid rows of installation.json; a bad file is kept aside, replaced by them, and in /health.
29
- const loadEntries = async (deps) => {
30
- const { doc, invalid, unreadable } = await bootInstallation(deps.configDir);
31
- if (invalid)
32
- await updateInstallation(deps.configDir, () => doc, deps.lockMs).catch(warnOf(deps));
33
- const entries = new Map();
34
- for (const install of doc.extensions) {
35
- const state = install.enabled === false ? 'disabled' : 'starting';
36
- entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
37
- }
38
- return { entries, invalid, unreadable };
39
- };
40
- // A disabled entry gets its folder (configure and enable work); a failure is kept as its error.
41
- const resolveDir = async (deps, entry) => {
42
- const { id, install } = entry;
43
- if (install.source)
44
- return void (entry.dir = install.source);
45
- await runInstaller(deps, { id, version: install.version }).then((got) => void Object.assign(entry, { dir: got.dir, version: got.version, error: undefined }), (err) => void (entry.error = err.message));
46
- };
47
- // Enabled folders first (no installer), then enabled versions one at a time, disabled ones last.
48
- const boot = async (deps, entries) => {
49
- const all = [...entries.values()];
50
- const off = all.filter((e) => e.state === 'disabled');
51
- const on = all.filter((e) => e.state !== 'disabled');
52
- const ordered = [...on.filter((e) => e.install.source), ...on.filter((e) => !e.install.source)];
53
- for (const entry of all)
54
- await repairReload(deps.configDir, entry, deps.log).catch(warnOf(deps));
55
- for (const entry of ordered)
56
- await startEntry(deps, entry);
57
- for (const entry of off)
58
- await resolveDir(deps, entry);
59
- };
60
- const stopper = (server, entries, deps, life) => {
61
- let stopped;
62
- const stop = async () => {
63
- life.abort();
64
- await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
65
- await stopAll(deps.stopping);
66
- await closeNow(server);
67
- await removeDaemonFile(deps.configDir);
68
- };
69
- return () => (stopped ??= stop());
70
- };
71
- // C4: how a client finds this daemon; D11: the host token, only in this 0600 file.
72
- const announce = ({ configDir, version, startedBy }, port, hostToken) => writeDaemonFile(configDir, {
73
- pid: process.pid,
74
- port,
75
- version,
76
- protocol: DAEMON_PROTOCOL,
77
- startedBy,
78
- hostToken,
79
- });
80
- // One source: the launch that forks the children (its test clock, its seal).
81
- const launchMarks = (launch) => ({
82
- ...(launch.clockRate && launch.clockRate !== 1 && { clockRate: launch.clockRate }),
83
- ...(launch.seal && { seal: launch.seal }),
84
- ...(launch.seal === 'off' && { sealError: sealOffReason(launch.node ?? process.versions.node) }),
85
- });
86
- const depsOf = (opts, launch, origin, stopping) => ({
87
- configDir: opts.configDir,
88
- launch: launchUnlessStopping(stopping, launch),
89
- stopping,
90
- install: opts.install,
91
- log: createLog({ extension: 'host', part: 'api', version: opts.version }),
92
- origin,
93
- ...limitsOf(opts),
94
- queue: serialQueue(),
95
- pending: pendingChanges(),
96
- unsynced: new Set(),
97
- user: {},
98
- });
99
- // A broken shell install costs the page, never the extensions.
100
- const shellOf = (deps, dir, version) => readShell(dir, version).catch((err) => {
101
- deps.log.warn('the shell package is not readable: no page at /', { reason: err.message });
102
- return undefined;
103
- });
104
- // No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
105
- export const startDaemon = async (opts, launch) => {
106
- await mkdir(opts.configDir, { recursive: true });
107
- // A live daemon owns the folder: a second one fails before it writes any file there.
108
- await assertNoOtherDaemon(opts.configDir);
109
- let port = opts.port ?? DAEMON_PORT;
110
- const life = new AbortController();
111
- const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
112
- const { entries, ...file } = await loadEntries(deps);
113
- const self = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL };
114
- const shellDir = opts.shellDir ?? kitShellDir();
115
- const kitOwn = opts.shellDir === undefined ? KIT_VERSION : undefined;
116
- const shell = shellDir ? { shell: await shellOf(deps, shellDir, kitOwn) } : {};
117
- const info = { ...launchMarks(launch), ...self, ...file, ...shell };
118
- const hostToken = newHostToken();
119
- const events = shellEvents();
120
- const app = daemonApp(deps, entries, () => port, info, hostToken, events);
121
- const server = await listen(app, port, '127.0.0.1');
122
- port = server.address().port;
123
- const stop = stopper(server, entries, deps, life);
124
- try {
125
- await announce(opts, port, hostToken);
126
- await deps.queue(() => syncCliUser(deps, entries, events));
127
- await deps.queue(() => boot(deps, entries));
128
- life.signal.addEventListener('abort', watchCliUser(deps, entries, events));
129
- }
130
- catch (err) {
131
- await stop();
132
- throw err;
133
- }
134
- return { port, stop };
135
- };
136
- // One daemon on 127.0.0.1, one child process for each extension (D1); a bad clockRate rejects.
137
- export const createDaemon = async (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs, opts.clockRate));
@@ -1,21 +0,0 @@
1
- import { type InstallEntry } from './installation.js';
2
- import { type Entry, type SupervisorDeps } from './supervisor.js';
3
- export type Entries = Map<string, Entry>;
4
- export declare const summary: ({ id, version, state, error, lane }: Entry) => {
5
- error?: string | undefined;
6
- pid?: number | undefined;
7
- id: string;
8
- version: string;
9
- state: import("./supervisor.js").State;
10
- };
11
- export declare const listed: (entry: Entry) => {
12
- source: string;
13
- enabled: boolean;
14
- error?: string | undefined;
15
- pid?: number | undefined;
16
- id: string;
17
- version: string;
18
- state: import("./supervisor.js").State;
19
- };
20
- export declare const entryOf: (entries: Entries, id: string) => Entry;
21
- export declare const persist: (deps: SupervisorDeps, id: string, install?: InstallEntry) => Promise<import("./installation.js").Installation>;
@@ -1,24 +0,0 @@
1
- import { fail } from '../../envelope/envelope.js';
2
- import { persistInstallation, withEntry } from './installation.js';
3
- import {} from './supervisor.js';
4
- // pid of a running child: the e2e teardown reads it.
5
- export const summary = ({ id, version, state, error, lane }) => ({
6
- id,
7
- version,
8
- state,
9
- ...(lane && { pid: lane.child.pid }),
10
- ...(error && { error }),
11
- });
12
- export const listed = (entry) => ({
13
- ...summary(entry),
14
- source: entry.install.source ?? 'market',
15
- enabled: entry.install.enabled !== false,
16
- });
17
- export const entryOf = (entries, id) => {
18
- const entry = entries.get(id);
19
- if (!entry)
20
- throw fail('NOT_FOUND', `${id} is not installed`);
21
- return entry;
22
- };
23
- // The entry of id in installation.json replaced, added, or (no install) removed.
24
- export const persist = (deps, id, install) => persistInstallation(deps.configDir, (doc) => withEntry(doc, id, install), deps.lockMs);
@@ -1,3 +0,0 @@
1
- import { type Entry } from './supervisor.js';
2
- export declare const hold: (entry: Entry) => (() => void);
3
- export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
@@ -1,19 +0,0 @@
1
- import { retire } from './lane.js';
2
- import { cancelRestart } from './restart.js';
3
- import {} from './supervisor.js';
4
- // New requests of the extension wait here (the proxy gives up after gateMs) until release.
5
- export const hold = (entry) => {
6
- let release = () => undefined;
7
- entry.gate = new Promise((resolve) => (release = resolve));
8
- return () => {
9
- entry.gate = undefined;
10
- release();
11
- };
12
- };
13
- // Detached first, so its exit is not a failure; then drained and stopped.
14
- export const halt = async (entry, drainMs) => {
15
- cancelRestart(entry);
16
- const lane = entry.lane;
17
- entry.lane = undefined;
18
- await retire(lane, drainMs);
19
- };
@@ -1,18 +0,0 @@
1
- import { type Express } from 'express';
2
- import { type Entries } from './entries.js';
3
- import { type Seal } from './seal.js';
4
- import { type Shell } from './shell-routes.js';
5
- import { type SupervisorDeps } from './supervisor.js';
6
- export interface DaemonInfo {
7
- version: string;
8
- pid: number;
9
- protocol: number;
10
- invalid: boolean;
11
- unreadable?: string;
12
- notJson?: boolean;
13
- clockRate?: number;
14
- seal?: Seal;
15
- sealError?: string;
16
- shell?: Shell;
17
- }
18
- export declare const healthRoutes: (app: Express, deps: SupervisorDeps, entries: Entries, info: DaemonInfo) => void;
@@ -1,75 +0,0 @@
1
- import {} from 'express';
2
- import { hostParts } from '../../manifest/parts.js';
3
- import { readManifest } from '../../manifest/read-manifest.js';
4
- import { appRowOf } from './app-files.js';
5
- import { summary } from './entries.js';
6
- import { restartsOf } from './restart.js';
7
- import { sealOfEntry } from './seal.js';
8
- import {} from './shell-routes.js';
9
- import {} from './supervisor.js';
10
- // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
11
- const DAEMON_SERVICE = 'agentage-daemon';
12
- // Read at each call: a reload can change the package in its folder.
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
- };
25
- const installationOf = ({ invalid, unreadable, notJson }) => {
26
- if (unreadable)
27
- return { installation: 'unreadable', installationError: unreadable };
28
- return invalid || notJson ? { installation: 'invalid' } : {};
29
- };
30
- const sealMark = ({ seal, sealError }) => (seal === 'off' ? { seal, sealError } : {});
31
- const statusOf = (deps, entries, info) => {
32
- const settled = [...entries.values()].every((e) => ['running', 'disabled'].includes(e.state));
33
- const clean = !info.invalid && !info.unreadable && !info.notJson && info.seal !== 'off';
34
- return settled && !deps.unsynced.size && clean ? 'ok' : 'degraded';
35
- };
36
- const healthOf = async (deps, entries, info) => {
37
- const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
38
- const extensions = await Promise.all([...entries.values()].map((e) => reported(e, info)));
39
- const changing = deps.pending.list();
40
- const marks = {
41
- ...(changing.length && { pending: changing }),
42
- ...(info.clockRate && { clockRate: info.clockRate }),
43
- ...(deps.unsynced.size && { unsynced: [...deps.unsynced] }),
44
- ...installationOf(info),
45
- ...sealMark(info),
46
- };
47
- const status = statusOf(deps, entries, info);
48
- return { status, version: info.version, ...self, extensions, ...marks };
49
- };
50
- const rowOf = async (e) => {
51
- const app = await appRowOf(e);
52
- return {
53
- id: e.id,
54
- version: e.version,
55
- state: e.state,
56
- parts: await partsOf(e),
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 };
66
- };
67
- const HOST_DISCOVERY_PATH = '/.well-known/agentage-host.json';
68
- export const healthRoutes = (app, deps, entries, info) => {
69
- app.get('/health', async (_req, res) => {
70
- res.set('Cache-Control', 'no-store').json(await healthOf(deps, entries, info));
71
- });
72
- app.get(HOST_DISCOVERY_PATH, async (_req, res) => {
73
- res.set('Cache-Control', 'no-store').json(await discoveryOf(entries, info));
74
- });
75
- };
@@ -1,6 +0,0 @@
1
- import { type IncomingHttpHeaders } from 'node:http';
2
- import { type RequestHandler } from 'express';
3
- export declare const newHostToken: () => string;
4
- export declare const carriesHostToken: (headers: IncomingHttpHeaders, token: string) => boolean;
5
- export declare const NO_TOKEN = "host token required: this cli is older than the daemon, update @agentage/cli or run \"agentage daemon restart\"";
6
- export declare const requireHostToken: (token: string) => RequestHandler;
@@ -1,28 +0,0 @@
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
- };
@@ -1,35 +0,0 @@
1
- import { z } from 'zod';
2
- declare const InstallEntrySchema: z.ZodObject<{
3
- id: z.ZodString;
4
- version: z.ZodOptional<z.ZodString>;
5
- source: z.ZodOptional<z.ZodString>;
6
- enabled: z.ZodOptional<z.ZodBoolean>;
7
- }, z.core.$loose>;
8
- export type InstallEntry = z.infer<typeof InstallEntrySchema>;
9
- export interface Installation {
10
- host: string;
11
- extensions: InstallEntry[];
12
- [key: string]: unknown;
13
- }
14
- interface CheckedInstallation {
15
- doc: Installation;
16
- invalid: boolean;
17
- }
18
- export declare const bootInstallation: (configDir: string) => Promise<{
19
- doc: Installation;
20
- invalid: boolean;
21
- unreadable: string;
22
- } | (CheckedInstallation & {
23
- unreadable?: string;
24
- })>;
25
- export declare const assertReadable: (configDir: string, why?: string) => Promise<void>;
26
- type Change = (doc: Installation) => Installation;
27
- /**
28
- * Read, change and write installation.json under the kit's lock, the path the daemon uses.
29
- * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
30
- * a live daemon named by daemon.json is refused, unless this is that daemon's process.
31
- */
32
- export declare const updateInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
33
- export declare const persistInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
34
- export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
35
- export {};
@@ -1,90 +0,0 @@
1
- import { copyFile } from 'node:fs/promises';
2
- import { isAbsolute, join } from 'node:path';
3
- import { z } from 'zod';
4
- import { fail } from '../../envelope/envelope.js';
5
- import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
6
- import { assertNoOtherDaemon } from './daemon-owner.js';
7
- import { readJsonFile, unreadableReason, withFileLock, writeJsonFile } from './json-file.js';
8
- // One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
9
- const InstallEntrySchema = z.looseObject({
10
- id: ExtensionIdSchema,
11
- version: z.string().min(1).optional(),
12
- source: z.string().refine(isAbsolute).optional(),
13
- enabled: z.boolean().optional(),
14
- });
15
- const InstallationSchema = z.looseObject({
16
- host: z.string().default('local'),
17
- extensions: z.array(z.unknown()),
18
- });
19
- const INSTALLATION_FILE = 'installation.json';
20
- const EMPTY = { host: 'local', extensions: [] };
21
- const checked = (raw) => {
22
- const top = InstallationSchema.safeParse(raw);
23
- if (!top.success)
24
- return { doc: EMPTY, invalid: true };
25
- const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
26
- const valid = rows.flatMap((row) => (row.success ? [row.data] : []));
27
- const extensions = valid.filter((row, at) => valid.findIndex((e) => e.id === row.id) === at);
28
- return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
29
- };
30
- // At boot the daemon has no rows from it, so a fix needs a restart; later a fix is enough.
31
- const unreadable = (why, atBoot = false) => fail('CONFLICT', `${INSTALLATION_FILE} cannot be read (${why}): fix it${atBoot ? ', then restart the daemon' : ''}; no change is written`, { code: 'INSTALLATION_UNREADABLE', details: { reason: why } });
32
- const reasonOf = unreadableReason;
33
- // Not readable (EACCES, EISDIR): thrown.
34
- const rawOf = (configDir, notJson = 'empty') => readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch((err) => {
35
- if (err instanceof SyntaxError && notJson === 'empty')
36
- return null;
37
- throw err;
38
- });
39
- const readInstallation = async (configDir, notJson) => checked(await rawOf(configDir, notJson).catch((err) => {
40
- throw unreadable(reasonOf(err));
41
- }));
42
- // At boot an unreadable file gives no rows and its reason; the daemon then refuses every change.
43
- export const bootInstallation = (configDir) => rawOf(configDir).then((raw) => checked(raw), (err) => ({ doc: EMPTY, invalid: false, unreadable: reasonOf(err) }));
44
- // A change is refused when the file was unreadable at boot (why) or is unreadable now.
45
- export const assertReadable = async (configDir, why) => {
46
- if (why)
47
- throw unreadable(why, true);
48
- await readInstallation(configDir, 'refuse');
49
- };
50
- // A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
51
- const keepBadCopy = (configDir) => copyFile(join(configDir, INSTALLATION_FILE), join(configDir, `${INSTALLATION_FILE}.bad`));
52
- // Only rows C3 accepts are written, and each id once.
53
- const checkedDoc = (next) => {
54
- const ids = next.extensions.map((row) => row.id);
55
- const bad = next.extensions.find((row) => !InstallEntrySchema.safeParse(row).success);
56
- if (bad || new Set(ids).size < ids.length || !InstallationSchema.safeParse(next).success)
57
- throw fail('VALIDATION_ERROR', `${INSTALLATION_FILE}: a row C3 refuses, or an id twice`);
58
- return next;
59
- };
60
- const changeInstallation = (notJson) => async (configDir, change, waitMs) => {
61
- await assertNoOtherDaemon(configDir);
62
- const file = join(configDir, INSTALLATION_FILE);
63
- const write = async () => {
64
- const read = await readInstallation(configDir, notJson);
65
- if (read.invalid)
66
- await keepBadCopy(configDir);
67
- const next = checkedDoc(change(read.doc));
68
- await writeJsonFile(file, next);
69
- return next;
70
- };
71
- return withFileLock(file, write, waitMs);
72
- };
73
- /**
74
- * Read, change and write installation.json under the kit's lock, the path the daemon uses.
75
- * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
76
- * a live daemon named by daemon.json is refused, unless this is that daemon's process.
77
- */
78
- export const updateInstallation = changeInstallation('empty');
79
- // The daemon after its boot: its rows are in the file, so a file that is not JSON is never replaced.
80
- export const persistInstallation = changeInstallation('refuse');
81
- // The entry of id replaced (or added), the order kept; undefined removes it.
82
- export const withEntry = (doc, id, entry) => {
83
- const at = doc.extensions.findIndex((e) => e.id === id);
84
- const rest = doc.extensions.filter((e) => e.id !== id);
85
- if (!entry)
86
- return { ...doc, extensions: rest };
87
- if (at < 0)
88
- return { ...doc, extensions: [...rest, entry] };
89
- return { ...doc, extensions: doc.extensions.map((e) => (e.id === id ? entry : e)) };
90
- };
@@ -1,21 +0,0 @@
1
- import { type InstallSpec, type SupervisorDeps } from './supervisor.js';
2
- export declare const NO_INSTALLER = "this daemon has no installer: install a folder with { source }";
3
- declare const BASE: {
4
- readonly 400: "VALIDATION_ERROR";
5
- readonly 404: "NOT_FOUND";
6
- readonly 409: "CONFLICT";
7
- readonly 501: "UNAVAILABLE";
8
- readonly 502: "UNAVAILABLE";
9
- readonly 504: "UNAVAILABLE";
10
- };
11
- export declare const answer: (status: keyof typeof BASE, message: string, code?: string, details?: Record<string, unknown>) => import("../../envelope/envelope.js").Failure & {
12
- code: string;
13
- status: 400 | 404 | 409 | 501 | 502 | 504;
14
- retryAfter: undefined;
15
- };
16
- export declare const runInstaller: (deps: SupervisorDeps, spec: Omit<InstallSpec, "signal">) => Promise<{
17
- id: string;
18
- version: string;
19
- dir: string;
20
- }>;
21
- export {};
@@ -1,48 +0,0 @@
1
- import { setTimeout as sleep } from 'node:timers/promises';
2
- import { fail } from '../../envelope/envelope.js';
3
- import {} from './supervisor.js';
4
- export const NO_INSTALLER = 'this daemon has no installer: install a folder with { source }';
5
- const BASE = {
6
- 400: 'VALIDATION_ERROR',
7
- 404: 'NOT_FOUND',
8
- 409: 'CONFLICT',
9
- 501: 'UNAVAILABLE',
10
- 502: 'UNAVAILABLE',
11
- 504: 'UNAVAILABLE',
12
- };
13
- // The envelope with a status or a code the closed set has not (501, 504, the installer's own code).
14
- export const answer = (status, message, code = BASE[status], details) => Object.assign(fail(BASE[status], message, { details }), { code, status, retryAfter: undefined });
15
- // An installer error with a string code is the client's envelope; any other stays a 500.
16
- const answerOf = (err) => {
17
- const { code, status, message } = (err ?? {});
18
- if (typeof code !== 'string' || !code)
19
- return err;
20
- const at = status === 404 || status === 502 ? status : 400;
21
- return answer(at, typeof message === 'string' && message ? message : code, code);
22
- };
23
- // A second call while a timed-out one of that id still runs would overlap it.
24
- const notTwice = (deps, id) => {
25
- const row = deps.pending.timedOut(id);
26
- if (row)
27
- throw answer(409, `the installer of ${id} still runs`, 'CONFLICT', { ...row });
28
- };
29
- // At most installMs, then 504 TIMEOUT; only then the signal asks the installer to stop.
30
- export const runInstaller = async (deps, spec) => {
31
- if (!deps.install)
32
- throw answer(501, NO_INSTALLER);
33
- notTwice(deps, spec.id);
34
- const since = new Date().toISOString();
35
- const stop = new AbortController();
36
- const timer = new AbortController();
37
- const call = deps.install({ ...spec, signal: stop.signal });
38
- const late = sleep(deps.installMs, undefined, { ref: false, signal: timer.signal }).then(() => {
39
- stop.abort();
40
- deps.pending.linger(spec.id, since, call);
41
- throw answer(504, `the installer did not answer in ${deps.installMs} ms`, 'TIMEOUT');
42
- });
43
- late.catch(() => undefined);
44
- const answered = call.catch((err) => {
45
- throw answerOf(err);
46
- });
47
- return Promise.race([answered, late]).finally(() => timer.abort());
48
- };
@@ -1,6 +0,0 @@
1
- export declare const readJsonFile: <T>(file: string, fallback: T) => Promise<T>;
2
- export declare const unreadableReason: (err: unknown) => string;
3
- export declare const unwritable: (file: string, err: unknown) => unknown;
4
- export declare const writeJsonFile: (file: string, value: unknown, given?: number) => Promise<void>;
5
- export declare const LOCK_WAIT_MS = 5000;
6
- export declare const withFileLock: <T>(file: string, fn: () => T | Promise<T>, waitMs?: number) => Promise<T>;
@@ -1,90 +0,0 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { chmod, open, readFile, rename, stat, unlink } from 'node:fs/promises';
3
- import { setTimeout as sleep } from 'node:timers/promises';
4
- import { constants } from 'node:os';
5
- import { basename, dirname } from 'node:path';
6
- import { fail } from '../../envelope/envelope.js';
7
- import { DATA_DIR_LOCKED, lockDataDir } from '../data-lock.js';
8
- export const readJsonFile = async (file, fallback) => {
9
- try {
10
- return JSON.parse(await readFile(file, 'utf8'));
11
- }
12
- catch (err) {
13
- if (err.code === 'ENOENT')
14
- return fallback;
15
- throw err;
16
- }
17
- };
18
- // Fixed words only: a parser message quotes the file, and secrets.json holds secrets.
19
- export const unreadableReason = (err) => err instanceof SyntaxError
20
- ? 'not JSON'
21
- : String(err.code ?? err.message);
22
- // The folder is full or not writable: the errno, the file and where to look, never a bare 500.
23
- const NOT_WRITABLE = ['ENOSPC', 'EDQUOT', 'EROFS', 'EACCES', 'EPERM'];
24
- // Node has no code name for EDQUOT on Linux ("Unknown system error -122"): read the errno too.
25
- const errnoName = (err) => {
26
- const { errno, code } = err;
27
- return errno === -constants.errno.EDQUOT ? 'EDQUOT' : (code ?? '');
28
- };
29
- export const unwritable = (file, err) => {
30
- const code = errnoName(err);
31
- if (!NOT_WRITABLE.includes(code))
32
- return err;
33
- const message = `${basename(file)} cannot be written (${code}): check the free space and rights of ${dirname(file)}; no change was made`;
34
- return fail('UNAVAILABLE', message, { retryAfter: 30 });
35
- };
36
- // The mode of a file already there, narrowed by the default: a 0600 file is never widened.
37
- const modeOf = (file, mode) => stat(file).then((st) => st.mode & mode & 0o777, () => mode);
38
- // A reader sees the old file or the new one, never half of one, also after a power loss.
39
- export const writeJsonFile = async (file, value, given = 0o644) => {
40
- const mode = await modeOf(file, given);
41
- const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
42
- try {
43
- const handle = await open(tmp, 'w', mode);
44
- try {
45
- await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`);
46
- await handle.sync();
47
- }
48
- finally {
49
- await handle.close();
50
- }
51
- await chmod(tmp, mode);
52
- await rename(tmp, file);
53
- }
54
- catch (err) {
55
- // A full disk leaves no half tmp file beside the real one.
56
- await unlink(tmp).catch(() => undefined);
57
- throw unwritable(file, err);
58
- }
59
- };
60
- export const LOCK_WAIT_MS = 5_000;
61
- // A live holder (or a reused pid of a dead one) named, so a person can check that process.
62
- const lockedBy = (file, err, waitMs) => fail('UNAVAILABLE', `${basename(file)} is locked by process ${err.pid ?? 0}: waited ${waitMs} ms`, { retryAfter: 1 });
63
- // The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one waited for waitMs.
64
- const acquire = async (file, waitMs) => {
65
- const until = Date.now() + waitMs;
66
- for (;;) {
67
- try {
68
- return await lockDataDir(file);
69
- }
70
- catch (err) {
71
- if (err.code !== DATA_DIR_LOCKED)
72
- throw err;
73
- if (Date.now() >= until)
74
- throw lockedBy(file, err, waitMs);
75
- await sleep(25);
76
- }
77
- }
78
- };
79
- // One writer at a time across processes: an exclusive lock file (<file>.lock) beside the file.
80
- export const withFileLock = async (file, fn, waitMs = LOCK_WAIT_MS) => {
81
- const release = await acquire(file, waitMs).catch((err) => {
82
- throw unwritable(file, err);
83
- });
84
- try {
85
- return await fn();
86
- }
87
- finally {
88
- await release();
89
- }
90
- };
@@ -1,9 +0,0 @@
1
- import { type Child } from './child.js';
2
- export interface Lane {
3
- child: Child;
4
- open: number;
5
- idle: (() => void)[];
6
- }
7
- export declare const laneOf: (child: Child) => Lane;
8
- export declare const enter: (lane: Lane) => (() => void);
9
- export declare const retire: (lane: Lane | undefined, drainMs: number) => Promise<void>;