@agentage/extension 0.20.1 → 0.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/auth/part-auth.js +4 -5
  2. package/dist/context/context.d.ts +0 -1
  3. package/dist/host/child-env.d.ts +11 -0
  4. package/dist/host/child-env.js +12 -0
  5. package/dist/host/{daemon/guard.js → guard.js} +1 -1
  6. package/dist/host/host-extension.js +1 -1
  7. package/dist/host/host-main.d.ts +1 -0
  8. package/dist/host/host-main.js +3 -0
  9. package/dist/host/index.d.ts +1 -5
  10. package/dist/host/index.js +1 -5
  11. package/dist/host/kit-shell.d.ts +1 -0
  12. package/dist/host/kit-shell.js +2 -0
  13. package/dist/host/serve-host.js +1 -1
  14. package/dist/internal/index.d.ts +29 -0
  15. package/dist/internal/index.js +30 -0
  16. package/dist/runtime/part-mounts.d.ts +0 -1
  17. package/dist/runtime/part-mounts.js +1 -1
  18. package/dist/runtime/run-part.js +0 -2
  19. package/dist/server/app.d.ts +0 -1
  20. package/dist/server/app.js +4 -5
  21. package/dist/tool/check.js +3 -0
  22. package/dist/tool/recipe.js +2 -2
  23. package/dist/tool/up/gateway.js +0 -3
  24. package/package.json +5 -1
  25. package/dist/host/daemon/add.d.ts +0 -11
  26. package/dist/host/daemon/add.js +0 -93
  27. package/dist/host/daemon/app-files.d.ts +0 -8
  28. package/dist/host/daemon/app-files.js +0 -34
  29. package/dist/host/daemon/app-header.d.ts +0 -2
  30. package/dist/host/daemon/app-header.js +0 -12
  31. package/dist/host/daemon/app-reload.d.ts +0 -10
  32. package/dist/host/daemon/app-reload.js +0 -18
  33. package/dist/host/daemon/child-files.d.ts +0 -20
  34. package/dist/host/daemon/child-files.js +0 -53
  35. package/dist/host/daemon/child.d.ts +0 -30
  36. package/dist/host/daemon/child.js +0 -126
  37. package/dist/host/daemon/cli-user-watch.d.ts +0 -9
  38. package/dist/host/daemon/cli-user-watch.js +0 -47
  39. package/dist/host/daemon/cli-user.d.ts +0 -2
  40. package/dist/host/daemon/cli-user.js +0 -42
  41. package/dist/host/daemon/daemon-files.d.ts +0 -20
  42. package/dist/host/daemon/daemon-files.js +0 -46
  43. package/dist/host/daemon/daemon-owner.d.ts +0 -1
  44. package/dist/host/daemon/daemon-owner.js +0 -32
  45. package/dist/host/daemon/daemon.d.ts +0 -19
  46. package/dist/host/daemon/daemon.js +0 -137
  47. package/dist/host/daemon/entries.d.ts +0 -21
  48. package/dist/host/daemon/entries.js +0 -24
  49. package/dist/host/daemon/gate.d.ts +0 -3
  50. package/dist/host/daemon/gate.js +0 -19
  51. package/dist/host/daemon/health-routes.d.ts +0 -18
  52. package/dist/host/daemon/health-routes.js +0 -75
  53. package/dist/host/daemon/host-token.d.ts +0 -6
  54. package/dist/host/daemon/host-token.js +0 -28
  55. package/dist/host/daemon/installation.d.ts +0 -35
  56. package/dist/host/daemon/installation.js +0 -90
  57. package/dist/host/daemon/installer-call.d.ts +0 -21
  58. package/dist/host/daemon/installer-call.js +0 -48
  59. package/dist/host/daemon/json-file.d.ts +0 -6
  60. package/dist/host/daemon/json-file.js +0 -90
  61. package/dist/host/daemon/lane.d.ts +0 -9
  62. package/dist/host/daemon/lane.js +0 -24
  63. package/dist/host/daemon/last-words.d.ts +0 -2
  64. package/dist/host/daemon/last-words.js +0 -28
  65. package/dist/host/daemon/limits.d.ts +0 -16
  66. package/dist/host/daemon/limits.js +0 -31
  67. package/dist/host/daemon/ops.d.ts +0 -12
  68. package/dist/host/daemon/ops.js +0 -94
  69. package/dist/host/daemon/patch-values.d.ts +0 -6
  70. package/dist/host/daemon/patch-values.js +0 -39
  71. package/dist/host/daemon/pending.d.ts +0 -15
  72. package/dist/host/daemon/pending.js +0 -18
  73. package/dist/host/daemon/proxy.d.ts +0 -11
  74. package/dist/host/daemon/proxy.js +0 -106
  75. package/dist/host/daemon/queue.d.ts +0 -3
  76. package/dist/host/daemon/queue.js +0 -27
  77. package/dist/host/daemon/redact-stream.d.ts +0 -4
  78. package/dist/host/daemon/redact-stream.js +0 -24
  79. package/dist/host/daemon/reload-marker.d.ts +0 -8
  80. package/dist/host/daemon/reload-marker.js +0 -57
  81. package/dist/host/daemon/reload.d.ts +0 -10
  82. package/dist/host/daemon/reload.js +0 -72
  83. package/dist/host/daemon/restart.d.ts +0 -14
  84. package/dist/host/daemon/restart.js +0 -59
  85. package/dist/host/daemon/routes.d.ts +0 -6
  86. package/dist/host/daemon/routes.js +0 -101
  87. package/dist/host/daemon/run-lock.d.ts +0 -1
  88. package/dist/host/daemon/run-lock.js +0 -15
  89. package/dist/host/daemon/seal-reach.d.ts +0 -2
  90. package/dist/host/daemon/seal-reach.js +0 -38
  91. package/dist/host/daemon/seal.d.ts +0 -20
  92. package/dist/host/daemon/seal.js +0 -93
  93. package/dist/host/daemon/shell-events.d.ts +0 -9
  94. package/dist/host/daemon/shell-events.js +0 -36
  95. package/dist/host/daemon/shell-routes.d.ts +0 -29
  96. package/dist/host/daemon/shell-routes.js +0 -68
  97. package/dist/host/daemon/sign-in-page.d.ts +0 -3
  98. package/dist/host/daemon/sign-in-page.js +0 -30
  99. package/dist/host/daemon/start-checks.d.ts +0 -6
  100. package/dist/host/daemon/start-checks.js +0 -29
  101. package/dist/host/daemon/stopping.d.ts +0 -10
  102. package/dist/host/daemon/stopping.js +0 -28
  103. package/dist/host/daemon/supervisor.d.ts +0 -59
  104. package/dist/host/daemon/supervisor.js +0 -107
  105. package/dist/host/daemon/write-all.d.ts +0 -8
  106. package/dist/host/daemon/write-all.js +0 -45
  107. package/dist/shell/dist/index.html +0 -49
  108. package/dist/shell/dist/shell.css +0 -2
  109. package/dist/shell/dist/shell.js +0 -69
  110. package/dist/shell/dist/vendor/app.js +0 -1
  111. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +0 -14
  112. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +0 -14
  113. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +0 -14
  114. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +0 -1
  115. package/dist/shell/dist/vendor/jsx-runtime.js +0 -1
  116. package/dist/shell/dist/vendor/react-dom-client.js +0 -33
  117. package/dist/shell/dist/vendor/react-dom.js +0 -1
  118. package/dist/shell/dist/vendor/react.js +0 -1
  119. package/dist/shell/package.json +0 -5
  120. /package/dist/host/{daemon/guard.d.ts → guard.d.ts} +0 -0
@@ -1,106 +0,0 @@
1
- import { request, } from 'node:http';
2
- import { setTimeout as sleep } from 'node:timers/promises';
3
- import {} from 'express';
4
- import { fail } from '../../envelope/envelope.js';
5
- import { carriesHostToken } from './host-token.js';
6
- import { enter } from './lane.js';
7
- import {} from './entries.js';
8
- import {} from './limits.js';
9
- import { stopsNow } from './stopping.js';
10
- import {} from './supervisor.js';
11
- // With no child: the daemon stops, a change still holds it (state still running), or its state.
12
- const noLane = (entry, stopping) => {
13
- if (stopping?.signal.aborted)
14
- return stopsNow();
15
- const now = entry.state === 'running' ? 'changing' : entry.state;
16
- return fail('UNAVAILABLE', `${entry.id} is ${now}: try again`, { retryAfter: 5 });
17
- };
18
- // 404 not installed or disabled (chosen, not to retry); 503 starting, failed, or held past gateMs.
19
- const laneFor = async (entries, id, limits) => {
20
- const entry = entries.get(id);
21
- if (!entry)
22
- throw fail('NOT_FOUND', `${id} is not installed`);
23
- if (entry.state === 'disabled')
24
- throw fail('NOT_FOUND', `${id} is disabled`);
25
- if (entry.gate)
26
- await Promise.race([entry.gate, sleep(limits.gateMs, undefined, { ref: false })]);
27
- const lane = entry.lane;
28
- if (!lane)
29
- throw noLane(entry, limits.stopping);
30
- // Counted in the same tick it is read: a swap cannot stop this child before the request is open.
31
- return { lane, leave: enter(lane) };
32
- };
33
- const HOP = [
34
- 'connection',
35
- 'keep-alive',
36
- 'proxy-authenticate',
37
- 'proxy-authorization',
38
- 'te',
39
- 'trailer',
40
- 'transfer-encoding',
41
- 'upgrade',
42
- ];
43
- // RFC 9110 7.6.1: hop-by-hop headers, and those the Connection header names, stay on their hop.
44
- export const endToEnd = (headers) => {
45
- const named = String(headers['connection'] ?? '')
46
- .toLowerCase()
47
- .split(',');
48
- const drop = new Set([...HOP, ...named.map((h) => h.trim())]);
49
- return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.has(key)));
50
- };
51
- // No answer headers in answerMs: 504 TIMEOUT; the child may still apply the call.
52
- const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did not answer in ${ms} ms`), {
53
- code: 'TIMEOUT',
54
- status: 504,
55
- retryAfter: undefined,
56
- });
57
- // D11: the host token is for the daemon; a child never sees it, also when a client sends it here.
58
- const forChild = (req, hostToken) => {
59
- const headers = endToEnd(req.headers);
60
- if (hostToken && carriesHostToken(req.headers, hostToken))
61
- delete headers['authorization'];
62
- return headers;
63
- };
64
- const requestTo = (req, lane, hostToken) => {
65
- const { method, originalUrl: path } = req;
66
- const headers = forChild(req, hostToken);
67
- const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
68
- return request(options);
69
- };
70
- // The child's answer as it streams; an error before its headers is the envelope (504 when late).
71
- const relay = (upstream, res, next, ms) => {
72
- let late = false;
73
- const timer = setTimeout(() => ((late = true), upstream.destroy()), ms);
74
- upstream.on('response', (up) => {
75
- clearTimeout(timer);
76
- res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
77
- // A child gone in the middle of its body: the answer is cut, not left open.
78
- up.once('close', () => void (up.complete || res.destroy()));
79
- up.pipe(res);
80
- });
81
- upstream.on('error', () => {
82
- if (res.headersSent)
83
- return void res.destroy();
84
- next(late ? noAnswer(ms) : fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
85
- });
86
- return () => clearTimeout(timer);
87
- };
88
- const forward = (req, res, next, { to, ms, hostToken }) => {
89
- const { lane, leave } = to;
90
- const upstream = requestTo(req, lane, hostToken);
91
- const stop = relay(upstream, res, next, ms);
92
- upstream.on('error', leave);
93
- // A client that went away aborts the request to the child too.
94
- res.on('close', () => {
95
- stop();
96
- if (!res.writableFinished)
97
- upstream.destroy();
98
- leave();
99
- });
100
- req.pipe(upstream);
101
- };
102
- // ANY /api/{id}/* and /mcp/{id} (C1): the same lane, the same refusals (404 unknown, 503 not running).
103
- export const proxyTo = (entries, limits, hostToken) => async (req, res, next) => {
104
- const to = await laneFor(entries, String(req.params['id']), limits);
105
- forward(req, res, next, { to, ms: limits.answerMs, hostToken });
106
- };
@@ -1,3 +0,0 @@
1
- export type Queue = <T>(fn: () => Promise<T>) => Promise<T>;
2
- export declare const serialQueue: () => Queue;
3
- export declare const waitAtMost: <T>(queue: Queue, ms: number, fn: () => Promise<T>) => Promise<T>;
@@ -1,27 +0,0 @@
1
- import { fail } from '../../envelope/envelope.js';
2
- export const serialQueue = () => {
3
- let chain = Promise.resolve();
4
- return (fn) => {
5
- const run = chain.then(fn, fn);
6
- chain = run.catch(() => undefined);
7
- return run;
8
- };
9
- };
10
- // A change that waited ms for the ones before it (the boot too) is 503 and never runs.
11
- export const waitAtMost = (queue, ms, fn) => {
12
- let gaveUp = false;
13
- let timer;
14
- const late = new Promise((_resolve, reject) => {
15
- timer = setTimeout(() => {
16
- gaveUp = true;
17
- reject(fail('UNAVAILABLE', `other changes ran for ${ms} ms: try again`, { retryAfter: 5 }));
18
- }, ms);
19
- });
20
- const run = queue(async () => {
21
- clearTimeout(timer);
22
- if (gaveUp)
23
- return undefined;
24
- return fn();
25
- });
26
- return Promise.race([run, late]);
27
- };
@@ -1,4 +0,0 @@
1
- import { type Readable, type Writable } from 'node:stream';
2
- export declare const PENDING_MAX: number;
3
- export declare const redactedLines: (write: (text: string) => void, secrets: Record<string, string>) => (chunk?: string) => void;
4
- export declare const pipeRedacted: (from: Readable | null, to: Writable, secrets: Record<string, string>) => void;
@@ -1,24 +0,0 @@
1
- import {} from 'node:stream';
2
- import { maskedForms, redact } from './start-checks.js';
3
- // Past this, a line with no newline is written up to a tail that could hold a split secret.
4
- export const PENDING_MAX = 64 * 1024;
5
- // By line, so a value split over two chunks is masked too; a call with no chunk flushes the rest.
6
- export const redactedLines = (write, secrets) => {
7
- const keep = Math.max(0, (maskedForms(secrets)[0]?.length ?? 1) - 1);
8
- let rest = '';
9
- return (chunk) => {
10
- const lines = (rest + (chunk ?? '\n')).split('\n');
11
- rest = lines.pop() ?? '';
12
- const cut = rest.length > PENDING_MAX ? rest.length - keep : 0;
13
- const out = `${lines.join('\n')}${lines.length && chunk !== undefined ? '\n' : ''}`;
14
- if (out || cut)
15
- write(redact(out + rest.slice(0, cut), secrets));
16
- rest = rest.slice(cut);
17
- };
18
- };
19
- // A child stream to the daemon's own, masked; its rest is written at the end.
20
- export const pipeRedacted = (from, to, secrets) => {
21
- const out = redactedLines((text) => to.write(text), secrets);
22
- from?.on('data', (chunk) => out(chunk.toString()));
23
- from?.once('end', () => out());
24
- };
@@ -1,8 +0,0 @@
1
- import { type Log } from '../../log/log.js';
2
- import { type Entry } from './supervisor.js';
3
- export declare const markReload: (configDir: string, id: string, dir: string) => Promise<void>;
4
- export declare const unmarkReload: (configDir: string, id: string) => Promise<void>;
5
- export declare const swapIn: (dir: string) => Promise<boolean>;
6
- export declare const swapBack: (dir: string) => Promise<void>;
7
- export declare const confirmReload: (configDir: string, id: string, dir: string) => Promise<void>;
8
- export declare const repairReload: (configDir: string, entry: Entry, log: Log) => Promise<void>;
@@ -1,57 +0,0 @@
1
- import { existsSync } from 'node:fs';
2
- import { cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import {} from '../../log/log.js';
5
- import { runDirOf } from './daemon-files.js';
6
- import {} from './supervisor.js';
7
- // D14 (revised): the child runs dist/; dist.next/ is the watcher's tree and stays; dist.prev/ is the last good.
8
- const DIST = 'dist';
9
- const NEXT = 'dist.next';
10
- const PREV = 'dist.prev';
11
- const markerOf = (configDir, id) => join(runDirOf(configDir, id), 'reload.json');
12
- const gone = (path) => rm(path, { recursive: true, force: true });
13
- // Written once a stale dist.prev is gone: marker and dist.prev together mean a swap not confirmed.
14
- export const markReload = async (configDir, id, dir) => {
15
- await gone(join(dir, PREV));
16
- const marker = markerOf(configDir, id);
17
- await mkdir(join(marker, '..'), { recursive: true });
18
- await writeFile(marker, JSON.stringify({ id, dir, complete: false, at: new Date().toISOString() }));
19
- };
20
- export const unmarkReload = (configDir, id) => gone(markerOf(configDir, id));
21
- // dist to dist.prev, a copy of dist.next to dist; false when there is no new build (a plain restart).
22
- export const swapIn = async (dir) => {
23
- if (!existsSync(join(dir, NEXT)))
24
- return false;
25
- if (existsSync(join(dir, DIST)))
26
- await rename(join(dir, DIST), join(dir, PREV));
27
- await cp(join(dir, NEXT), join(dir, DIST), { recursive: true });
28
- return true;
29
- };
30
- // The copied build goes, the last good one comes back; with no dist.prev, dist is never touched.
31
- export const swapBack = async (dir) => {
32
- if (!existsSync(join(dir, PREV)))
33
- return;
34
- await gone(join(dir, DIST));
35
- await rename(join(dir, PREV), join(dir, DIST));
36
- };
37
- // The new build is healthy: the marker first, then the old build.
38
- export const confirmReload = async (configDir, id, dir) => {
39
- await unmarkReload(configDir, id);
40
- await gone(join(dir, PREV));
41
- };
42
- const markedDir = async (configDir, id) => {
43
- const text = await readFile(markerOf(configDir, id), 'utf8');
44
- return JSON.parse(text).dir;
45
- };
46
- // At boot: a marker of this row's folder with a dist.prev is a cut reload, put back to the last good build.
47
- export const repairReload = async (configDir, entry, log) => {
48
- const dir = entry.install.source;
49
- if (!dir || !existsSync(markerOf(configDir, entry.id)))
50
- return;
51
- const ours = (await markedDir(configDir, entry.id).catch(() => undefined)) === dir;
52
- if (ours && existsSync(join(dir, PREV))) {
53
- await swapBack(dir);
54
- log.warn('a cut reload was put back to the last good build', { id: entry.id });
55
- }
56
- await unmarkReload(configDir, entry.id);
57
- };
@@ -1,10 +0,0 @@
1
- import { type Entries } from './entries.js';
2
- import { type SupervisorDeps } from './supervisor.js';
3
- export declare const reloadExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
4
- refused?: string | undefined;
5
- reloaded: boolean;
6
- pid?: number | undefined;
7
- id: string;
8
- version: string;
9
- state: import("./supervisor.js").State;
10
- }>;
@@ -1,72 +0,0 @@
1
- import { z } from 'zod';
2
- import { fail } from '../../envelope/envelope.js';
3
- import { parse } from '../../envelope/parse.js';
4
- import { entryOf } from './entries.js';
5
- import { confirmReload, markReload, swapBack, swapIn, unmarkReload } from './reload-marker.js';
6
- import { halt, hold } from './gate.js';
7
- import { startEntry } from './supervisor.js';
8
- const ReloadSchema = z.strictObject({});
9
- // Only a linked working copy has a build to reload; a disabled one stays stopped.
10
- const folderOf = (entry) => {
11
- const dir = entry.install.source;
12
- if (!dir)
13
- throw fail('VALIDATION_ERROR', `${entry.id} is not a folder: only a linked folder reloads`);
14
- if (entry.install.enabled === false)
15
- throw fail('CONFLICT', `${entry.id} is disabled: enable it first`);
16
- return dir;
17
- };
18
- const answer = (entry, refused) => ({
19
- id: entry.id,
20
- version: entry.version,
21
- state: entry.state,
22
- ...(entry.lane && { pid: entry.lane.child.pid }),
23
- reloaded: refused === undefined,
24
- ...(refused !== undefined && { refused }),
25
- });
26
- // Not healthy: the copied build goes, the last good build starts again.
27
- const restoreLast = async (deps, entry, dir, swapped) => {
28
- if (swapped)
29
- await swapBack(dir);
30
- await unmarkReload(deps.configDir, entry.id);
31
- if (swapped)
32
- await startEntry(deps, entry);
33
- };
34
- // The new child runs: what is left to clean is best-effort, never a second start.
35
- const settle = async (deps, entry, dir) => {
36
- await confirmReload(deps.configDir, entry.id, dir).catch((err) => deps.log.warn('a reload left dist.prev or its marker', { id: entry.id, reason: err.message }));
37
- return answer(entry);
38
- };
39
- const tryNew = async (deps, entry, dir) => {
40
- await markReload(deps.configDir, entry.id, dir);
41
- const swapped = await swapIn(dir);
42
- const err = await startEntry(deps, entry, true);
43
- if (!err)
44
- return settle(deps, entry, dir);
45
- await restoreLast(deps, entry, dir, swapped);
46
- return answer(entry, err.message.split('\n')[0]);
47
- };
48
- // A file step failed (EPERM, EBUSY): the last good build runs again, the answer says why.
49
- const fileFailed = async (deps, entry, dir, err) => {
50
- await swapBack(dir).catch((again) => deps.log.warn('a reload could not put the last good build back', { reason: again.message }));
51
- await unmarkReload(deps.configDir, entry.id).catch(() => undefined);
52
- await startEntry(deps, entry);
53
- return answer(entry, err.message.split('\n')[0]);
54
- };
55
- // D14: stop and wait for the exit (one writer on the store), swap the builds, start, wait healthy.
56
- const reloadIn = async (deps, entry, dir) => {
57
- await halt(entry, deps.drainMs);
58
- return tryNew(deps, entry, dir).catch((err) => fileFailed(deps, entry, dir, err));
59
- };
60
- // POST /host/extensions/{id}/reload, body {}: requests wait at the gate and go to the new child.
61
- export const reloadExtension = async (deps, entries, id, body) => {
62
- parse(ReloadSchema, body ?? {}, 'Invalid body');
63
- const entry = entryOf(entries, id);
64
- const dir = folderOf(entry);
65
- const release = hold(entry);
66
- try {
67
- return await reloadIn(deps, entry, dir);
68
- }
69
- finally {
70
- release();
71
- }
72
- };
@@ -1,14 +0,0 @@
1
- import { type Exit } from './child.js';
2
- import { type Lane } from './lane.js';
3
- import { type Entry, type SupervisorDeps } from './supervisor.js';
4
- export interface Retry {
5
- timer: NodeJS.Timeout;
6
- }
7
- type Again = () => Promise<void>;
8
- export declare const restartsOf: (entry: Entry) => number;
9
- export declare const cancelRestart: (entry: Entry) => void;
10
- export declare const resetRestarts: (entry: Entry) => void;
11
- export declare const healthyFor: (deps: SupervisorDeps, entry: Entry, lane: Lane) => void;
12
- export declare const reasonOf: (how: Exit) => string;
13
- export declare const crashed: (deps: SupervisorDeps, entry: Entry, why: string, again: Again) => void;
14
- export {};
@@ -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 {};