@agentage/extension 0.13.0 → 0.14.0

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 (93) hide show
  1. package/dist/discovery/discovery.d.ts +1 -0
  2. package/dist/discovery/discovery.schema.d.ts +2 -0
  3. package/dist/discovery/discovery.schema.js +22 -10
  4. package/dist/host/daemon/add.d.ts +9 -0
  5. package/dist/host/daemon/add.js +63 -0
  6. package/dist/host/daemon/child.d.ts +5 -3
  7. package/dist/host/daemon/child.js +21 -13
  8. package/dist/host/daemon/daemon-files.d.ts +3 -5
  9. package/dist/host/daemon/daemon-files.js +15 -11
  10. package/dist/host/daemon/daemon-owner.d.ts +1 -0
  11. package/dist/host/daemon/daemon-owner.js +32 -0
  12. package/dist/host/daemon/daemon.d.ts +2 -3
  13. package/dist/host/daemon/daemon.js +53 -31
  14. package/dist/host/daemon/entries.d.ts +21 -0
  15. package/dist/host/daemon/entries.js +24 -0
  16. package/dist/host/daemon/guard.d.ts +1 -1
  17. package/dist/host/daemon/guard.js +4 -3
  18. package/dist/host/daemon/installation.d.ts +17 -4
  19. package/dist/host/daemon/installation.js +52 -8
  20. package/dist/host/daemon/installer-call.d.ts +16 -2
  21. package/dist/host/daemon/installer-call.js +33 -7
  22. package/dist/host/daemon/json-file.d.ts +3 -2
  23. package/dist/host/daemon/json-file.js +21 -10
  24. package/dist/host/daemon/lane.d.ts +1 -3
  25. package/dist/host/daemon/lane.js +4 -9
  26. package/dist/host/daemon/limits.d.ts +11 -0
  27. package/dist/host/daemon/limits.js +22 -0
  28. package/dist/host/daemon/ops.d.ts +2 -26
  29. package/dist/host/daemon/ops.js +43 -103
  30. package/dist/host/daemon/patch-values.d.ts +6 -0
  31. package/dist/host/daemon/patch-values.js +39 -0
  32. package/dist/host/daemon/pending.d.ts +15 -0
  33. package/dist/host/daemon/pending.js +18 -0
  34. package/dist/host/daemon/proxy.d.ts +3 -2
  35. package/dist/host/daemon/proxy.js +46 -24
  36. package/dist/host/daemon/queue.d.ts +1 -0
  37. package/dist/host/daemon/queue.js +19 -0
  38. package/dist/host/daemon/routes.d.ts +5 -3
  39. package/dist/host/daemon/routes.js +67 -17
  40. package/dist/host/daemon/stopping.d.ts +10 -0
  41. package/dist/host/daemon/stopping.js +28 -0
  42. package/dist/host/daemon/supervisor.d.ts +13 -11
  43. package/dist/host/daemon/supervisor.js +17 -18
  44. package/dist/host/daemon/write-all.d.ts +8 -0
  45. package/dist/host/daemon/write-all.js +45 -0
  46. package/dist/host/data-lock.d.ts +1 -0
  47. package/dist/host/data-lock.js +63 -23
  48. package/dist/host/host-env.d.ts +2 -1
  49. package/dist/host/host-env.js +8 -2
  50. package/dist/host/host-extension.d.ts +4 -0
  51. package/dist/host/host-extension.js +11 -6
  52. package/dist/host/host-store.d.ts +8 -1
  53. package/dist/host/host-store.js +24 -10
  54. package/dist/host/index.d.ts +4 -0
  55. package/dist/host/index.js +4 -0
  56. package/dist/host/serve-host.d.ts +2 -1
  57. package/dist/host/serve-host.js +12 -9
  58. package/dist/server/app.d.ts +2 -1
  59. package/dist/server/app.js +1 -1
  60. package/dist/server/serve.d.ts +3 -0
  61. package/dist/server/serve.js +9 -4
  62. package/dist/tool/build.d.ts +3 -0
  63. package/dist/tool/build.js +42 -27
  64. package/dist/tool/capabilities.d.ts +1 -0
  65. package/dist/tool/capabilities.js +8 -0
  66. package/dist/tool/container-parts.d.ts +7 -0
  67. package/dist/tool/container-parts.js +10 -0
  68. package/dist/tool/container-recipe.d.ts +4 -0
  69. package/dist/tool/container-recipe.js +55 -0
  70. package/dist/tool/container-stage.d.ts +3 -0
  71. package/dist/tool/container-stage.js +51 -0
  72. package/dist/tool/container.d.ts +73 -0
  73. package/dist/tool/container.js +28 -0
  74. package/dist/tool/docker.d.ts +5 -0
  75. package/dist/tool/docker.js +15 -0
  76. package/dist/tool/format.js +12 -5
  77. package/dist/tool/index.d.ts +2 -0
  78. package/dist/tool/index.js +2 -0
  79. package/dist/tool/kit-version.d.ts +1 -0
  80. package/dist/tool/kit-version.js +16 -2
  81. package/dist/tool/labels.d.ts +1 -1
  82. package/dist/tool/labels.js +4 -2
  83. package/dist/tool/main.js +10 -1
  84. package/dist/tool/stage.d.ts +1 -0
  85. package/dist/tool/stage.js +1 -1
  86. package/dist/tool/up/local-record.d.ts +1 -0
  87. package/package.json +1 -1
  88. package/schemas/extension-discovery.schema.json +8 -1
  89. package/schemas/extension-record.schema.json +8 -1
  90. package/dist/host/daemon/secret-names.d.ts +0 -1
  91. package/dist/host/daemon/secret-names.js +0 -14
  92. package/dist/host/daemon/setting-values.d.ts +0 -1
  93. package/dist/host/daemon/setting-values.js +0 -26
@@ -1,10 +1,10 @@
1
- import { request } from 'node:http';
1
+ import { request, } from 'node:http';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
2
3
  import {} from 'express';
3
4
  import { fail } from '../../envelope/envelope.js';
4
5
  import { enter } from './lane.js';
5
- import {} from './ops.js';
6
- import { GATE_MS } from './supervisor.js';
7
- const waited = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
6
+ import {} from './entries.js';
7
+ import {} from './limits.js';
8
8
  // 404 not installed or disabled (chosen, not to retry); 503 starting, failed, or held past gateMs.
9
9
  const laneFor = async (entries, id, gateMs) => {
10
10
  const entry = entries.get(id);
@@ -13,10 +13,12 @@ const laneFor = async (entries, id, gateMs) => {
13
13
  if (entry.state === 'disabled')
14
14
  throw fail('NOT_FOUND', `${id} is disabled`);
15
15
  if (entry.gate)
16
- await Promise.race([entry.gate, waited(gateMs)]);
17
- if (!entry.lane)
16
+ await Promise.race([entry.gate, sleep(gateMs, undefined, { ref: false })]);
17
+ const lane = entry.lane;
18
+ if (!lane)
18
19
  throw fail('UNAVAILABLE', `${id} is ${entry.state}`, { retryAfter: 5 });
19
- return entry.lane;
20
+ // Counted in the same tick it is read: a swap cannot stop this child before the request is open.
21
+ return { lane, leave: enter(lane) };
20
22
  };
21
23
  const HOP = [
22
24
  'connection',
@@ -36,32 +38,52 @@ export const endToEnd = (headers) => {
36
38
  const drop = new Set([...HOP, ...named.map((h) => h.trim())]);
37
39
  return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.has(key)));
38
40
  };
39
- const answer = (res) => (up) => {
40
- res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
41
- up.pipe(res);
42
- };
43
- // Streams the request to the child as it came (path and query kept), no pooled connection.
44
- const forward = (req, res, next, lane) => {
45
- const leave = enter(lane);
41
+ // No answer headers in answerMs: 504 TIMEOUT; the child may still apply the call.
42
+ const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did not answer in ${ms} ms`), {
43
+ code: 'TIMEOUT',
44
+ status: 504,
45
+ retryAfter: undefined,
46
+ });
47
+ const requestTo = (req, lane) => {
46
48
  const { method, originalUrl: path } = req;
47
49
  const headers = endToEnd(req.headers);
48
50
  const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
49
- const upstream = request(options, answer(res));
51
+ return request(options);
52
+ };
53
+ // The child's answer as it streams; an error before its headers is the envelope (504 when late).
54
+ const relay = (upstream, res, next, ms) => {
55
+ let late = false;
56
+ const timer = setTimeout(() => ((late = true), upstream.destroy()), ms);
57
+ upstream.on('response', (up) => {
58
+ clearTimeout(timer);
59
+ res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
60
+ // A child gone in the middle of its body: the answer is cut, not left open.
61
+ up.once('close', () => void (up.complete || res.destroy()));
62
+ up.pipe(res);
63
+ });
64
+ upstream.on('error', () => {
65
+ if (res.headersSent)
66
+ return void res.destroy();
67
+ next(late ? noAnswer(ms) : fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
68
+ });
69
+ return () => clearTimeout(timer);
70
+ };
71
+ // Streams the request to the child as it came (path and query kept), no pooled connection.
72
+ const forward = (req, res, next, to, ms) => {
73
+ const { lane, leave } = to;
74
+ const upstream = requestTo(req, lane);
75
+ const stop = relay(upstream, res, next, ms);
76
+ upstream.on('error', leave);
50
77
  // A client that went away aborts the request to the child too.
51
78
  res.on('close', () => {
79
+ stop();
52
80
  if (!res.writableFinished)
53
81
  upstream.destroy();
54
82
  leave();
55
83
  });
56
- upstream.on('error', () => {
57
- leave();
58
- if (res.headersSent)
59
- return void res.destroy();
60
- next(fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
61
- });
62
84
  req.pipe(upstream);
63
85
  };
64
- export const proxyTo = (entries, gateMs = GATE_MS) => async (req, res, next) => {
65
- const lane = await laneFor(entries, String(req.params['id']), gateMs);
66
- forward(req, res, next, lane);
86
+ export const proxyTo = (entries, limits) => async (req, res, next) => {
87
+ const taken = await laneFor(entries, String(req.params['id']), limits.gateMs);
88
+ forward(req, res, next, taken, limits.answerMs);
67
89
  };
@@ -1,2 +1,3 @@
1
1
  export type Queue = <T>(fn: () => Promise<T>) => Promise<T>;
2
2
  export declare const serialQueue: () => Queue;
3
+ export declare const waitAtMost: <T>(queue: Queue, ms: number, fn: () => Promise<T>) => Promise<T>;
@@ -1,3 +1,4 @@
1
+ import { fail } from '../../envelope/envelope.js';
1
2
  export const serialQueue = () => {
2
3
  let chain = Promise.resolve();
3
4
  return (fn) => {
@@ -6,3 +7,21 @@ export const serialQueue = () => {
6
7
  return run;
7
8
  };
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,11 +1,13 @@
1
1
  import { type Express } from 'express';
2
- import { type Entries } from './ops.js';
2
+ import { type Entries } from './entries.js';
3
3
  import { type SupervisorDeps } from './supervisor.js';
4
- export declare const DAEMON_SERVICE = "agentage-daemon";
5
- export interface DaemonInfo {
4
+ interface DaemonInfo {
6
5
  version: string;
7
6
  pid: number;
8
7
  protocol: number;
9
8
  invalid: boolean;
9
+ unreadable?: string;
10
+ notJson?: boolean;
10
11
  }
11
12
  export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo) => Express;
13
+ export {};
@@ -4,32 +4,81 @@ import { ok } from '../../envelope/envelope.js';
4
4
  import { BODY_LIMIT } from '../../server/app.js';
5
5
  import { errorHandler, notFound } from '../../server/errors.js';
6
6
  import { localOnly } from './guard.js';
7
- import { addExtension, changeExtension, listed, removeExtension, summary, } from './ops.js';
7
+ import { addExtension } from './add.js';
8
+ import { listed, summary } from './entries.js';
9
+ import { assertReadable } from './installation.js';
10
+ import { changeExtension, removeExtension } from './ops.js';
11
+ import {} from './pending.js';
12
+ import { waitAtMost } from './queue.js';
8
13
  import { proxyTo } from './proxy.js';
14
+ import { stopsNow } from './stopping.js';
9
15
  import {} from './supervisor.js';
10
16
  // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
11
- export const DAEMON_SERVICE = 'agentage-daemon';
12
- const healthOf = (entries, { version, pid, protocol, invalid }) => {
17
+ const DAEMON_SERVICE = 'agentage-daemon';
18
+ const installationOf = ({ invalid, unreadable, notJson }) => {
19
+ if (unreadable)
20
+ return { installation: 'unreadable', installationError: unreadable };
21
+ return invalid || notJson ? { installation: 'invalid' } : {};
22
+ };
23
+ const reasonOf = (err) => err.details?.reason;
24
+ // A refusal for a file that turned not JSON shows in /health until a change reads the file again.
25
+ const checkReadable = (deps, info) => assertReadable(deps.configDir, info.unreadable).then(() => void (info.notJson = false), (err) => {
26
+ info.notJson = reasonOf(err) === 'not JSON';
27
+ throw err;
28
+ });
29
+ const healthOf = (deps, entries, info) => {
13
30
  const all = [...entries.values()];
14
- const settled = !invalid && all.every((e) => e.state === 'running' || e.state === 'disabled');
31
+ const settled = all.every((e) => e.state === 'running' || e.state === 'disabled');
32
+ const synced = !deps.unsynced.size;
33
+ const clean = !info.invalid && !info.unreadable && !info.notJson;
34
+ const status = settled && synced && clean ? 'ok' : 'degraded';
35
+ const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
15
36
  const extensions = all.map(summary);
16
- const status = settled ? 'ok' : 'degraded';
17
- const self = { service: DAEMON_SERVICE, pid, protocol };
18
- return { status, version, ...self, extensions, ...(invalid && { installation: 'invalid' }) };
37
+ const changing = deps.pending.list();
38
+ const busy = changing.length ? { pending: changing } : {};
39
+ const marks = {
40
+ ...busy,
41
+ ...(!synced && { unsynced: [...deps.unsynced] }),
42
+ ...installationOf(info),
43
+ };
44
+ return { status, version: info.version, ...self, extensions, ...marks };
45
+ };
46
+ // What a POST body names, for /health: the id, or the folder.
47
+ const named = (body) => {
48
+ const { id, source } = (body ?? {});
49
+ if (typeof id === 'string')
50
+ return { id };
51
+ return typeof source === 'string' ? { source } : {};
19
52
  };
20
- const changes = (deps, entries) => {
21
- const run = deps.queue;
53
+ // Every change in the queue, and none while installation.json cannot be read.
54
+ const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(deps.queue, deps.installMs, async () => {
55
+ if (deps.stopping.signal.aborted)
56
+ throw stopsNow();
57
+ await checkReadable(deps, info);
58
+ return fn();
59
+ }));
60
+ const changes = (deps, entries, info, p) => {
61
+ const run = runner(deps, info, p);
22
62
  const id = (params) => String(params['id']);
23
- const add = async (req, res) => void res.status(201).json(ok(await run(() => addExtension(deps, entries, req.body))));
24
- const change = async (req, res) => void res.json(ok(await run(() => changeExtension(deps, entries, id(req.params), req.body))));
63
+ const add = async (req, res) => {
64
+ const what = { op: 'install', ...named(req.body) };
65
+ res.status(201).json(ok(await run(what, () => addExtension(deps, entries, req.body))));
66
+ };
67
+ const change = async ({ params, body }, res) => {
68
+ const what = { op: 'update', id: id(params) };
69
+ res.json(ok(await run(what, () => changeExtension(deps, entries, id(params), body))));
70
+ };
25
71
  const purge = (q) => q['purge'] === 'true';
26
- const remove = async (req, res) => void res.json(ok(await run(() => removeExtension(deps, entries, id(req.params), purge(req.query)))));
72
+ const remove = async ({ params, query }, res) => {
73
+ const what = { op: 'remove', id: id(params) };
74
+ res.json(ok(await run(what, () => removeExtension(deps, entries, what.id, purge(query)))));
75
+ };
27
76
  return { add, change, remove };
28
77
  };
29
- const hostRoutes = (app, deps, entries) => {
78
+ const hostRoutes = (app, deps, entries, info, p) => {
30
79
  app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
31
80
  const json = express.json({ limit: BODY_LIMIT });
32
- const { add, change, remove } = changes(deps, entries);
81
+ const { add, change, remove } = changes(deps, entries, info, p);
33
82
  app.post('/host/extensions', json, add);
34
83
  app.patch('/host/extensions/:id', json, change);
35
84
  app.delete('/host/extensions/:id', remove);
@@ -37,11 +86,12 @@ const hostRoutes = (app, deps, entries) => {
37
86
  // C5: /health, /host/extensions, and /api/{id}/* to the child of that id; Host and Origin first.
38
87
  export const daemonApp = (deps, entries, port, info) => {
39
88
  const app = express();
89
+ const pending = deps.pending;
40
90
  app.disable('x-powered-by');
41
91
  app.use(agcidMiddleware, localOnly(port));
42
- app.use('/api/:id', proxyTo(entries));
43
- app.get('/health', (_req, res) => void res.set('Cache-Control', 'no-store').json(healthOf(entries, info)));
44
- hostRoutes(app, deps, entries);
92
+ app.use('/api/:id', proxyTo(entries, deps));
93
+ app.get('/health', (_req, res) => void res.set('Cache-Control', 'no-store').json(healthOf(deps, entries, info)));
94
+ hostRoutes(app, deps, entries, info, pending);
45
95
  app.use(notFound);
46
96
  app.use(errorHandler(deps.log));
47
97
  return app;
@@ -0,0 +1,10 @@
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>;
@@ -0,0 +1,28 @@
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
+ };
@@ -2,12 +2,16 @@ import { type Log } from '../../log/log.js';
2
2
  import { type Launch } from './child.js';
3
3
  import { type InstallEntry } from './installation.js';
4
4
  import { type Lane } from './lane.js';
5
+ import { type Limits } from './limits.js';
6
+ import { type PendingChanges } from './pending.js';
5
7
  import { type Queue } from './queue.js';
6
- export declare const GATE_MS = 30000;
7
- export type Installer = (spec: {
8
+ import { type Stopping } from './stopping.js';
9
+ export interface InstallSpec {
8
10
  id: string;
9
11
  version?: string;
10
- }) => Promise<{
12
+ signal?: AbortSignal;
13
+ }
14
+ export type Installer = (spec: InstallSpec) => Promise<{
11
15
  id: string;
12
16
  version: string;
13
17
  dir: string;
@@ -32,21 +36,19 @@ export interface Next {
32
36
  values: Values;
33
37
  dir?: string;
34
38
  }
35
- export interface SupervisorDeps {
39
+ export interface SupervisorDeps extends Limits {
36
40
  configDir: string;
37
41
  launch: Launch;
38
42
  origin: () => string;
39
43
  install?: Installer;
40
44
  log: Log;
41
- drainMs: number;
42
- healthMs: number;
43
45
  queue: Queue;
46
+ pending: PendingChanges;
47
+ stopping: Stopping;
48
+ unsynced: Set<string>;
44
49
  }
45
- export declare const DRAIN_MS = 10000;
46
- export declare const HEALTH_MS = 60000;
47
50
  export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
48
- export declare const launchFor: (deps: SupervisorDeps, entry: Entry, install: InstallEntry, values: Values, given?: string) => Promise<Lane>;
49
51
  export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
50
- export declare const startFailed: (entry: Entry, err: unknown) => import("../../envelope/envelope.js").Failure;
51
- export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next) => Promise<void>;
52
+ export declare const hold: (entry: Entry) => (() => void);
53
+ export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next, undo?: () => Promise<unknown>) => Promise<void>;
52
54
  export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
@@ -5,11 +5,11 @@ import {} from './child.js';
5
5
  import { dataDirOf, readValues } from './daemon-files.js';
6
6
  import {} from './installation.js';
7
7
  import { laneOf, retire } from './lane.js';
8
+ import {} from './limits.js';
8
9
  import { runInstaller } from './installer-call.js';
10
+ import {} from './pending.js';
9
11
  import {} from './queue.js';
10
- export const GATE_MS = 30_000;
11
- export const DRAIN_MS = 10_000;
12
- export const HEALTH_MS = 60_000;
12
+ import {} from './stopping.js';
13
13
  export const valuesOf = async (configDir, id) => ({
14
14
  settings: await readValues(configDir, 'settings', id),
15
15
  secrets: (await readValues(configDir, 'secrets', id)),
@@ -27,24 +27,27 @@ const dirOf = async (deps, entry, install, given) => {
27
27
  // Healthy before it gets the route: the child's own /health answers 200.
28
28
  const healthy = async (port, ms) => {
29
29
  const signal = AbortSignal.timeout(ms);
30
- const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch(() => {
31
- throw new Error(`health did not answer in ${ms} ms`);
30
+ const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
31
+ if (err.name === 'TimeoutError')
32
+ throw new Error(`health did not answer in ${ms} ms`);
33
+ const cause = err.cause?.code ?? err.message;
34
+ throw new Error(`health could not be reached (${cause})`);
32
35
  });
33
36
  if (res.status !== 200)
34
37
  throw new Error(`health answered ${res.status}`);
35
38
  };
36
39
  // A new child for install with values, healthy; the entry learns the version the package has.
37
- export const launchFor = async (deps, entry, install, values, given) => {
40
+ const launchFor = async (deps, entry, install, values, given) => {
38
41
  const dir = await dirOf(deps, entry, install, given);
39
42
  const pkg = await readManifest(dir);
40
43
  const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...values };
41
- const child = await deps.launch({ ...spec, origin: deps.origin() });
44
+ const child = await deps.launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs });
42
45
  await healthy(child.port, deps.healthMs).catch(async (err) => {
43
46
  await child.stop();
44
47
  throw err;
45
48
  });
46
49
  Object.assign(entry, { dir, version: pkg.version });
47
- const lane = laneOf(child, pkg.version);
50
+ const lane = laneOf(child);
48
51
  void child.exited.then((how) => exitedEarly(deps, entry, lane, how));
49
52
  return lane;
50
53
  };
@@ -72,8 +75,8 @@ export const startEntry = async (deps, entry) => {
72
75
  failed(deps, entry, err);
73
76
  }
74
77
  };
75
- // New requests of the extension wait here (the proxy gives up after GATE_MS) until release.
76
- const hold = (entry) => {
78
+ // New requests of the extension wait here (the proxy gives up after gateMs) until release.
79
+ export const hold = (entry) => {
77
80
  let release = () => undefined;
78
81
  entry.gate = new Promise((resolve) => (release = resolve));
79
82
  return () => {
@@ -88,25 +91,21 @@ const restore = async (deps, entry) => {
88
91
  else
89
92
  await startEntry(deps, entry);
90
93
  };
91
- export const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
94
+ const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
92
95
  code: 'START_FAILED',
93
96
  });
94
- // One writer per data folder, so one sequence for every extension, running or not: hold, drain
95
- // and stop the old child, start the new one, release. A refusal restores the old one and is a 400.
96
- export const swap = async (deps, entry, to) => {
97
- const release = hold(entry);
97
+ // One writer per data folder (the caller holds the gate): stop the old child, start the new one.
98
+ export const swap = async (deps, entry, to, undo = async () => undefined) => {
98
99
  try {
99
100
  await halt(entry, deps.drainMs);
100
101
  entry.lane = await launchFor(deps, entry, to.install, to.values, to.dir);
101
102
  Object.assign(entry, { state: 'running', error: undefined });
102
103
  }
103
104
  catch (err) {
105
+ await undo();
104
106
  await restore(deps, entry);
105
107
  throw startFailed(entry, err);
106
108
  }
107
- finally {
108
- release();
109
- }
110
109
  };
111
110
  // Detached first, so its exit is not a failure; then drained and stopped.
112
111
  export const halt = async (entry, drainMs) => {
@@ -0,0 +1,8 @@
1
+ import { type InstallEntry } from './installation.js';
2
+ import { type SupervisorDeps, type Values } from './supervisor.js';
3
+ export interface Written {
4
+ install?: InstallEntry;
5
+ values?: Values;
6
+ }
7
+ export declare const unsynced: (deps: SupervisorDeps, id: string) => void;
8
+ export declare const writeAll: (deps: SupervisorDeps, id: string, to: Written, was?: Written) => Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { writeValues } from './daemon-files.js';
2
+ import { persist } from './entries.js';
3
+ import {} from './installation.js';
4
+ import {} from './supervisor.js';
5
+ const stepsOf = (deps, id, to, was) => {
6
+ // An empty object is no row: what valuesOf reads for an id the file does not name.
7
+ const values = (kind, v) => () => {
8
+ const rows = v?.[kind];
9
+ return writeValues(deps.configDir, kind, id, rows && Object.keys(rows).length ? rows : undefined, deps.lockMs);
10
+ };
11
+ const steps = [
12
+ [() => persist(deps, id, to.install), () => persist(deps, id, was.install)],
13
+ [values('settings', to.values), values('settings', was.values)],
14
+ // Last: a failed write before it leaves secrets.json as it was.
15
+ [values('secrets', to.values), values('secrets', was.values)],
16
+ ];
17
+ // A remove deletes the secrets first: a crash half way leaves none for a later install of id.
18
+ return to.install ? steps : steps.reverse();
19
+ };
20
+ // An undo that failed leaves the files of id unlike the list: one warn line, and /health names it.
21
+ export const unsynced = (deps, id) => {
22
+ deps.unsynced.add(id);
23
+ deps.log.warn('a failed write could not be undone: the daemon files may not match the list', {
24
+ id,
25
+ });
26
+ };
27
+ // installation.json, settings.json, secrets.json in turn; a failed one undoes those written before it.
28
+ export const writeAll = async (deps, id, to, was = {}) => {
29
+ const done = [];
30
+ try {
31
+ for (const [run, undo] of stepsOf(deps, id, to, was)) {
32
+ await run();
33
+ done.unshift(undo);
34
+ }
35
+ }
36
+ catch (err) {
37
+ let lost = false;
38
+ for (const undo of done)
39
+ await undo().catch(() => (lost = true));
40
+ if (lost)
41
+ unsynced(deps, id);
42
+ throw err;
43
+ }
44
+ deps.unsynced.delete(id);
45
+ };
@@ -1,2 +1,3 @@
1
1
  export declare const DATA_DIR_LOCKED = "DATA_DIR_LOCKED";
2
+ export declare const EMPTY_LOCK_MS = 1000;
2
3
  export declare const lockDataDir: (dataDir: string) => Promise<() => Promise<void>>;
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { rmSync } from 'node:fs';
3
- import { link, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { link, readFile, unlink, writeFile } from 'node:fs/promises';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
4
5
  export const DATA_DIR_LOCKED = 'DATA_DIR_LOCKED';
5
6
  // The locks of this process: our own pid in a lock not in here is stale (a container is pid 1 again).
6
7
  const held = new Set();
@@ -12,43 +13,82 @@ const alive = (pid) => {
12
13
  return err.code === 'EPERM';
13
14
  }
14
15
  };
15
- const holder = async (file) => Number(await readFile(file, 'utf8').catch(() => '0'));
16
+ // A lock made with wx is empty until its pid is written (slow on a network volume): being written
17
+ // for EMPTY_LOCK_MS, then stale.
18
+ export const EMPTY_LOCK_MS = 1_000;
19
+ const pidIn = (file) => readFile(file, 'utf8').catch(() => '0');
20
+ const holder = async (file) => {
21
+ const until = Date.now() + EMPTY_LOCK_MS;
22
+ let pid = await pidIn(file);
23
+ while (pid === '' && Date.now() < until) {
24
+ await sleep(25);
25
+ pid = await pidIn(file);
26
+ }
27
+ return Number(pid);
28
+ };
16
29
  const live = (lock, pid) => pid === process.pid ? held.has(lock) : pid > 0 && alive(pid);
17
30
  const locked = (lock, pid) => Object.assign(new Error(`${lock.slice(0, -5)} is open in process ${pid}`), {
18
31
  code: DATA_DIR_LOCKED,
32
+ pid,
19
33
  });
20
- const unique = (file) => `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
21
- // A full lock file appears at once or not at all: written aside, then linked (fails if one exists).
22
- const take = async (lock) => {
23
- const tmp = unique(lock);
24
- await writeFile(tmp, String(process.pid));
34
+ const exists = (err) => err.code === 'EEXIST';
35
+ // No hard links on the volume (some network or FUSE mounts): an exclusive create, then the pid.
36
+ const create = async (lock, pid) => {
25
37
  try {
26
- await link(tmp, lock);
27
- held.add(lock);
38
+ await writeFile(lock, String(pid), { flag: 'wx' });
28
39
  return true;
29
40
  }
30
41
  catch (err) {
31
- if (err.code !== 'EEXIST')
42
+ if (!exists(err))
32
43
  throw err;
33
44
  return false;
34
45
  }
46
+ };
47
+ // The lock file at once (a link of a full file), or by create where links fail; false: it exists.
48
+ const place = async (from, lock, pid) => {
49
+ try {
50
+ await link(from, lock);
51
+ return true;
52
+ }
53
+ catch (err) {
54
+ return exists(err) ? false : create(lock, pid);
55
+ }
56
+ };
57
+ const unique = (file) => `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
58
+ // A full lock file appears at once or not at all: written aside, then linked (fails if one exists).
59
+ const take = async (lock) => {
60
+ const tmp = unique(lock);
61
+ await writeFile(tmp, String(process.pid));
62
+ try {
63
+ const taken = await place(tmp, lock, process.pid);
64
+ if (taken)
65
+ held.add(lock);
66
+ return taken;
67
+ }
35
68
  finally {
36
69
  await unlink(tmp).catch(() => undefined);
37
70
  }
38
71
  };
39
- // Only one starter moves the stale file away; one that moved a fresh lock puts it back and refuses.
40
- const clearStale = async (lock, pid) => {
41
- const moved = unique(`${lock}.stale`);
42
- const gone = await rename(lock, moved).then(() => false, (err) => err.code === 'ENOENT');
43
- if (gone)
44
- return;
45
- const now = await holder(moved);
46
- if (now !== pid) {
47
- await link(moved, lock).catch(() => undefined);
48
- await unlink(moved);
49
- throw locked(lock, now);
72
+ // A guard left by a breaker that died is removed and taken once more.
73
+ const takeDeadGuard = async (guard) => {
74
+ if (live(guard, await holder(guard)))
75
+ return false;
76
+ await unlink(guard).catch(() => undefined);
77
+ return take(guard);
78
+ };
79
+ // One breaker at a time (<lock>.break): the lock is removed only while it still names the dead pid.
80
+ const breakStale = async (lock, pid) => {
81
+ const guard = `${lock}.break`;
82
+ if (!(await take(guard)) && !(await takeDeadGuard(guard)))
83
+ throw locked(lock, await holder(guard));
84
+ try {
85
+ if ((await holder(lock)) === pid)
86
+ await unlink(lock).catch(() => undefined);
87
+ }
88
+ finally {
89
+ rmSync(guard, { force: true });
90
+ held.delete(guard);
50
91
  }
51
- await unlink(moved);
52
92
  };
53
93
  const turns = new Map();
54
94
  // One taker per lock in this process: none sees our pid in the file before it is in held.
@@ -65,7 +105,7 @@ const acquire = async (lock) => {
65
105
  const pid = await holder(lock);
66
106
  if (live(lock, pid))
67
107
  throw locked(lock, pid);
68
- await clearStale(lock, pid);
108
+ await breakStale(lock, pid);
69
109
  if (!(await take(lock)))
70
110
  throw locked(lock, await holder(lock));
71
111
  };
@@ -1,6 +1,5 @@
1
1
  import { type Env } from '../runtime/build-info.js';
2
2
  import { type HostExtras } from './host-extension.js';
3
- export declare const HOST_PORT = 8080;
4
3
  export declare const BIND_REFUSED = "AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off";
5
4
  export declare const hostEnvOf: (env: Env) => {
6
5
  dir: string;
@@ -10,6 +9,8 @@ export declare const hostEnvOf: (env: Env) => {
10
9
  settings: Record<string, unknown>;
11
10
  secretsDir: string;
12
11
  origin: string;
12
+ drainMs: number;
13
+ storeOpenMs: number;
13
14
  };
14
15
  export declare const guardOf: (env: Env, { bind, dir }: {
15
16
  bind: string;