@agentage/extension 0.20.1 → 0.20.3

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 (120) 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 +2 -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/tool/check.js +3 -0
  22. package/dist/tool/recipe.js +2 -2
  23. package/dist/tool/up/gateway.js +0 -3
  24. package/package.json +5 -1
  25. package/dist/host/daemon/add.d.ts +0 -11
  26. package/dist/host/daemon/add.js +0 -93
  27. package/dist/host/daemon/app-files.d.ts +0 -8
  28. package/dist/host/daemon/app-files.js +0 -34
  29. package/dist/host/daemon/app-header.d.ts +0 -2
  30. package/dist/host/daemon/app-header.js +0 -12
  31. package/dist/host/daemon/app-reload.d.ts +0 -10
  32. package/dist/host/daemon/app-reload.js +0 -18
  33. package/dist/host/daemon/child-files.d.ts +0 -20
  34. package/dist/host/daemon/child-files.js +0 -53
  35. package/dist/host/daemon/child.d.ts +0 -30
  36. package/dist/host/daemon/child.js +0 -126
  37. package/dist/host/daemon/cli-user-watch.d.ts +0 -9
  38. package/dist/host/daemon/cli-user-watch.js +0 -47
  39. package/dist/host/daemon/cli-user.d.ts +0 -2
  40. package/dist/host/daemon/cli-user.js +0 -42
  41. package/dist/host/daemon/daemon-files.d.ts +0 -20
  42. package/dist/host/daemon/daemon-files.js +0 -46
  43. package/dist/host/daemon/daemon-owner.d.ts +0 -1
  44. package/dist/host/daemon/daemon-owner.js +0 -32
  45. package/dist/host/daemon/daemon.d.ts +0 -19
  46. package/dist/host/daemon/daemon.js +0 -137
  47. package/dist/host/daemon/entries.d.ts +0 -21
  48. package/dist/host/daemon/entries.js +0 -24
  49. package/dist/host/daemon/gate.d.ts +0 -3
  50. package/dist/host/daemon/gate.js +0 -19
  51. package/dist/host/daemon/health-routes.d.ts +0 -18
  52. package/dist/host/daemon/health-routes.js +0 -75
  53. package/dist/host/daemon/host-token.d.ts +0 -6
  54. package/dist/host/daemon/host-token.js +0 -28
  55. package/dist/host/daemon/installation.d.ts +0 -35
  56. package/dist/host/daemon/installation.js +0 -90
  57. package/dist/host/daemon/installer-call.d.ts +0 -21
  58. package/dist/host/daemon/installer-call.js +0 -48
  59. package/dist/host/daemon/json-file.d.ts +0 -6
  60. package/dist/host/daemon/json-file.js +0 -90
  61. package/dist/host/daemon/lane.d.ts +0 -9
  62. package/dist/host/daemon/lane.js +0 -24
  63. package/dist/host/daemon/last-words.d.ts +0 -2
  64. package/dist/host/daemon/last-words.js +0 -28
  65. package/dist/host/daemon/limits.d.ts +0 -16
  66. package/dist/host/daemon/limits.js +0 -31
  67. package/dist/host/daemon/ops.d.ts +0 -12
  68. package/dist/host/daemon/ops.js +0 -94
  69. package/dist/host/daemon/patch-values.d.ts +0 -6
  70. package/dist/host/daemon/patch-values.js +0 -39
  71. package/dist/host/daemon/pending.d.ts +0 -15
  72. package/dist/host/daemon/pending.js +0 -18
  73. package/dist/host/daemon/proxy.d.ts +0 -11
  74. package/dist/host/daemon/proxy.js +0 -106
  75. package/dist/host/daemon/queue.d.ts +0 -3
  76. package/dist/host/daemon/queue.js +0 -27
  77. package/dist/host/daemon/redact-stream.d.ts +0 -4
  78. package/dist/host/daemon/redact-stream.js +0 -24
  79. package/dist/host/daemon/reload-marker.d.ts +0 -8
  80. package/dist/host/daemon/reload-marker.js +0 -57
  81. package/dist/host/daemon/reload.d.ts +0 -10
  82. package/dist/host/daemon/reload.js +0 -72
  83. package/dist/host/daemon/restart.d.ts +0 -14
  84. package/dist/host/daemon/restart.js +0 -59
  85. package/dist/host/daemon/routes.d.ts +0 -6
  86. package/dist/host/daemon/routes.js +0 -101
  87. package/dist/host/daemon/run-lock.d.ts +0 -1
  88. package/dist/host/daemon/run-lock.js +0 -15
  89. package/dist/host/daemon/seal-reach.d.ts +0 -2
  90. package/dist/host/daemon/seal-reach.js +0 -38
  91. package/dist/host/daemon/seal.d.ts +0 -20
  92. package/dist/host/daemon/seal.js +0 -93
  93. package/dist/host/daemon/shell-events.d.ts +0 -9
  94. package/dist/host/daemon/shell-events.js +0 -36
  95. package/dist/host/daemon/shell-routes.d.ts +0 -29
  96. package/dist/host/daemon/shell-routes.js +0 -68
  97. package/dist/host/daemon/sign-in-page.d.ts +0 -3
  98. package/dist/host/daemon/sign-in-page.js +0 -30
  99. package/dist/host/daemon/start-checks.d.ts +0 -6
  100. package/dist/host/daemon/start-checks.js +0 -29
  101. package/dist/host/daemon/stopping.d.ts +0 -10
  102. package/dist/host/daemon/stopping.js +0 -28
  103. package/dist/host/daemon/supervisor.d.ts +0 -59
  104. package/dist/host/daemon/supervisor.js +0 -107
  105. package/dist/host/daemon/write-all.d.ts +0 -8
  106. package/dist/host/daemon/write-all.js +0 -45
  107. package/dist/shell/dist/index.html +0 -49
  108. package/dist/shell/dist/shell.css +0 -2
  109. package/dist/shell/dist/shell.js +0 -69
  110. package/dist/shell/dist/vendor/app.js +0 -1
  111. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +0 -14
  112. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +0 -14
  113. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +0 -14
  114. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +0 -1
  115. package/dist/shell/dist/vendor/jsx-runtime.js +0 -1
  116. package/dist/shell/dist/vendor/react-dom-client.js +0 -33
  117. package/dist/shell/dist/vendor/react-dom.js +0 -1
  118. package/dist/shell/dist/vendor/react.js +0 -1
  119. package/dist/shell/package.json +0 -5
  120. /package/dist/host/{daemon/guard.d.ts → guard.d.ts} +0 -0
@@ -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>;
@@ -1,24 +0,0 @@
1
- import { setTimeout as sleep } from 'node:timers/promises';
2
- import {} from './child.js';
3
- export const laneOf = (child) => ({ child, open: 0, idle: [] });
4
- // Counts one request until leave() is called (once).
5
- export const enter = (lane) => {
6
- lane.open += 1;
7
- let left = false;
8
- return () => {
9
- if (left)
10
- return;
11
- left = true;
12
- lane.open -= 1;
13
- if (lane.open === 0)
14
- lane.idle.splice(0).forEach((resolve) => resolve());
15
- };
16
- };
17
- const drained = (lane) => lane.open === 0 ? Promise.resolve() : new Promise((resolve) => lane.idle.push(resolve));
18
- // Waits for the open requests (at most drainMs, so a hung one blocks nothing), then stops the child.
19
- export const retire = async (lane, drainMs) => {
20
- if (!lane)
21
- return;
22
- await Promise.race([drained(lane), sleep(drainMs, undefined, { ref: false })]);
23
- await lane.child.stop();
24
- };
@@ -1,2 +0,0 @@
1
- import { type Exit } from './child.js';
2
- export declare const lastWords: (tail: string, how: Exit) => string;
@@ -1,28 +0,0 @@
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
- };
@@ -1,16 +0,0 @@
1
- export declare const LIMITS: {
2
- drainMs: number;
3
- startMs: number;
4
- healthMs: number;
5
- lockMs: number;
6
- gateMs: number;
7
- answerMs: number;
8
- installMs: number;
9
- backoffMs: number[];
10
- crashLimit: number;
11
- crashWindowMs: number;
12
- healthyResetMs: number;
13
- userPollMs: number;
14
- };
15
- export type Limits = typeof LIMITS;
16
- export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -1,31 +0,0 @@
1
- // Every wait of the daemon has a bound; each is a createDaemon option (docs/part-image.md).
2
- export const LIMITS = {
3
- // An old child's open requests before it is stopped.
4
- drainMs: 10_000,
5
- // A forked child's port report; then SIGKILL.
6
- startMs: 60_000,
7
- // A new child's own /health, once it reported its port.
8
- healthMs: 60_000,
9
- // A write waits for another process that holds the lock of a daemon file.
10
- lockMs: 5_000,
11
- // A request held while its extension swaps children.
12
- gateMs: 30_000,
13
- // A child's answer headers; then 504.
14
- answerMs: 60_000,
15
- // One Installer call (POST, PATCH, each entry at boot), and a change queued behind others:
16
- // above the cli's npm bound (10 min), below its client wait (12 min).
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,
25
- // How often auth.json is read: a sign-in or sign-out restarts the running children.
26
- userPollMs: 2_000,
27
- };
28
- export const limitsOf = (given) => {
29
- const keys = Object.keys(LIMITS);
30
- return Object.fromEntries(keys.map((key) => [key, given[key] ?? LIMITS[key]]));
31
- };
@@ -1,12 +0,0 @@
1
- import { type Entries } from './entries.js';
2
- import { type SupervisorDeps } from './supervisor.js';
3
- export declare const changeExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
4
- error?: string | undefined;
5
- pid?: number | undefined;
6
- id: string;
7
- version: string;
8
- state: import("./supervisor.js").State;
9
- }>;
10
- export declare const removeExtension: (deps: SupervisorDeps, entries: Entries, id: string, purge: boolean) => Promise<{
11
- id: string;
12
- }>;
@@ -1,94 +0,0 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { z } from 'zod';
3
- import { fail } from '../../envelope/envelope.js';
4
- import { parse } from '../../envelope/parse.js';
5
- import { SecretNameSchema } from '../../manifest/primitives.schema.js';
6
- import { VersionSpecSchema } from './add.js';
7
- import { clearRunDir, purgeData } from './daemon-files.js';
8
- import { unmarkReload } from './reload-marker.js';
9
- import { entryOf, summary } from './entries.js';
10
- import { unsynced, writeAll } from './write-all.js';
11
- import { runInstaller } from './installer-call.js';
12
- import { checkedSettings } from './patch-values.js';
13
- import {} from './installation.js';
14
- import { halt, hold } from './gate.js';
15
- import { swap, valuesOf, } from './supervisor.js';
16
- const PatchSchema = z.strictObject({
17
- version: VersionSpecSchema.optional(),
18
- enabled: z.boolean().optional(),
19
- settings: z.record(z.string(), z.unknown()).optional(),
20
- secrets: z.record(SecretNameSchema, z.string()).optional(),
21
- });
22
- // The install entry a patch asks for; a new version is installed first and its folder kept aside.
23
- const nextInstall = async (deps, entry, patch) => {
24
- // enabled absent means true (C3), so only false is written.
25
- const install = { ...entry.install };
26
- delete install.enabled;
27
- if ((patch.enabled ?? entry.install.enabled) === false)
28
- install.enabled = false;
29
- if (!patch.version || patch.version === entry.install.version)
30
- return { install };
31
- if (install.source)
32
- throw fail('VALIDATION_ERROR', `${entry.id} runs a folder: it has no version`);
33
- const got = await runInstaller(deps, { id: entry.id, version: patch.version });
34
- return { install: { ...install, version: got.version }, dir: got.dir };
35
- };
36
- // The change, and the values on disk now: what a failed write puts back.
37
- const nextOf = async (deps, entry, patch) => {
38
- const next = await nextInstall(deps, entry, patch);
39
- const dir = next.dir ?? entry.dir ?? entry.install.source;
40
- const given = await checkedSettings(dir, patch, entry.id);
41
- const was = await valuesOf(deps.configDir, entry.id);
42
- const settings = { ...was.settings, ...given };
43
- const values = { settings, secrets: { ...was.secrets, ...patch.secrets } };
44
- return { to: { ...next, values }, was };
45
- };
46
- // Disabled: written, then stopped. Else written, then swapped; a refused start puts the files back.
47
- const apply = async (deps, entry, to, was) => {
48
- const back = { install: entry.install, values: was };
49
- await writeAll(deps, entry.id, to, back);
50
- const undo = () => writeAll(deps, entry.id, back, to).catch(() => unsynced(deps, entry.id));
51
- if (to.install.enabled !== false)
52
- await swap(deps, entry, to, undo);
53
- else
54
- await halt(entry, deps.drainMs);
55
- Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
56
- if (to.install.enabled === false)
57
- entry.state = 'disabled';
58
- };
59
- // A request sent once the change is decided waits (gateMs) and goes to the result.
60
- const held = async (deps, entry, to, was) => {
61
- const release = hold(entry);
62
- try {
63
- await apply(deps, entry, to, was);
64
- }
65
- finally {
66
- release();
67
- }
68
- };
69
- // Nothing to do: the same files, and the entry already runs (or is stopped) as they say.
70
- const unchanged = (entry, to, was) => entry.state === (to.install.enabled === false ? 'disabled' : 'running') &&
71
- (!to.dir || to.dir === entry.dir) &&
72
- isDeepStrictEqual(to.install, entry.install) &&
73
- isDeepStrictEqual(to.values, was);
74
- // PATCH: a refused change keeps the old one and is 400 START_FAILED; a failed entry is started again.
75
- export const changeExtension = async (deps, entries, id, body) => {
76
- const patch = parse(PatchSchema, body, 'Invalid body');
77
- const entry = entryOf(entries, id);
78
- const { to, was } = await nextOf(deps, entry, patch);
79
- if (!unchanged(entry, to, was))
80
- await held(deps, entry, to, was);
81
- return summary(entry);
82
- };
83
- // DELETE: the files first (all or none), then the child stops; purge also deletes its data folder.
84
- export const removeExtension = async (deps, entries, id, purge) => {
85
- const entry = entryOf(entries, id);
86
- await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
87
- entries.delete(id);
88
- await halt(entry, deps.drainMs);
89
- await unmarkReload(deps.configDir, id);
90
- await clearRunDir(deps.configDir, id);
91
- if (purge)
92
- await purgeData(deps.configDir, id);
93
- return { id };
94
- };
@@ -1,6 +0,0 @@
1
- interface GivenValues {
2
- settings?: Record<string, unknown>;
3
- secrets?: Record<string, string>;
4
- }
5
- export declare const checkedSettings: (dir: string | undefined, given: GivenValues, id: string) => Promise<Record<string, unknown>>;
6
- export {};
@@ -1,39 +0,0 @@
1
- import { fits } from '../../context/settings.js';
2
- import { fail } from '../../envelope/envelope.js';
3
- import {} from '../../manifest/manifest.schema.js';
4
- import { readManifest } from '../../manifest/read-manifest.js';
5
- const PARSE = {
6
- number: (t) => (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t) ? Number(t) : t),
7
- integer: (t) => (/^-?\d+$/.test(t) ? Number(t) : t),
8
- boolean: (t) => (t === 'true' ? true : t === 'false' ? false : t),
9
- };
10
- const refused = (key, message) => fail('VALIDATION_ERROR', `setting ${key}: ${message}`, { code: 'INVALID_SETTING' });
11
- const valueOf = (key, setting, given) => {
12
- if (!setting)
13
- throw refused(key, 'not declared in the manifest');
14
- const value = typeof given === 'string' ? (PARSE[setting.type]?.(given) ?? given) : given;
15
- if (!fits(setting, value))
16
- throw refused(key, `${JSON.stringify(given)} is not a valid ${setting.type}`);
17
- return value;
18
- };
19
- // Only a secret the package declares: the name becomes a file name in the child's folder.
20
- const checkSecrets = (pkg, names, id) => {
21
- const known = (pkg.agentage.secrets ?? []).map((s) => (typeof s === 'string' ? s : s.name));
22
- const unknown = names.filter((name) => !known.includes(name));
23
- if (unknown.length)
24
- throw fail('VALIDATION_ERROR', `${id} declares no secret ${unknown.join(', ')}`);
25
- };
26
- // The secret names checked, and each setting a client sent as text (`limit=5`) in its declared type.
27
- export const checkedSettings = async (dir, given, id) => {
28
- const settings = given.settings ?? {};
29
- const names = Object.keys(given.secrets ?? {});
30
- if (!names.length && !Object.keys(settings).length)
31
- return settings;
32
- if (!dir)
33
- throw fail('VALIDATION_ERROR', `${id} has no package yet: install it first`);
34
- const pkg = await readManifest(dir);
35
- checkSecrets(pkg, names, id);
36
- const declared = pkg.agentage.settings ?? {};
37
- const typed = Object.entries(settings).map(([key, v]) => [key, valueOf(key, declared[key], v)]);
38
- return Object.fromEntries(typed);
39
- };
@@ -1,15 +0,0 @@
1
- export type PendingOp = 'install' | 'update' | 'remove' | 'reload';
2
- export interface Pending {
3
- op: PendingOp;
4
- id?: string;
5
- source?: string;
6
- since: string;
7
- timedOut?: true;
8
- }
9
- export declare const pendingChanges: () => {
10
- track: <T>(change: Omit<Pending, "since">, fn: () => Promise<T>) => Promise<T>;
11
- linger: (id: string, since: string, work: Promise<unknown>) => void;
12
- timedOut: (id: string) => Pending | undefined;
13
- list: () => Pending[];
14
- };
15
- export type PendingChanges = ReturnType<typeof pendingChanges>;
@@ -1,18 +0,0 @@
1
- // The changes taken and not yet answered, queued ones too: /health shows one the client gave up on.
2
- export const pendingChanges = () => {
3
- const open = new Set();
4
- const until = async (row, work) => {
5
- open.add(row);
6
- try {
7
- return await work;
8
- }
9
- finally {
10
- open.delete(row);
11
- }
12
- };
13
- const track = (change, fn) => until({ ...change, since: new Date().toISOString() }, Promise.resolve().then(fn));
14
- // A timed-out installer call stays listed until it settles.
15
- const linger = (id, since, work) => void until({ op: 'install', id, since, timedOut: true }, work).catch(() => undefined);
16
- const timedOut = (id) => [...open].find((row) => row.timedOut && row.id === id);
17
- return { track, linger, timedOut, list: () => [...open] };
18
- };
@@ -1,11 +0,0 @@
1
- import { type IncomingHttpHeaders } from 'node:http';
2
- import { type RequestHandler } from 'express';
3
- import { type Entries } from './entries.js';
4
- import { type Limits } from './limits.js';
5
- import { type Stopping } from './stopping.js';
6
- type ProxyLimits = Pick<Limits, 'gateMs' | 'answerMs'> & {
7
- stopping?: Stopping;
8
- };
9
- export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
10
- export declare const proxyTo: (entries: Entries, limits: ProxyLimits, hostToken?: string) => RequestHandler;
11
- export {};