@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,59 +0,0 @@
1
- import {} from './child.js';
2
- import {} from './lane.js';
3
- import {} from './supervisor.js';
4
- // C6: the restarts since the last enable, update, configure or reload (/health reads it).
5
- export const restartsOf = (entry) => entry.restarts ?? 0;
6
- export const cancelRestart = (entry) => {
7
- if (entry.retry)
8
- clearTimeout(entry.retry.timer);
9
- entry.retry = undefined;
10
- };
11
- // A new start the owner asked for: the exits and the backoff begin again.
12
- export const resetRestarts = (entry) => {
13
- cancelRestart(entry);
14
- Object.assign(entry, { exits: [], restarts: 0 });
15
- };
16
- // Healthy for healthyResetMs on the same child: the past exits no longer count.
17
- export const healthyFor = (deps, entry, lane) => {
18
- const reset = () => entry.lane === lane && Object.assign(entry, { exits: [], restarts: 0 });
19
- setTimeout(reset, deps.healthyResetMs).unref();
20
- };
21
- export const reasonOf = (how) => how.words || `the process exited (${how.signal ? `signal ${how.signal}` : `code ${how.code}`})`;
22
- // The backoff grows with each restart since the reset; the last value repeats.
23
- const delayOf = (deps, restarts) => deps.backoffMs[Math.min(restarts, deps.backoffMs.length - 1)] ?? 0;
24
- const giveUp = (deps, entry, why) => {
25
- const min = Math.round(deps.crashWindowMs / 60_000);
26
- const error = `exited ${deps.crashLimit} times in ${min} min: ${why}`;
27
- Object.assign(entry, { state: 'failed', error });
28
- deps.log.warn('extension failed: too many exits', { id: entry.id, reason: why });
29
- };
30
- // In the queue, so it never runs inside a change; a change, remove, reload or stop since cancels it.
31
- const run = async (deps, entry, retry, again) => {
32
- if (entry.retry !== retry || entry.lane || deps.stopping.signal.aborted)
33
- return;
34
- entry.retry = undefined;
35
- if (entry.install.enabled === false)
36
- return;
37
- entry.restarts = restartsOf(entry) + 1;
38
- deps.log.info('extension restarts', { id: entry.id, restarts: entry.restarts });
39
- await again();
40
- };
41
- const schedule = (deps, entry, ms, again) => {
42
- const retry = {};
43
- const fire = () => void deps.queue(() => run(deps, entry, retry, again)).catch(() => undefined);
44
- retry.timer = setTimeout(fire, ms);
45
- retry.timer.unref();
46
- entry.retry = retry;
47
- };
48
- // A child that was the route exited (or a restart did not start): restart after the backoff, or failed.
49
- export const crashed = (deps, entry, why, again) => {
50
- const now = Date.now();
51
- const exits = [...(entry.exits ?? []), now].filter((at) => at > now - deps.crashWindowMs);
52
- entry.exits = exits;
53
- if (exits.length >= deps.crashLimit)
54
- return giveUp(deps, entry, why);
55
- const ms = delayOf(deps, restartsOf(entry));
56
- Object.assign(entry, { state: 'starting', error: `${why}: restart in ${ms} ms` });
57
- deps.log.warn('extension process exited', { id: entry.id, reason: why, restartMs: ms });
58
- schedule(deps, entry, ms, again);
59
- };
@@ -1,6 +0,0 @@
1
- import { type Express } from 'express';
2
- import { type Entries } from './entries.js';
3
- import { type DaemonInfo } from './health-routes.js';
4
- import { type ShellEvents } from './shell-events.js';
5
- import { type SupervisorDeps } from './supervisor.js';
6
- export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo, hostToken: string, events?: ShellEvents) => Express;
@@ -1,101 +0,0 @@
1
- import express, {} from 'express';
2
- import { agcidMiddleware } from '../../agcid/scope.js';
3
- import { ok } from '../../envelope/envelope.js';
4
- import { BODY_LIMIT } from '../../server/app.js';
5
- import { errorHandler, notFound } from '../../server/errors.js';
6
- import { localOnly } from './guard.js';
7
- import { ownAppOnly } from './app-header.js';
8
- import { appRoutes } from './app-files.js';
9
- import { isAppReload, reloadApp } from './app-reload.js';
10
- import { addExtension } from './add.js';
11
- import { listed } from './entries.js';
12
- import { healthRoutes } from './health-routes.js';
13
- import { requireHostToken } from './host-token.js';
14
- import { assertReadable } from './installation.js';
15
- import { changeExtension, removeExtension } from './ops.js';
16
- import {} from './pending.js';
17
- import { waitAtMost } from './queue.js';
18
- import { proxyTo } from './proxy.js';
19
- import { reloadExtension } from './reload.js';
20
- import { shellEvents } from './shell-events.js';
21
- import { shellRoutes } from './shell-routes.js';
22
- import { stopsNow } from './stopping.js';
23
- import {} from './supervisor.js';
24
- const reasonOf = (err) => err.details?.reason;
25
- // A refusal for a file that turned not JSON shows in /health until a change reads the file again.
26
- const checkReadable = (deps, info) => assertReadable(deps.configDir, info.unreadable).then(() => void (info.notJson = false), (err) => {
27
- info.notJson = reasonOf(err) === 'not JSON';
28
- throw err;
29
- });
30
- // What a POST body names, for /health: the id, or the folder.
31
- const named = (body) => {
32
- const { id, source } = (body ?? {});
33
- if (typeof id === 'string')
34
- return { id };
35
- return typeof source === 'string' ? { source } : {};
36
- };
37
- // Every change in the queue, and none while installation.json cannot be read.
38
- const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(deps.queue, deps.installMs, async () => {
39
- if (deps.stopping.signal.aborted)
40
- throw stopsNow();
41
- await checkReadable(deps, info);
42
- return fn();
43
- }));
44
- const purge = (q) => q['purge'] === 'true';
45
- // Each change that went through tells the open shell pages to read discovery again (K7).
46
- const changes = (deps, entries, info, events) => {
47
- const queued = runner(deps, info, deps.pending);
48
- const run = async (what, fn) => {
49
- const done = await queued(what, fn);
50
- events.send('extensions', { op: what.op, ...(what.id && { id: what.id }) });
51
- return done;
52
- };
53
- const id = (params) => String(params['id']);
54
- const add = async (req, res) => {
55
- const what = { op: 'install', ...named(req.body) };
56
- res.status(201).json(ok(await run(what, () => addExtension(deps, entries, req.body))));
57
- };
58
- const change = async ({ params, body }, res) => {
59
- const what = { op: 'update', id: id(params) };
60
- res.json(ok(await run(what, () => changeExtension(deps, entries, id(params), body))));
61
- };
62
- const remove = async ({ params, query }, res) => {
63
- const what = { op: 'remove', id: id(params) };
64
- res.json(ok(await run(what, () => removeExtension(deps, entries, what.id, purge(query)))));
65
- };
66
- const reload = async ({ params, body }, res) => {
67
- const what = { op: 'reload', id: id(params) };
68
- if (isAppReload(body))
69
- return void res.json(ok(await queued(what, () => reloadApp(entries, what.id, events))));
70
- res.json(ok(await run(what, () => reloadExtension(deps, entries, what.id, body))));
71
- };
72
- return { add, change, remove, reload };
73
- };
74
- const hostRoutes = (app, deps, entries, info, events) => {
75
- app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
76
- const json = express.json({ limit: BODY_LIMIT });
77
- const { add, change, remove, reload } = changes(deps, entries, info, events);
78
- app.post('/host/extensions', json, add);
79
- app.patch('/host/extensions/:id', json, change);
80
- app.delete('/host/extensions/:id', remove);
81
- app.post('/host/extensions/:id/reload', json, reload);
82
- };
83
- // C5 and C1: /health, discovery, /host/* (host token); /api, /mcp, /connector, /files of {id} to the child; S1.2 the shell and /app.
84
- export const daemonApp = (deps, entries, port, info, hostToken, events = shellEvents()) => {
85
- const app = express();
86
- const proxy = proxyTo(entries, deps, hostToken);
87
- app.disable('x-powered-by');
88
- app.use(agcidMiddleware, localOnly(port));
89
- app.use('/api/:id', ownAppOnly, proxy);
90
- app.use('/mcp/:id', proxy);
91
- app.use('/connector/:id', ownAppOnly, proxy);
92
- app.use('/files/:id', ownAppOnly, proxy);
93
- healthRoutes(app, deps, entries, info);
94
- app.use('/host', requireHostToken(hostToken));
95
- hostRoutes(app, deps, entries, info, events);
96
- appRoutes(app, entries);
97
- shellRoutes(app, { shell: info.shell, entries, events, user: deps.user });
98
- app.use(notFound);
99
- app.use(errorHandler(deps.log));
100
- return app;
101
- };
@@ -1 +0,0 @@
1
- export declare const clearRunLock: (lock: string, runDir: string) => Promise<void>;
@@ -1,15 +0,0 @@
1
- import { readFile, unlink } from 'node:fs/promises';
2
- const pidIn = (lock) => readFile(lock, 'utf8').then(Number, () => 0);
3
- // Linux: a child of this run folder has it in its env; a reused pid or a zombie does not.
4
- const childOf = async (pid, runDir) => {
5
- if (process.platform !== 'linux')
6
- return true;
7
- const env = await readFile(`/proc/${pid}/environ`, 'utf8').catch(() => '');
8
- return env.split('\0').includes(`AGENTAGE_RUN_DIR=${runDir}`);
9
- };
10
- // The daemon starts one child per id at a time: a lock not held by a child of this id is left over.
11
- export const clearRunLock = async (lock, runDir) => {
12
- const pid = await pidIn(lock);
13
- if (pid > 0 && !(await childOf(pid, runDir)))
14
- await unlink(lock).catch(() => undefined);
15
- };
@@ -1,2 +0,0 @@
1
- export declare const real: (path: string) => string;
2
- export declare const assertReach: (reads: string[], writes: string[], configDir: string, id: string) => void;
@@ -1,38 +0,0 @@
1
- import { realpathSync } from 'node:fs';
2
- import { isAbsolute, join, relative, sep } from 'node:path';
3
- import { fail } from '../../envelope/envelope.js';
4
- // A path is checked as given and modules load from the real path: a symlinked folder needs both.
5
- export const real = (path) => {
6
- try {
7
- return realpathSync(path);
8
- }
9
- catch {
10
- return path;
11
- }
12
- };
13
- // True when path is folder or inside it.
14
- const within = (path, folder) => {
15
- const rel = relative(folder, path);
16
- return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
17
- };
18
- // The tree folders the cli installs into: the shared 0.51 tree, or one tree per id@version.
19
- const ownTree = (grant, configDir, id) => {
20
- const [first, second, third] = relative(join(configDir, 'extensions'), grant).split(sep);
21
- if (first === 'trees')
22
- return !!second && !second.startsWith('.');
23
- const name = first === 'packages' && second === 'trees' ? third : undefined;
24
- return !!name && name.startsWith(`${id}@`) && name.length > id.length + 1;
25
- };
26
- // Inside the config dir only the extension's own tree holds no secret, row or other id's folder.
27
- const exposes = (grant, configDir, id) => within(configDir, grant) || (within(grant, configDir) && !ownTree(grant, configDir, id));
28
- const refused = (path, why) => fail('VALIDATION_ERROR', `seal: the folder ${path} ${why}`);
29
- // Node reads a * in a grant as a wildcard; a read grant on the config dir (or above it) shows daemon.json and secrets.json.
30
- export const assertReach = (reads, writes, configDir, id) => {
31
- const star = [...reads, ...writes].find((path) => path.includes('*'));
32
- if (star)
33
- throw refused(star, 'has a * that Node reads as a wildcard');
34
- const configs = [configDir, real(configDir)];
35
- const open = reads.find((grant) => [grant, real(grant)].some((path) => configs.some((config) => exposes(path, config, id))));
36
- if (open)
37
- throw refused(open, 'would expose the agentage config folder');
38
- };
@@ -1,20 +0,0 @@
1
- import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
- export type Seal = 'on' | 'off' | 'partial';
3
- export declare const spawnsGit: (pkg: ExtensionPackage) => boolean;
4
- export declare const sealOfEntry: (seal: Seal, pkg: ExtensionPackage | undefined) => Seal;
5
- export declare const sealOf: (version: string) => Seal;
6
- export declare const permissionFlag: (version: string) => boolean;
7
- export declare const sealOffReason: (version: string) => string;
8
- export declare const treeOf: (dir: string) => string;
9
- export declare const kitReadDirs: (main: string) => string[];
10
- interface SealAt {
11
- id: string;
12
- main: string;
13
- dir: string;
14
- configDir: string;
15
- runDir: string;
16
- dataDir: string;
17
- childProcess?: boolean;
18
- }
19
- export declare const sealFlags: (at: SealAt) => string[];
20
- export {};
@@ -1,93 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { dirname, join, parse, sep } from 'node:path';
4
- import {} from '../../manifest/manifest.schema.js';
5
- import { hasStore } from '../../manifest/parts.js';
6
- import { assertReach, real } from './seal-reach.js';
7
- // G6 (PD2): a git store spawns git for each operation; no other package gets a child process.
8
- export const spawnsGit = (pkg) => hasStore(pkg, 'git');
9
- export const sealOfEntry = (seal, pkg) => seal === 'on' && pkg && spawnsGit(pkg) ? 'partial' : seal;
10
- // C2: the permission model with the bypass fixes of D2; the same rule as e2e sealFloorMet.
11
- const SEAL_FLOOR = 'Node 22.22.2 or 24.14.1';
12
- const versionOf = (version) => version.split('.').map(Number);
13
- const atLeast = (version, major, minor, patch) => {
14
- const [a = 0, b = 0, c = 0] = versionOf(version);
15
- return a === major && (b > minor || (b === minor && c >= patch));
16
- };
17
- // An odd major has no known fix release: off; an even major above 24 is on.
18
- export const sealOf = (version) => {
19
- const [major = 0] = versionOf(version);
20
- if (major === 22)
21
- return atLeast(version, 22, 22, 2) ? 'on' : 'off';
22
- if (major === 24)
23
- return atLeast(version, 24, 14, 1) ? 'on' : 'off';
24
- return major > 24 && major % 2 === 0 ? 'on' : 'off';
25
- };
26
- // --permission is a stable flag from 22.13.0 and 23.5.0: below the floor it still limits, seal off.
27
- export const permissionFlag = (version) => {
28
- const [major = 0] = versionOf(version);
29
- return major >= 24 || atLeast(version, 22, 13, 0) || atLeast(version, 23, 5, 0);
30
- };
31
- export const sealOffReason = (version) => `seal off: ${SEAL_FLOOR} needed, this is Node ${version}`;
32
- const NODE_MODULES = `${sep}node_modules${sep}`;
33
- // The folder that holds the node_modules a path sits in (a tree of the cli); else the path itself.
34
- export const treeOf = (dir) => {
35
- const at = dir.lastIndexOf(NODE_MODULES);
36
- return at < 0 ? dir : dir.slice(0, at);
37
- };
38
- const hasWorkspaces = (dir) => {
39
- try {
40
- return 'workspaces' in JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
41
- }
42
- catch {
43
- return false;
44
- }
45
- };
46
- // The folders from start up, never above the user's home nor the root.
47
- const upward = (start) => {
48
- const found = [start];
49
- for (let dir = start; dir !== homedir() && dir !== parse(dir).root;)
50
- found.push((dir = dirname(dir)));
51
- return found;
52
- };
53
- // The nearest folder with a package.json; none: the folder of the file.
54
- const packageRoot = (file) => upward(dirname(file)).find((dir) => existsSync(join(dir, 'package.json'))) ?? dirname(file);
55
- const kitDeps = (pkgDir) => {
56
- try {
57
- const pkg = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'));
58
- return Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies });
59
- }
60
- catch {
61
- return [];
62
- }
63
- };
64
- // Node walks out of a kit nested under the cli to the node_modules npm hoisted a dependency to.
65
- const hoistedDirs = (inner, main) => {
66
- const walk = upward(dirname(inner)).map((dir) => join(dir, 'node_modules'));
67
- const found = kitDeps(packageRoot(main)).map((dep) => walk.find((dir) => existsSync(join(dir, dep, 'package.json'))));
68
- return [...new Set([inner, ...found.filter((dir) => dir !== undefined)])];
69
- };
70
- // Installed: the node_modules of the kit and its dependencies. A checkout: its package and workspace root.
71
- export const kitReadDirs = (main) => {
72
- const at = main.lastIndexOf(NODE_MODULES);
73
- if (at >= 0)
74
- return hoistedDirs(main.slice(0, at + NODE_MODULES.length - 1), main);
75
- const root = packageRoot(main);
76
- return [...new Set([root, upward(root).find(hasWorkspaces) ?? root])];
77
- };
78
- // C2: read kit, tree, run/{id}, data/{id}; write the last two; no worker, addon, WASI, sqlite; a child process for git only.
79
- export const sealFlags = (at) => {
80
- const { id, main, dir, configDir, runDir, dataDir } = at;
81
- const both = (paths) => [...new Set(paths.flatMap((path) => [path, real(path)]))];
82
- const writes = both([runDir, dataDir]);
83
- const kit = both([...kitReadDirs(main), treeOf(dir)]);
84
- assertReach(kit, writes, configDir, id);
85
- const reads = [...new Set([...kit, ...writes])];
86
- return [
87
- '--permission',
88
- '--no-experimental-sqlite',
89
- ...(at.childProcess ? ['--allow-child-process'] : []),
90
- ...reads.map((path) => `--allow-fs-read=${path}`),
91
- ...writes.map((path) => `--allow-fs-write=${path}`),
92
- ];
93
- };
@@ -1,9 +0,0 @@
1
- import { type RequestHandler } from 'express';
2
- export type ShellEvent = 'extensions' | 'app' | 'session';
3
- export interface ShellEvents {
4
- send(event: ShellEvent, data: unknown): void;
5
- stream: RequestHandler;
6
- }
7
- export declare const HEARTBEAT_MS = 25000;
8
- export declare const STALLED_WRITES = 32;
9
- export declare const shellEvents: (heartbeatMs?: number) => ShellEvents;
@@ -1,36 +0,0 @@
1
- import {} from 'express';
2
- // A comment line now and then, so an idle connection is not cut by a proxy or a browser.
3
- export const HEARTBEAT_MS = 25_000;
4
- // A tab that does not read: after this many writes in a row that the socket refused, the stream is dropped.
5
- export const STALLED_WRITES = 32;
6
- export const shellEvents = (heartbeatMs = HEARTBEAT_MS) => {
7
- const open = new Map();
8
- const write = (res, frame) => {
9
- const refused = res.write(frame) ? 0 : (open.get(res) ?? 0) + 1;
10
- if (refused < STALLED_WRITES)
11
- return void open.set(res, refused);
12
- open.delete(res);
13
- res.destroy();
14
- };
15
- const send = (event, data) => {
16
- const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
17
- for (const res of [...open.keys()])
18
- write(res, frame);
19
- };
20
- // GET /shell/events: server-sent events; the daemon's stop closes every stream.
21
- const stream = (req, res) => {
22
- res.writeHead(200, {
23
- 'content-type': 'text/event-stream',
24
- 'cache-control': 'no-store',
25
- connection: 'keep-alive',
26
- });
27
- res.write('retry: 1000\n\n');
28
- open.set(res, 0);
29
- const beat = setInterval(() => res.write(': beat\n\n'), heartbeatMs).unref();
30
- req.on('close', () => {
31
- clearInterval(beat);
32
- open.delete(res);
33
- });
34
- };
35
- return { send, stream };
36
- };
@@ -1,29 +0,0 @@
1
- import { type Express } from 'express';
2
- import { type CliUser } from './cli-user-watch.js';
3
- import { type Entries } from './entries.js';
4
- import { type ShellEvents } from './shell-events.js';
5
- export declare const kitShellDir: (base?: string) => string | undefined;
6
- export interface Shell {
7
- dir: string;
8
- package: string;
9
- version: string;
10
- }
11
- export declare const readShell: (dir: string, version?: string) => Promise<Shell>;
12
- type User = {
13
- id: string;
14
- email?: string;
15
- };
16
- type Session = {
17
- user: User | null;
18
- host: 'local';
19
- signIn?: string;
20
- };
21
- export declare const sessionOf: ({ sub, text }: CliUser) => Session;
22
- export declare const shellRoutes: (app: Express, { shell, entries, events, user }: ShellDeps) => void;
23
- export interface ShellDeps {
24
- shell?: Shell;
25
- entries: Entries;
26
- events: ShellEvents;
27
- user: CliUser;
28
- }
29
- export {};
@@ -1,68 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { readFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import express, {} from 'express';
6
- import { fail } from '../../envelope/envelope.js';
7
- import { hasApp } from './app-files.js';
8
- import {} from './cli-user-watch.js';
9
- import {} from './entries.js';
10
- import {} from './shell-events.js';
11
- import { LOCAL_SIGN_IN, signInPage } from './sign-in-page.js';
12
- // The shell the kit carries (dist/shell, written by the kit build); none when run from src.
13
- export const kitShellDir = (base = import.meta.url) => {
14
- const dir = fileURLToPath(new URL('../../shell', base));
15
- return existsSync(join(dir, 'package.json')) ? dir : undefined;
16
- };
17
- // `version` overrides the package's: the kit's own shell reports the kit that built it.
18
- export const readShell = async (dir, version) => {
19
- const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
20
- if (typeof pkg.version !== 'string' || typeof pkg.name !== 'string')
21
- throw new Error(`${dir}/package.json has no name or version: not a shell package`);
22
- return { dir, package: pkg.name, version: version ?? pkg.version };
23
- };
24
- const textOf = (value) => (typeof value === 'string' ? value : undefined);
25
- // K9: the user the children run as (issuer checked in cli-user.ts) and the email of its auth.json.
26
- // The fields of a cloud app host's session (id, email; no name), so both frames show one label.
27
- export const sessionOf = ({ sub, text }) => {
28
- if (sub === undefined)
29
- return { user: null, host: 'local', signIn: LOCAL_SIGN_IN };
30
- let shown = {};
31
- try {
32
- shown = JSON.parse(text ?? '').user ?? {};
33
- }
34
- catch {
35
- // the sub alone
36
- }
37
- const email = textOf(shown['email']);
38
- return { user: { id: sub, ...(email && { email }) }, host: 'local' };
39
- };
40
- // First path segments that are daemon routes: an unknown path under them stays a JSON 404.
41
- const OWN = new Set(['api', 'mcp', 'host', 'shell', 'app', 'health', '.well-known']);
42
- const page = (shell, entries) => async (req, res, next) => {
43
- const id = req.path.split('/')[1] ?? '';
44
- const read = req.method === 'GET' || req.method === 'HEAD';
45
- if (!read || OWN.has(id) || req.accepts(['html', 'json']) !== 'html')
46
- return next();
47
- const known = id === '' || (await hasApp(entries, id));
48
- res.status(known ? 200 : 404).set('Cache-Control', 'no-cache');
49
- // The daemon names this path: a dot folder above it (~/.agentage) is allowed.
50
- res.sendFile(join(shell.dir, 'dist', 'index.html'), { dotfiles: 'allow' }, (err) => err && next(err));
51
- };
52
- const notAFile = (req) => {
53
- throw fail('NOT_FOUND', `${req.originalUrl} is not a shell file`);
54
- };
55
- // S1.2.1: /, /{id}/* (the shell page, 404 for an id with no app), /shell/*, the session, the events,
56
- // and the page of the Sign in link.
57
- export const shellRoutes = (app, { shell, entries, events, user }) => {
58
- app.get('/shell/session', async (_req, res) => {
59
- res.set('Cache-Control', 'no-store').json(sessionOf(user));
60
- });
61
- app.get(LOCAL_SIGN_IN, signInPage);
62
- app.get('/shell/events', events.stream);
63
- if (!shell)
64
- return;
65
- const files = express.static(join(shell.dir, 'dist'), { index: false, dotfiles: 'deny' });
66
- app.use('/shell', files, notAFile);
67
- app.use(page(shell, entries));
68
- };
@@ -1,3 +0,0 @@
1
- import { type RequestHandler } from 'express';
2
- export declare const LOCAL_SIGN_IN = "/shell/sign-in";
3
- export declare const signInPage: RequestHandler;
@@ -1,30 +0,0 @@
1
- import {} from 'express';
2
- // The shell's Sign in link on the daemon: one fixed same-origin path, never a URL of another origin.
3
- export const LOCAL_SIGN_IN = '/shell/sign-in';
4
- const PAGE = `<!doctype html>
5
- <html lang="en">
6
- <meta charset="utf-8">
7
- <meta name="viewport" content="width=device-width, initial-scale=1">
8
- <title>Sign in - agentage</title>
9
- <style>
10
- :root { color-scheme: light dark; }
11
- body { font: 15px/1.5 system-ui, sans-serif; max-width: 32rem; margin: 15vh auto; padding: 0 16px; }
12
- code { font-size: 14px; padding: 2px 6px; border-radius: 4px; background: rgba(127, 127, 127, 0.18); }
13
- </style>
14
- <h1>Sign in</h1>
15
- <p>This dashboard runs on your machine. To sign in, run <code>agentage setup</code> in a terminal.</p>
16
- <p>The dashboard shows your account a few seconds after the sign-in.</p>
17
- <p><a href="/">Back to the dashboard</a></p>
18
- </html>
19
- `;
20
- // A browser cannot start the cli: the page says how to sign in. The desktop catches the link first.
21
- export const signInPage = (_req, res) => {
22
- res
23
- .status(200)
24
- .set({
25
- 'Content-Type': 'text/html; charset=utf-8',
26
- 'Cache-Control': 'no-store',
27
- 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'",
28
- })
29
- .send(PAGE);
30
- };
@@ -1,6 +0,0 @@
1
- import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
- export declare const assertSecrets: (pkg: ExtensionPackage, secrets: Record<string, string>) => void;
3
- export declare const needsSecret: (err: unknown) => boolean;
4
- export declare const healthy: (port: number, ms: number) => Promise<void>;
5
- export declare const maskedForms: (secrets: Record<string, string>) => string[];
6
- export declare const redact: (text: string, secrets: Record<string, string>) => string;
@@ -1,29 +0,0 @@
1
- import {} from '../../manifest/manifest.schema.js';
2
- import { hostParts, mountedIn } from '../../manifest/parts.js';
3
- const NEEDS_SECRET = 'NEEDS_SECRET';
4
- // C6: a declared secret of a server part with no value; the daemon checks it before the fork.
5
- export const assertSecrets = (pkg, secrets) => {
6
- const names = new Set(hostParts(pkg).flatMap((part) => mountedIn(pkg, part)));
7
- const missing = [...names].find((name) => !secrets[name]);
8
- if (missing)
9
- throw Object.assign(new Error(`needs secret ${missing}`), { code: NEEDS_SECRET });
10
- };
11
- export const needsSecret = (err) => err?.code === NEEDS_SECRET;
12
- // Healthy before it gets the route: the child's own /health answers 200.
13
- export const healthy = async (port, ms) => {
14
- const signal = AbortSignal.timeout(ms);
15
- const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
16
- if (err.name === 'TimeoutError')
17
- throw new Error(`health did not answer in ${ms} ms`);
18
- const cause = err.cause?.code ?? err.message;
19
- throw new Error(`health could not be reached (${cause})`);
20
- });
21
- if (res.status !== 200)
22
- throw new Error(`health answered ${res.status}`);
23
- };
24
- // Each value raw and as it shows inside a JSON log row (quotes, backslashes escaped).
25
- export const maskedForms = (secrets) => [...new Set(Object.values(secrets).flatMap((v) => [v, JSON.stringify(v).slice(1, -1)]))]
26
- .filter((value) => value.length >= 4)
27
- .sort((a, b) => b.length - a.length);
28
- // A secret value this child was given never reaches error, /health, the list or the log.
29
- export const redact = (text, secrets) => maskedForms(secrets).reduce((out, value) => out.split(value).join('***'), text);
@@ -1,10 +0,0 @@
1
- import { type Child, type Launch } from './child.js';
2
- export interface Stopping {
3
- signal: AbortSignal;
4
- launching: Set<Promise<unknown>>;
5
- children: Set<Child>;
6
- }
7
- export declare const stoppingOf: (signal: AbortSignal) => Stopping;
8
- export declare const stopsNow: () => import("../../envelope/envelope.js").Failure;
9
- export declare const launchUnlessStopping: (stopping: Stopping, launch: Launch) => Launch;
10
- export declare const stopAll: (stopping: Stopping) => Promise<void>;
@@ -1,28 +0,0 @@
1
- import { fail } from '../../envelope/envelope.js';
2
- import {} from './child.js';
3
- export const stoppingOf = (signal) => ({
4
- signal,
5
- launching: new Set(),
6
- children: new Set(),
7
- });
8
- export const stopsNow = () => fail('UNAVAILABLE', 'the daemon stops', { retryAfter: 5 });
9
- const started = async (stopping, launch) => {
10
- if (stopping.signal.aborted)
11
- throw stopsNow();
12
- const child = await launch();
13
- stopping.children.add(child);
14
- void child.exited.then(() => stopping.children.delete(child));
15
- return child;
16
- };
17
- // No child outlives stop(): none starts once it began; stopAll waits for the ones in flight.
18
- export const launchUnlessStopping = (stopping, launch) => (spec) => {
19
- const run = started(stopping, () => launch(spec));
20
- stopping.launching.add(run);
21
- void run.catch(() => undefined).finally(() => stopping.launching.delete(run));
22
- return run;
23
- };
24
- // After the drain of each route: a child still starting or swapping is stopped too.
25
- export const stopAll = async (stopping) => {
26
- await Promise.allSettled([...stopping.launching]);
27
- await Promise.all([...stopping.children].map((child) => child.stop()));
28
- };