@agentage/extension 0.20.0 → 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 (122) hide show
  1. package/dist/auth/part-auth.js +4 -5
  2. package/dist/context/context.d.ts +0 -1
  3. package/dist/contracts/index.d.ts +1 -1
  4. package/dist/contracts/index.js +1 -1
  5. package/dist/discovery/combine-answers.d.ts +42 -0
  6. package/dist/discovery/combine-answers.js +70 -0
  7. package/dist/discovery/combine.d.ts +2 -28
  8. package/dist/discovery/combine.js +3 -44
  9. package/dist/discovery/discovery.d.ts +1 -1
  10. package/dist/discovery/discovery.schema.d.ts +14 -4
  11. package/dist/discovery/discovery.schema.js +10 -5
  12. package/dist/discovery/host-document.schema.d.ts +44 -0
  13. package/dist/discovery/host-document.schema.js +3 -6
  14. package/dist/host/child-env.d.ts +11 -0
  15. package/dist/host/child-env.js +12 -0
  16. package/dist/host/{daemon/guard.js → guard.js} +1 -1
  17. package/dist/host/host-extension.js +1 -1
  18. package/dist/host/host-main.d.ts +1 -0
  19. package/dist/host/host-main.js +3 -0
  20. package/dist/host/index.d.ts +2 -6
  21. package/dist/host/index.js +1 -5
  22. package/dist/host/kit-shell.d.ts +1 -0
  23. package/dist/host/kit-shell.js +8 -0
  24. package/dist/host/serve-host.js +1 -1
  25. package/dist/internal/index.d.ts +29 -0
  26. package/dist/internal/index.js +30 -0
  27. package/dist/runtime/part-mounts.d.ts +0 -1
  28. package/dist/runtime/part-mounts.js +1 -1
  29. package/dist/runtime/run-part.js +0 -2
  30. package/dist/server/app.d.ts +0 -1
  31. package/dist/server/app.js +4 -5
  32. package/dist/server/discovery-handler.js +11 -3
  33. package/dist/shell/dist/index.html +1 -1
  34. package/dist/shell/dist/shell.css +1 -1
  35. package/dist/tool/check.js +3 -0
  36. package/dist/tool/recipe.js +2 -2
  37. package/dist/tool/up/gateway.js +0 -3
  38. package/package.json +5 -1
  39. package/schemas/extension-discovery.schema.json +40 -22
  40. package/dist/host/daemon/add.d.ts +0 -11
  41. package/dist/host/daemon/add.js +0 -93
  42. package/dist/host/daemon/app-files.d.ts +0 -8
  43. package/dist/host/daemon/app-files.js +0 -34
  44. package/dist/host/daemon/app-header.d.ts +0 -2
  45. package/dist/host/daemon/app-header.js +0 -12
  46. package/dist/host/daemon/app-reload.d.ts +0 -10
  47. package/dist/host/daemon/app-reload.js +0 -18
  48. package/dist/host/daemon/child-files.d.ts +0 -20
  49. package/dist/host/daemon/child-files.js +0 -53
  50. package/dist/host/daemon/child.d.ts +0 -30
  51. package/dist/host/daemon/child.js +0 -126
  52. package/dist/host/daemon/cli-user-watch.d.ts +0 -9
  53. package/dist/host/daemon/cli-user-watch.js +0 -47
  54. package/dist/host/daemon/cli-user.d.ts +0 -2
  55. package/dist/host/daemon/cli-user.js +0 -42
  56. package/dist/host/daemon/daemon-files.d.ts +0 -20
  57. package/dist/host/daemon/daemon-files.js +0 -46
  58. package/dist/host/daemon/daemon-owner.d.ts +0 -1
  59. package/dist/host/daemon/daemon-owner.js +0 -32
  60. package/dist/host/daemon/daemon.d.ts +0 -19
  61. package/dist/host/daemon/daemon.js +0 -137
  62. package/dist/host/daemon/entries.d.ts +0 -21
  63. package/dist/host/daemon/entries.js +0 -24
  64. package/dist/host/daemon/gate.d.ts +0 -3
  65. package/dist/host/daemon/gate.js +0 -19
  66. package/dist/host/daemon/health-routes.d.ts +0 -18
  67. package/dist/host/daemon/health-routes.js +0 -75
  68. package/dist/host/daemon/host-token.d.ts +0 -6
  69. package/dist/host/daemon/host-token.js +0 -28
  70. package/dist/host/daemon/installation.d.ts +0 -35
  71. package/dist/host/daemon/installation.js +0 -90
  72. package/dist/host/daemon/installer-call.d.ts +0 -21
  73. package/dist/host/daemon/installer-call.js +0 -48
  74. package/dist/host/daemon/json-file.d.ts +0 -6
  75. package/dist/host/daemon/json-file.js +0 -90
  76. package/dist/host/daemon/lane.d.ts +0 -9
  77. package/dist/host/daemon/lane.js +0 -24
  78. package/dist/host/daemon/last-words.d.ts +0 -2
  79. package/dist/host/daemon/last-words.js +0 -28
  80. package/dist/host/daemon/limits.d.ts +0 -16
  81. package/dist/host/daemon/limits.js +0 -31
  82. package/dist/host/daemon/ops.d.ts +0 -12
  83. package/dist/host/daemon/ops.js +0 -94
  84. package/dist/host/daemon/patch-values.d.ts +0 -6
  85. package/dist/host/daemon/patch-values.js +0 -39
  86. package/dist/host/daemon/pending.d.ts +0 -15
  87. package/dist/host/daemon/pending.js +0 -18
  88. package/dist/host/daemon/proxy.d.ts +0 -11
  89. package/dist/host/daemon/proxy.js +0 -106
  90. package/dist/host/daemon/queue.d.ts +0 -3
  91. package/dist/host/daemon/queue.js +0 -27
  92. package/dist/host/daemon/redact-stream.d.ts +0 -4
  93. package/dist/host/daemon/redact-stream.js +0 -24
  94. package/dist/host/daemon/reload-marker.d.ts +0 -8
  95. package/dist/host/daemon/reload-marker.js +0 -57
  96. package/dist/host/daemon/reload.d.ts +0 -10
  97. package/dist/host/daemon/reload.js +0 -72
  98. package/dist/host/daemon/restart.d.ts +0 -14
  99. package/dist/host/daemon/restart.js +0 -59
  100. package/dist/host/daemon/routes.d.ts +0 -6
  101. package/dist/host/daemon/routes.js +0 -101
  102. package/dist/host/daemon/run-lock.d.ts +0 -1
  103. package/dist/host/daemon/run-lock.js +0 -15
  104. package/dist/host/daemon/seal-reach.d.ts +0 -2
  105. package/dist/host/daemon/seal-reach.js +0 -38
  106. package/dist/host/daemon/seal.d.ts +0 -20
  107. package/dist/host/daemon/seal.js +0 -93
  108. package/dist/host/daemon/shell-events.d.ts +0 -9
  109. package/dist/host/daemon/shell-events.js +0 -36
  110. package/dist/host/daemon/shell-routes.d.ts +0 -29
  111. package/dist/host/daemon/shell-routes.js +0 -68
  112. package/dist/host/daemon/sign-in-page.d.ts +0 -3
  113. package/dist/host/daemon/sign-in-page.js +0 -30
  114. package/dist/host/daemon/start-checks.d.ts +0 -6
  115. package/dist/host/daemon/start-checks.js +0 -29
  116. package/dist/host/daemon/stopping.d.ts +0 -10
  117. package/dist/host/daemon/stopping.js +0 -28
  118. package/dist/host/daemon/supervisor.d.ts +0 -59
  119. package/dist/host/daemon/supervisor.js +0 -107
  120. package/dist/host/daemon/write-all.d.ts +0 -8
  121. package/dist/host/daemon/write-all.js +0 -45
  122. /package/dist/host/{daemon/guard.d.ts → guard.d.ts} +0 -0
@@ -1,53 +0,0 @@
1
- import { mkdir, rm, rmdir, writeFile } from 'node:fs/promises';
2
- import { dirname, join } from 'node:path';
3
- import { secretNames } from '../../manifest/parts.js';
4
- import { SecretNameSchema } from '../../manifest/primitives.schema.js';
5
- import { readManifest } from '../../manifest/read-manifest.js';
6
- import { clearOldLock } from '../data-lock.js';
7
- import { runDirOf } from './daemon-files.js';
8
- import { clearRunLock } from './run-lock.js';
9
- // The supervisor's dataDir is <configDir>/data/{id}, so run/{id} sits beside data/ (C2).
10
- export const configDirOf = (dataDir) => dirname(dirname(dataDir));
11
- // Only the names the package declares now: a row can still hold one an older version declared.
12
- const declared = async (spec) => {
13
- const names = new Set(secretNames(await readManifest(spec.dir)));
14
- return Object.entries(spec.secrets).filter(([name]) => names.has(name));
15
- };
16
- // The folders first, so undoRun knows what this launch made; data/{id} before the fork (PGlite).
17
- export const makeRun = async (spec) => {
18
- const runDir = runDirOf(configDirOf(spec.dataDir), spec.id);
19
- const made = { run: await mkdir(runDir, { recursive: true, mode: 0o700 }), data: false };
20
- const run = { runDir, secretsDir: join(runDir, 'secrets'), tmpDir: join(runDir, 'tmp'), made };
21
- const data = await mkdir(spec.dataDir, { recursive: true }).catch(async (err) => {
22
- await undoRun(run, spec.dataDir);
23
- throw err;
24
- });
25
- made.data = data !== undefined;
26
- return run;
27
- };
28
- // Fresh secrets and tmp; the old lock beside data/{id} and a left-over run lock are cleared.
29
- export const fillRun = async (run, spec) => {
30
- for (const dir of [run.secretsDir, run.tmpDir]) {
31
- await rm(dir, { recursive: true, force: true });
32
- await mkdir(dir, { mode: 0o700 });
33
- }
34
- await clearOldLock(`${spec.dataDir}.lock`);
35
- await clearRunLock(join(run.runDir, 'store.lock'), run.runDir);
36
- for (const [name, value] of await declared(spec))
37
- await writeFile(join(run.secretsDir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
38
- };
39
- // From dir up to top, each folder only while it is empty: rmdir refuses one that is not.
40
- const emptyUpTo = async (dir, top) => {
41
- for (; dir.startsWith(top); dir = dirname(dir))
42
- if (await rmdir(dir).catch(() => 'kept'))
43
- return;
44
- };
45
- // A child that never reported its port: what this launch made goes, run/ only while empty.
46
- export const undoRun = async ({ runDir, made }, dataDir) => {
47
- if (made.run)
48
- await rm(runDir, { recursive: true, force: true });
49
- if (made.run)
50
- await emptyUpTo(dirname(runDir), made.run);
51
- if (made.data)
52
- await rmdir(dataDir).catch(() => undefined);
53
- };
@@ -1,30 +0,0 @@
1
- import { type Seal } from './seal.js';
2
- interface LaunchSpec {
3
- id: string;
4
- dir: string;
5
- dataDir: string;
6
- settings: Record<string, unknown>;
7
- secrets: Record<string, string>;
8
- origin: string;
9
- storeOpenMs?: number;
10
- userSub?: string;
11
- }
12
- export interface Exit {
13
- code: number | null;
14
- signal: string | null;
15
- words?: string;
16
- }
17
- export interface Child {
18
- port: number;
19
- pid: number;
20
- exited: Promise<Exit>;
21
- stop(): Promise<void>;
22
- }
23
- export type Launch = ((spec: LaunchSpec) => Promise<Child>) & {
24
- clockRate?: number;
25
- seal?: Seal;
26
- node?: string;
27
- };
28
- export declare const childEnv: (spec: LaunchSpec, secretsDir: string, runDir?: string) => Record<string, string>;
29
- export declare const forkLaunch: (main?: string, startMs?: number, rate?: number, node?: string) => Launch;
30
- export {};
@@ -1,126 +0,0 @@
1
- import { fork } from 'node:child_process';
2
- import { rm } from 'node:fs/promises';
3
- import { fileURLToPath } from 'node:url';
4
- import { CLOCK_RATE_ENV, parseClockRate } from '../../worker/clock.js';
5
- import { configDirOf, fillRun, makeRun, undoRun } from './child-files.js';
6
- import { lastWords } from './last-words.js';
7
- import { LIMITS } from './limits.js';
8
- import { pipeRedacted } from './redact-stream.js';
9
- import { readManifest } from '../../manifest/read-manifest.js';
10
- import { permissionFlag, sealFlags, sealOf, spawnsGit } from './seal.js';
11
- const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
12
- const STOP_MS = 5_000;
13
- const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
14
- // What dist/host/main.js reads (docs/part-image.md), on a port the OS picks.
15
- export const childEnv = (spec, secretsDir, runDir) => ({
16
- PORT: '0',
17
- AGENTAGE_EXTENSION_DIR: spec.dir,
18
- AGENTAGE_DATA_DIR: spec.dataDir,
19
- AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
20
- AGENTAGE_SECRETS_DIR: secretsDir,
21
- AGENTAGE_ORIGIN: spec.origin,
22
- ...(runDir && { AGENTAGE_RUN_DIR: runDir }),
23
- ...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
24
- ...(spec.userSub && { AGENTAGE_USER_SUB: spec.userSub }),
25
- });
26
- const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
27
- const captured = (child, secrets) => {
28
- let tail = '';
29
- pipeRedacted(child.stdout, process.stdout, secrets);
30
- pipeRedacted(child.stderr, process.stderr, secrets);
31
- child.stderr?.on('data', (chunk) => (tail = (tail + chunk.toString()).slice(-4000)));
32
- return () => tail;
33
- };
34
- // 'exit' can come before the last stderr chunk: wait for the stream end, at most 500 ms.
35
- const flushed = (child) => new Promise((resolve) => {
36
- if (!child.stderr || child.stderr.readableEnded)
37
- return resolve();
38
- child.stderr.once('end', resolve);
39
- setTimeout(resolve, 500).unref();
40
- });
41
- const exitOf = (child, tail) => new Promise((resolve) => child.once('exit', (code, signal) => {
42
- const how = { code, signal };
43
- void flushed(child).then(() => resolve({ ...how, words: lastWords(tail(), how) }));
44
- }));
45
- const portOf = (msg) => {
46
- const { type, port } = (msg ?? {});
47
- return type === 'ready' && typeof port === 'number' ? port : undefined;
48
- };
49
- // The port the child bound, or why it exited first; a child silent for startMs is killed.
50
- const readyOf = (child, tail, startMs) => new Promise((resolve, reject) => {
51
- let killed = false;
52
- const timer = setTimeout(() => ((killed = true), child.kill('SIGKILL')), startMs);
53
- const settle = (fn) => {
54
- clearTimeout(timer);
55
- fn();
56
- };
57
- child.on('message', (msg) => {
58
- const port = portOf(msg);
59
- if (port)
60
- settle(() => resolve(port));
61
- });
62
- child.once('exit', (code, signal) => {
63
- const why = killed
64
- ? `reported no port in ${startMs} ms: killed`
65
- : lastWords(tail(), { code, signal });
66
- settle(() => reject(new Error(why)));
67
- });
68
- });
69
- // SIGTERM drains; a child still there after STOP_MS (a request that never ends) gets SIGKILL.
70
- const stopOf = (child, exited) => async () => {
71
- if (child.exitCode === null && child.signalCode === null)
72
- child.kill('SIGTERM');
73
- const kill = setTimeout(() => child.kill('SIGKILL'), STOP_MS);
74
- await exited;
75
- clearTimeout(kill);
76
- };
77
- // The daemon's own node flags (a loader, --input-type) are never the child's; C2 where Node has --permission.
78
- const execArgvOf = async (node, main, spec, run) => {
79
- if (!permissionFlag(node))
80
- return [];
81
- const configDir = configDirOf(spec.dataDir);
82
- const { id, dir, dataDir } = spec;
83
- const childProcess = spawnsGit(await readManifest(dir));
84
- return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir, childProcess });
85
- };
86
- // The listed env of the daemon, then the child's own: TMPDIR in run/{id}, the test clock when not 1.
87
- const envOf = (spec, run, clockRate) => ({
88
- ...passedEnv(),
89
- ...childEnv(spec, run.secretsDir, run.runDir),
90
- TMPDIR: run.tmpDir,
91
- ...(clockRate === 1 ? {} : { [CLOCK_RATE_ENV]: String(clockRate) }),
92
- });
93
- const started = async (at, spec, run) => {
94
- const execArgv = await execArgvOf(at.node, at.main, spec, run);
95
- await fillRun(run, spec);
96
- const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
97
- const child = fork(at.main, [], {
98
- env: envOf(spec, run, at.clockRate),
99
- execArgv,
100
- stdio: [...stdio],
101
- });
102
- const tail = captured(child, spec.secrets);
103
- const exited = exitOf(child, tail);
104
- const port = await readyOf(child, tail, at.startMs);
105
- return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
106
- };
107
- // Anything before the port (files, the seal check, the start) undoes the folders this launch made.
108
- const launchAt = (at) => async (spec) => {
109
- const run = await makeRun(spec);
110
- try {
111
- return await started(at, spec, run);
112
- }
113
- catch (err) {
114
- await undoRun(run, spec.dataDir);
115
- throw err;
116
- }
117
- finally {
118
- await rm(run.secretsDir, { recursive: true, force: true });
119
- }
120
- };
121
- // One child process per extension on a port the OS picks; node: the version the seal gate reads.
122
- export const forkLaunch = (main = HOST_MAIN, startMs = LIMITS.startMs, rate, node = process.versions.node) => {
123
- const clockRate = parseClockRate(rate);
124
- const launch = launchAt({ main, startMs, clockRate, node });
125
- return Object.assign(launch, { clockRate, seal: sealOf(node), node });
126
- };
@@ -1,9 +0,0 @@
1
- import { type Entries } from './entries.js';
2
- import { type ShellEvents } from './shell-events.js';
3
- import { type SupervisorDeps } from './supervisor.js';
4
- export interface CliUser {
5
- text?: string;
6
- sub?: string;
7
- }
8
- export declare const syncCliUser: (deps: SupervisorDeps, entries: Entries, events?: ShellEvents, polls?: number) => Promise<boolean>;
9
- export declare const watchCliUser: (deps: SupervisorDeps, entries: Entries, events?: ShellEvents) => (() => void);
@@ -1,47 +0,0 @@
1
- import {} from './entries.js';
2
- import { cliUserOf, readCliAuth } from './cli-user.js';
3
- import { halt, hold } from './gate.js';
4
- import {} from './shell-events.js';
5
- import { startEntry } from './supervisor.js';
6
- // A failed session check (offline) is tried again this many polls later, with the same file.
7
- const RETRY_POLLS = 30;
8
- const restart = async (deps, entry) => {
9
- const release = hold(entry);
10
- try {
11
- await halt(entry, deps.drainMs);
12
- await startEntry(deps, entry);
13
- }
14
- finally {
15
- release();
16
- }
17
- };
18
- // Read the file; a new user (sign-in, sign-out, another account) restarts every running child.
19
- export const syncCliUser = async (deps, entries, events, polls = 0) => {
20
- const text = await readCliAuth(deps.configDir);
21
- const retry = text !== '' && deps.user.sub === undefined && polls % RETRY_POLLS === 0;
22
- if (text === deps.user.text && !retry)
23
- return false;
24
- const sub = await cliUserOf(text);
25
- const changed = sub !== deps.user.sub;
26
- Object.assign(deps.user, { text, sub });
27
- // A signed-in file shows its email and name too; signed out says it once, not on each offline retry.
28
- if (changed || sub !== undefined)
29
- events?.send('session', { signedIn: sub !== undefined });
30
- if (!changed)
31
- return false;
32
- deps.log.info('cli user changed: running extensions restart', { signedIn: sub !== undefined });
33
- for (const entry of entries.values())
34
- if (entry.lane)
35
- await restart(deps, entry);
36
- return true;
37
- };
38
- // Polled in the change queue, so a restart never runs inside an install, update or reload.
39
- export const watchCliUser = (deps, entries, events) => {
40
- let polls = 0;
41
- const tick = () => void deps
42
- .queue(() => syncCliUser(deps, entries, events, ++polls))
43
- .catch((err) => deps.log.warn('cli user not read', { reason: err.message }));
44
- const timer = setInterval(tick, deps.userPollMs);
45
- timer.unref();
46
- return () => clearInterval(timer);
47
- };
@@ -1,2 +0,0 @@
1
- export declare const cliUserOf: (text: string) => Promise<string | undefined>;
2
- export declare const readCliAuth: (configDir: string) => Promise<string>;
@@ -1,42 +0,0 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- // A segment the extension may use as a folder name (memory: <root>/<sub>/<vault>.git).
4
- const SUB = /^[A-Za-z0-9_-]{1,128}$/;
5
- const SESSION_MS = 3_000;
6
- const objectOf = (value) => typeof value === 'object' && value !== null ? value : {};
7
- const subOf = (value) => typeof value === 'string' && SUB.test(value) ? value : undefined;
8
- const parsed = (text) => {
9
- try {
10
- return objectOf(JSON.parse(text));
11
- }
12
- catch {
13
- return {};
14
- }
15
- };
16
- // The platform token of the issuer (aga_<jwt>) names the sub, no network.
17
- const tokenSub = (auth, issuer) => {
18
- const token = String(objectOf(objectOf(auth['platformPats'])[issuer])['token'] ?? '');
19
- return subOf(parsed(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString())['sub']);
20
- };
21
- // The session as the cli checks it (get-session with its bearer); any failure is no user.
22
- const sessionSub = async (issuer, bearer) => {
23
- if (typeof bearer !== 'string' || !bearer)
24
- return undefined;
25
- const url = `${issuer}/api/auth/mcp/get-session`;
26
- const headers = { authorization: `Bearer ${bearer}` };
27
- const signal = AbortSignal.timeout(SESSION_MS);
28
- const res = await fetch(url, { headers, signal, redirect: 'error' }).catch(() => undefined);
29
- if (!res?.ok)
30
- return void (await res?.body?.cancel());
31
- return subOf(objectOf(await res.json().catch(() => null))['userId']);
32
- };
33
- const isOrigin = (value) => typeof value === 'string' && URL.canParse(value) && new URL(value).origin === value;
34
- // The user of an auth.json text: only of its own issuer; no issuer (a session before cli 0.50.1) is none.
35
- export const cliUserOf = async (text) => {
36
- const auth = parsed(text);
37
- const issuer = auth['issuer'];
38
- if (!isOrigin(issuer))
39
- return undefined;
40
- return tokenSub(auth, issuer) ?? sessionSub(issuer, objectOf(auth['tokens'])['accessToken']);
41
- };
42
- export const readCliAuth = (configDir) => readFile(join(configDir, 'auth.json'), 'utf8').catch(() => '');
@@ -1,20 +0,0 @@
1
- export declare const DAEMON_PROTOCOL = 1;
2
- interface DaemonFile {
3
- pid: number;
4
- port: number;
5
- version: string;
6
- protocol: number;
7
- startedBy: string;
8
- hostToken: string;
9
- }
10
- export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => Promise<void>;
11
- export declare const removeDaemonFile: (configDir: string) => Promise<void>;
12
- export declare const dataDirOf: (configDir: string, id: string) => string;
13
- export declare const runDirOf: (configDir: string, id: string) => string;
14
- export declare const clearRunDir: (configDir: string, id: string) => Promise<void>;
15
- export declare const purgeData: (configDir: string, id: string) => Promise<void>;
16
- type ValueKind = 'settings' | 'secrets';
17
- type Values = Record<string, unknown>;
18
- export declare const readValues: (configDir: string, kind: ValueKind, id: string) => Promise<Values>;
19
- export declare const writeValues: (configDir: string, kind: ValueKind, id: string, values?: Values, waitMs?: number) => Promise<void>;
20
- export {};
@@ -1,46 +0,0 @@
1
- import { rm, unlink } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
- import { fail } from '../../envelope/envelope.js';
4
- import { readJsonFile, unreadableReason, withFileLock, writeJsonFile } from './json-file.js';
5
- const DAEMON_FILE = 'daemon.json';
6
- export const DAEMON_PROTOCOL = 1;
7
- export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file, 0o600);
8
- export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
9
- export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
10
- // C2: the folder only this child reads and writes (secrets, TMPDIR, the store lock).
11
- export const runDirOf = (configDir, id) => join(configDir, 'run', id);
12
- // No user data in it: removed with the extension; each start makes its secrets and tmp anew.
13
- export const clearRunDir = (configDir, id) => rm(runDirOf(configDir, id), { recursive: true, force: true });
14
- export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
15
- const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
16
- const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
17
- // A file that is not JSON, or not { id: { name: value } }, is refused by name and never written over.
18
- const unreadable = (kind, reason) => fail('CONFLICT', `${kind}.json cannot be read (${reason}): fix it; no change is written`, {
19
- code: `${kind.toUpperCase()}_UNREADABLE`,
20
- details: { file: `${kind}.json`, reason },
21
- });
22
- const rowsOf = async (configDir, kind) => {
23
- const all = await readJsonFile(fileOf(configDir, kind), {}).catch((err) => {
24
- throw unreadable(kind, unreadableReason(err));
25
- });
26
- if (!isObject(all) || !Object.values(all).every(isObject))
27
- throw unreadable(kind, 'not an object of rows by id');
28
- return all;
29
- };
30
- export const readValues = async (configDir, kind, id) => (await rowsOf(configDir, kind))[id] ?? {};
31
- // The rows of one file changed under its lock; the same object back writes nothing.
32
- const changeValues = (configDir, kind, change, waitMs) => {
33
- const file = fileOf(configDir, kind);
34
- const write = async () => {
35
- const all = await rowsOf(configDir, kind);
36
- const next = change(all);
37
- if (next !== all)
38
- await writeJsonFile(file, next, kind === 'secrets' ? 0o600 : 0o644);
39
- };
40
- return withFileLock(file, write, waitMs);
41
- };
42
- export const writeValues = (configDir, kind, id, values, waitMs) => changeValues(configDir, kind, (all) => {
43
- const rest = { ...all };
44
- delete rest[id];
45
- return values ? { ...rest, [id]: values } : rest;
46
- }, waitMs);
@@ -1 +0,0 @@
1
- export declare const assertNoOtherDaemon: (configDir: string) => Promise<void>;
@@ -1,32 +0,0 @@
1
- import { join } from 'node:path';
2
- import { fail } from '../../envelope/envelope.js';
3
- import { readJsonFile } from './json-file.js';
4
- const alive = (pid) => {
5
- try {
6
- return process.kill(pid, 0);
7
- }
8
- catch (err) {
9
- return err.code === 'EPERM';
10
- }
11
- };
12
- // A daemon.json of a dead or other process is stale: only one that answers as that daemon counts.
13
- const answersAsDaemon = async (port, pid) => {
14
- const res = await fetch(`http://127.0.0.1:${port}/health`, {
15
- signal: AbortSignal.timeout(1_000),
16
- });
17
- const body = (await res.json());
18
- return body.service === 'agentage-daemon' && body.pid === pid;
19
- };
20
- // installation.json belongs to the daemon that runs on configDir; its own process may write it.
21
- export const assertNoOtherDaemon = async (configDir) => {
22
- const file = await readJsonFile(join(configDir, 'daemon.json'), null).catch(() => null);
23
- const { pid, port } = file ?? {};
24
- if (!pid || !port || pid === process.pid || !alive(pid))
25
- return;
26
- if (!(await answersAsDaemon(port, pid).catch(() => false)))
27
- return;
28
- throw fail('CONFLICT', `a daemon (process ${pid}) runs on ${configDir}: change it through it`, {
29
- code: 'DAEMON_RUNNING',
30
- details: { pid, port },
31
- });
32
- };
@@ -1,19 +0,0 @@
1
- import { type Launch } from './child.js';
2
- import { type Limits } from './limits.js';
3
- import { type Installer } from './supervisor.js';
4
- export interface DaemonOptions extends Partial<Limits> {
5
- configDir: string;
6
- port?: number;
7
- install?: Installer;
8
- version: string;
9
- startedBy: string;
10
- clockRate?: number;
11
- shellDir?: string;
12
- }
13
- export interface Daemon {
14
- port: number;
15
- stop(): Promise<void>;
16
- }
17
- export declare const DAEMON_PORT = 4243;
18
- export declare const startDaemon: (opts: DaemonOptions, launch: Launch) => Promise<Daemon>;
19
- export declare const createDaemon: (opts: DaemonOptions) => Promise<Daemon>;
@@ -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
- };