@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,93 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { rm } from 'node:fs/promises';
3
- import { isAbsolute } from 'node:path';
4
- import { validRange } from 'semver';
5
- import { z } from 'zod';
6
- import { fail } from '../../envelope/envelope.js';
7
- import { parse } from '../../envelope/parse.js';
8
- import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
9
- import { readManifest } from '../../manifest/read-manifest.js';
10
- import { persist, summary } from './entries.js';
11
- import { runInstaller } from './installer-call.js';
12
- import {} from './installation.js';
13
- import { clearRunDir, dataDirOf } from './daemon-files.js';
14
- import { needsSecret } from './start-checks.js';
15
- import { startEntry, startFailed } from './supervisor.js';
16
- const RESERVED_ID = 'host';
17
- // The cli's rule for what follows `<id>@`: a version, a range or a dist-tag; never a path, URL or flag.
18
- const DIST_TAG = /^[A-Za-z][\w.-]*$/;
19
- const isVersionSpec = (spec) => !/\s/.test(spec) && (validRange(spec) !== null || DIST_TAG.test(spec));
20
- // POST and PATCH: the same rule, so no route hands the installer a path.
21
- export const VersionSpecSchema = z
22
- .string()
23
- .min(1)
24
- .refine(isVersionSpec, 'a version, a range or a dist-tag');
25
- // enabled: false records the extension and never starts it (a profile "off" entry).
26
- const AddSchema = z.union([
27
- z.strictObject({
28
- id: ExtensionIdSchema,
29
- version: VersionSpecSchema.optional(),
30
- enabled: z.boolean().optional(),
31
- }),
32
- z.strictObject({
33
- source: z.string().refine(isAbsolute, 'an absolute path'),
34
- enabled: z.boolean().optional(),
35
- }),
36
- ]);
37
- // The entry a 409 names, so a client can tell a repeat from another package of that id.
38
- const existing = ({ id, version, install }) => ({
39
- id,
40
- ...(version ? { version } : {}),
41
- ...(install.source ? { source: install.source } : {}),
42
- });
43
- const reserve = (entries, id) => {
44
- if (id === RESERVED_ID)
45
- throw fail('VALIDATION_ERROR', 'the id host is reserved');
46
- const has = entries.get(id);
47
- if (has)
48
- throw fail('CONFLICT', `${id} is installed`, { details: existing(has) });
49
- };
50
- const sourceEntry = async (source) => {
51
- const pkg = await readManifest(source).catch((err) => {
52
- throw fail('VALIDATION_ERROR', `${source}: ${err.message}`);
53
- });
54
- return { install: { id: pkg.agentage.id, source }, dir: source, version: pkg.version };
55
- };
56
- const marketEntry = async (deps, entries, id, version) => {
57
- reserve(entries, id);
58
- const got = await runInstaller(deps, { id, version });
59
- return { install: { id: got.id, version: got.version }, dir: got.dir, version: got.version };
60
- };
61
- // C6: a new id that did not start leaves no row; only a data folder this start made goes too.
62
- const rollBack = async (deps, entries, entry, fresh) => {
63
- entries.delete(entry.id);
64
- await persist(deps, entry.id);
65
- await clearRunDir(deps.configDir, entry.id);
66
- if (fresh)
67
- await rm(dataDirOf(deps.configDir, entry.id), { recursive: true, force: true });
68
- };
69
- // The first start; refused and rolled back unless it waits for a secret or the daemon stops (kept).
70
- const firstStart = async (deps, entries, entry) => {
71
- const fresh = !existsSync(dataDirOf(deps.configDir, entry.id));
72
- const err = await startEntry(deps, entry);
73
- if (!err || needsSecret(err) || deps.stopping.signal.aborted)
74
- return;
75
- await rollBack(deps, entries, entry, fresh);
76
- throw startFailed(entry, err);
77
- };
78
- // POST: installs (or links a folder), records it, then starts it (C6: a failed start is refused).
79
- export const addExtension = async (deps, entries, body) => {
80
- const spec = parse(AddSchema, body, 'Invalid body');
81
- const got = 'source' in spec
82
- ? await sourceEntry(spec.source)
83
- : await marketEntry(deps, entries, spec.id, spec.version);
84
- reserve(entries, got.install.id);
85
- const off = spec.enabled === false;
86
- const install = off ? { ...got.install, enabled: false } : got.install;
87
- await persist(deps, install.id, install);
88
- const entry = { ...got, id: install.id, install, state: 'disabled' };
89
- entries.set(entry.id, entry);
90
- if (!off)
91
- await firstStart(deps, entries, entry);
92
- return summary(entry);
93
- };
@@ -1,8 +0,0 @@
1
- import { type Express } from 'express';
2
- import { type AppRow } from '../app-bundle.js';
3
- import { type Entries } from './entries.js';
4
- import { type Entry } from './supervisor.js';
5
- export { type AppRow };
6
- export declare const appRowOf: (entry: Entry) => Promise<AppRow | undefined>;
7
- export declare const hasApp: (entries: Entries, id: string) => Promise<boolean>;
8
- export declare const appRoutes: (app: Express, entries: Entries) => void;
@@ -1,34 +0,0 @@
1
- import {} from 'express';
2
- import { fail } from '../../envelope/envelope.js';
3
- import { readManifest } from '../../manifest/read-manifest.js';
4
- import { appRowIn, appStatic } from '../app-bundle.js';
5
- import {} from './entries.js';
6
- import {} from './supervisor.js';
7
- export {};
8
- // The nav row of an enabled entry whose package has the app part, built; else none.
9
- export const appRowOf = async (entry) => {
10
- const dir = entry.dir;
11
- if (!dir || entry.install.enabled === false)
12
- return undefined;
13
- const pkg = await readManifest(dir).catch(() => undefined);
14
- return pkg && appRowIn(dir, pkg, entry.id);
15
- };
16
- // The app id of a page path, when the id is installed and has an app row.
17
- export const hasApp = async (entries, id) => {
18
- const entry = entries.get(id);
19
- return entry !== undefined && (await appRowOf(entry)) !== undefined;
20
- };
21
- const appDirOf = async (entries, id) => {
22
- const entry = entries.get(id);
23
- if (!entry || !(await appRowOf(entry)))
24
- throw fail('NOT_FOUND', `${id} has no app`);
25
- return entry.dir ?? '';
26
- };
27
- // GET /app/{id}/*: static from the package folder (not the child), so it answers while the child is down.
28
- const serveApp = (entries) => async (req, res, next) => {
29
- const root = await appDirOf(entries, String(req.params['id']));
30
- appStatic(root, false)(req, res, (err) => next(err && fail('NOT_FOUND', `${String(req.params['id'])} has no such app file`)));
31
- };
32
- export const appRoutes = (app, entries) => {
33
- app.use('/app/:id', serveApp(entries));
34
- };
@@ -1,2 +0,0 @@
1
- import { type RequestHandler } from 'express';
2
- export declare const ownAppOnly: RequestHandler;
@@ -1,12 +0,0 @@
1
- import {} from 'express';
2
- import { fail } from '../../envelope/envelope.js';
3
- // What useAppHost().api sends: the app that made the call.
4
- const APP_HEADER = 'x-agentage-app';
5
- // K10: an app calls only its own extension; a raw fetch with no header is not stopped (stated limit).
6
- export const ownAppOnly = (req, _res, next) => {
7
- const from = req.get(APP_HEADER);
8
- const id = String(req.params['id']);
9
- if (from !== undefined && from !== id)
10
- throw fail('FORBIDDEN', `the app ${from} may not call the extension ${id}`);
11
- next();
12
- };
@@ -1,10 +0,0 @@
1
- import { type Entries } from './entries.js';
2
- import { type ShellEvents } from './shell-events.js';
3
- export declare const isAppReload: (body: unknown) => boolean;
4
- export declare const reloadApp: (entries: Entries, id: string, events: ShellEvents) => Promise<{
5
- id: string;
6
- version: string;
7
- state: import("./supervisor.js").State;
8
- reloaded: boolean;
9
- part: string;
10
- }>;
@@ -1,18 +0,0 @@
1
- import { fail } from '../../envelope/envelope.js';
2
- import { appRowOf } from './app-files.js';
3
- import { entryOf } from './entries.js';
4
- import {} from './shell-events.js';
5
- // The body of a reload that names the app part: the child keeps running.
6
- export const isAppReload = (body) => typeof body === 'object' &&
7
- body !== null &&
8
- Object.keys(body).length === 1 &&
9
- body.part === 'app';
10
- // K8: the new build is in dist/app already; the shell re-imports the entry the event names.
11
- export const reloadApp = async (entries, id, events) => {
12
- const entry = entryOf(entries, id);
13
- const row = await appRowOf(entry);
14
- if (!row)
15
- throw fail('VALIDATION_ERROR', `${id} has no built app: run the app build first`);
16
- events.send('app', { id, entry: row.entry, css: row.css });
17
- return { id, version: entry.version, state: entry.state, reloaded: true, part: 'app' };
18
- };
@@ -1,20 +0,0 @@
1
- interface RunSpec {
2
- id: string;
3
- dir: string;
4
- dataDir: string;
5
- secrets: Record<string, string>;
6
- }
7
- export interface RunFolders {
8
- runDir: string;
9
- secretsDir: string;
10
- tmpDir: string;
11
- made: {
12
- run?: string;
13
- data: boolean;
14
- };
15
- }
16
- export declare const configDirOf: (dataDir: string) => string;
17
- export declare const makeRun: (spec: RunSpec) => Promise<RunFolders>;
18
- export declare const fillRun: (run: RunFolders, spec: RunSpec) => Promise<void>;
19
- export declare const undoRun: ({ runDir, made }: RunFolders, dataDir: string) => Promise<void>;
20
- export {};
@@ -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>;