@agentage/extension 0.13.0 → 0.15.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 (146) hide show
  1. package/README.md +3 -1
  2. package/dist/discovery/discovery.d.ts +1 -0
  3. package/dist/discovery/discovery.schema.d.ts +2 -0
  4. package/dist/discovery/discovery.schema.js +22 -10
  5. package/dist/health/health.d.ts +2 -0
  6. package/dist/health/health.js +4 -2
  7. package/dist/health/health.schema.d.ts +9 -0
  8. package/dist/health/health.schema.js +3 -0
  9. package/dist/host/clock-rate.d.ts +1 -0
  10. package/dist/host/clock-rate.js +12 -0
  11. package/dist/host/daemon/add.d.ts +9 -0
  12. package/dist/host/daemon/add.js +84 -0
  13. package/dist/host/daemon/child-files.d.ts +20 -0
  14. package/dist/host/daemon/child-files.js +45 -0
  15. package/dist/host/daemon/child.d.ts +12 -4
  16. package/dist/host/daemon/child.js +78 -44
  17. package/dist/host/daemon/daemon-files.d.ts +6 -5
  18. package/dist/host/daemon/daemon-files.js +20 -12
  19. package/dist/host/daemon/daemon-owner.d.ts +1 -0
  20. package/dist/host/daemon/daemon-owner.js +32 -0
  21. package/dist/host/daemon/daemon.d.ts +3 -3
  22. package/dist/host/daemon/daemon.js +72 -35
  23. package/dist/host/daemon/entries.d.ts +21 -0
  24. package/dist/host/daemon/entries.js +24 -0
  25. package/dist/host/daemon/gate.d.ts +3 -0
  26. package/dist/host/daemon/gate.js +19 -0
  27. package/dist/host/daemon/guard.d.ts +2 -1
  28. package/dist/host/daemon/guard.js +17 -4
  29. package/dist/host/daemon/health-routes.d.ts +17 -0
  30. package/dist/host/daemon/health-routes.js +61 -0
  31. package/dist/host/daemon/host-token.d.ts +6 -0
  32. package/dist/host/daemon/host-token.js +28 -0
  33. package/dist/host/daemon/installation.d.ts +17 -4
  34. package/dist/host/daemon/installation.js +52 -8
  35. package/dist/host/daemon/installer-call.d.ts +16 -2
  36. package/dist/host/daemon/installer-call.js +33 -7
  37. package/dist/host/daemon/json-file.d.ts +3 -2
  38. package/dist/host/daemon/json-file.js +21 -10
  39. package/dist/host/daemon/lane.d.ts +1 -3
  40. package/dist/host/daemon/lane.js +4 -9
  41. package/dist/host/daemon/last-words.d.ts +2 -0
  42. package/dist/host/daemon/last-words.js +28 -0
  43. package/dist/host/daemon/limits.d.ts +15 -0
  44. package/dist/host/daemon/limits.js +29 -0
  45. package/dist/host/daemon/ops.d.ts +2 -26
  46. package/dist/host/daemon/ops.js +46 -103
  47. package/dist/host/daemon/patch-values.d.ts +6 -0
  48. package/dist/host/daemon/patch-values.js +39 -0
  49. package/dist/host/daemon/pending.d.ts +15 -0
  50. package/dist/host/daemon/pending.js +18 -0
  51. package/dist/host/daemon/proxy.d.ts +3 -2
  52. package/dist/host/daemon/proxy.js +54 -24
  53. package/dist/host/daemon/queue.d.ts +1 -0
  54. package/dist/host/daemon/queue.js +19 -0
  55. package/dist/host/daemon/reload-marker.d.ts +8 -0
  56. package/dist/host/daemon/reload-marker.js +56 -0
  57. package/dist/host/daemon/reload-route.d.ts +4 -0
  58. package/dist/host/daemon/reload-route.js +21 -0
  59. package/dist/host/daemon/reload.d.ts +10 -0
  60. package/dist/host/daemon/reload.js +73 -0
  61. package/dist/host/daemon/restart.d.ts +14 -0
  62. package/dist/host/daemon/restart.js +59 -0
  63. package/dist/host/daemon/routes.d.ts +3 -9
  64. package/dist/host/daemon/routes.js +54 -22
  65. package/dist/host/daemon/run-lock.d.ts +1 -0
  66. package/dist/host/daemon/run-lock.js +15 -0
  67. package/dist/host/daemon/seal-reach.d.ts +2 -0
  68. package/dist/host/daemon/seal-reach.js +38 -0
  69. package/dist/host/daemon/seal.d.ts +16 -0
  70. package/dist/host/daemon/seal.js +71 -0
  71. package/dist/host/daemon/start-checks.d.ts +6 -0
  72. package/dist/host/daemon/start-checks.js +28 -0
  73. package/dist/host/daemon/stopping.d.ts +10 -0
  74. package/dist/host/daemon/stopping.js +28 -0
  75. package/dist/host/daemon/supervisor.d.ts +19 -11
  76. package/dist/host/daemon/supervisor.js +39 -47
  77. package/dist/host/daemon/write-all.d.ts +8 -0
  78. package/dist/host/daemon/write-all.js +45 -0
  79. package/dist/host/data-lock.d.ts +3 -1
  80. package/dist/host/data-lock.js +88 -29
  81. package/dist/host/host-env.d.ts +3 -1
  82. package/dist/host/host-env.js +10 -2
  83. package/dist/host/host-extension.d.ts +8 -0
  84. package/dist/host/host-extension.js +30 -45
  85. package/dist/host/host-parts.d.ts +25 -0
  86. package/dist/host/host-parts.js +75 -0
  87. package/dist/host/host-store.d.ts +11 -1
  88. package/dist/host/host-store.js +45 -12
  89. package/dist/host/index.d.ts +4 -0
  90. package/dist/host/index.js +4 -0
  91. package/dist/host/main.js +2 -0
  92. package/dist/host/part-checks.d.ts +2 -0
  93. package/dist/host/part-checks.js +19 -0
  94. package/dist/host/serve-host.d.ts +2 -1
  95. package/dist/host/serve-host.js +16 -10
  96. package/dist/manifest/parts.d.ts +3 -0
  97. package/dist/manifest/parts.js +3 -0
  98. package/dist/mcp/mcp-app.d.ts +4 -0
  99. package/dist/mcp/mcp-app.js +11 -11
  100. package/dist/runtime/part-mounts.d.ts +29 -0
  101. package/dist/runtime/part-mounts.js +52 -0
  102. package/dist/runtime/part-runners.d.ts +2 -15
  103. package/dist/runtime/part-runners.js +13 -58
  104. package/dist/server/app.d.ts +5 -1
  105. package/dist/server/app.js +17 -17
  106. package/dist/server/serve.d.ts +3 -0
  107. package/dist/server/serve.js +9 -4
  108. package/dist/tool/build.d.ts +3 -0
  109. package/dist/tool/build.js +42 -27
  110. package/dist/tool/capabilities.d.ts +1 -0
  111. package/dist/tool/capabilities.js +8 -0
  112. package/dist/tool/check.d.ts +2 -0
  113. package/dist/tool/check.js +23 -8
  114. package/dist/tool/container-parts.d.ts +7 -0
  115. package/dist/tool/container-parts.js +10 -0
  116. package/dist/tool/container-recipe.d.ts +4 -0
  117. package/dist/tool/container-recipe.js +55 -0
  118. package/dist/tool/container-stage.d.ts +3 -0
  119. package/dist/tool/container-stage.js +51 -0
  120. package/dist/tool/container.d.ts +73 -0
  121. package/dist/tool/container.js +28 -0
  122. package/dist/tool/docker.d.ts +5 -0
  123. package/dist/tool/docker.js +15 -0
  124. package/dist/tool/format.js +23 -9
  125. package/dist/tool/index.d.ts +2 -0
  126. package/dist/tool/index.js +2 -0
  127. package/dist/tool/kit-version.d.ts +3 -0
  128. package/dist/tool/kit-version.js +28 -2
  129. package/dist/tool/labels.d.ts +1 -1
  130. package/dist/tool/labels.js +4 -2
  131. package/dist/tool/main.js +10 -1
  132. package/dist/tool/stage.d.ts +1 -0
  133. package/dist/tool/stage.js +1 -1
  134. package/dist/tool/up/local-record.d.ts +1 -0
  135. package/dist/worker/clock.d.ts +6 -0
  136. package/dist/worker/clock.js +21 -0
  137. package/dist/worker/scheduler.d.ts +1 -0
  138. package/dist/worker/scheduler.js +6 -2
  139. package/package.json +1 -1
  140. package/schemas/extension-discovery.schema.json +8 -1
  141. package/schemas/extension-record.schema.json +8 -1
  142. package/schemas/health.schema.json +17 -0
  143. package/dist/host/daemon/secret-names.d.ts +0 -1
  144. package/dist/host/daemon/secret-names.js +0 -14
  145. package/dist/host/daemon/setting-values.d.ts +0 -1
  146. package/dist/host/daemon/setting-values.js +0 -26
@@ -2,12 +2,18 @@ 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 Retry } from './restart.js';
9
+ import { type Stopping } from './stopping.js';
10
+ export { halt, hold } from './gate.js';
11
+ export interface InstallSpec {
8
12
  id: string;
9
13
  version?: string;
10
- }) => Promise<{
14
+ signal?: AbortSignal;
15
+ }
16
+ export type Installer = (spec: InstallSpec) => Promise<{
11
17
  id: string;
12
18
  version: string;
13
19
  dir: string;
@@ -22,6 +28,9 @@ export interface Entry {
22
28
  error?: string;
23
29
  lane?: Lane;
24
30
  gate?: Promise<void>;
31
+ exits?: number[];
32
+ restarts?: number;
33
+ retry?: Retry;
25
34
  }
26
35
  export interface Values {
27
36
  settings: Record<string, unknown>;
@@ -32,21 +41,20 @@ export interface Next {
32
41
  values: Values;
33
42
  dir?: string;
34
43
  }
35
- export interface SupervisorDeps {
44
+ export interface SupervisorDeps extends Limits {
36
45
  configDir: string;
37
46
  launch: Launch;
38
47
  origin: () => string;
39
48
  install?: Installer;
40
49
  log: Log;
41
- drainMs: number;
42
- healthMs: number;
43
50
  queue: Queue;
51
+ pending: PendingChanges;
52
+ stopping: Stopping;
53
+ unsynced: Set<string>;
44
54
  }
45
- export declare const DRAIN_MS = 10000;
46
- export declare const HEALTH_MS = 60000;
47
55
  export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
48
56
  export declare const launchFor: (deps: SupervisorDeps, entry: Entry, install: InstallEntry, values: Values, given?: string) => Promise<Lane>;
49
- export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
57
+ export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<Error | undefined>;
58
+ export declare const restore: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
50
59
  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 halt: (entry: Entry, drainMs: number) => Promise<void>;
60
+ export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next, undo?: () => Promise<unknown>) => Promise<void>;
@@ -4,12 +4,16 @@ import { readManifest } from '../../manifest/read-manifest.js';
4
4
  import {} from './child.js';
5
5
  import { dataDirOf, readValues } from './daemon-files.js';
6
6
  import {} from './installation.js';
7
- import { laneOf, retire } from './lane.js';
7
+ import { halt } from './gate.js';
8
+ import { laneOf } from './lane.js';
9
+ import {} from './limits.js';
8
10
  import { runInstaller } from './installer-call.js';
11
+ import {} from './pending.js';
9
12
  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;
13
+ import { crashed, healthyFor, reasonOf, resetRestarts } from './restart.js';
14
+ import { assertSecrets, healthy, redact } from './start-checks.js';
15
+ import {} from './stopping.js';
16
+ export { halt, hold } from './gate.js';
13
17
  export const valuesOf = async (configDir, id) => ({
14
18
  settings: await readValues(configDir, 'settings', id),
15
19
  secrets: (await readValues(configDir, 'secrets', id)),
@@ -24,93 +28,81 @@ const dirOf = async (deps, entry, install, given) => {
24
28
  return entry.dir;
25
29
  return (await runInstaller(deps, { id: entry.id, version: install.version })).dir;
26
30
  };
27
- // Healthy before it gets the route: the child's own /health answers 200.
28
- const healthy = async (port, ms) => {
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`);
32
- });
33
- if (res.status !== 200)
34
- throw new Error(`health answered ${res.status}`);
35
- };
36
31
  // A new child for install with values, healthy; the entry learns the version the package has.
37
32
  export const launchFor = async (deps, entry, install, values, given) => {
38
33
  const dir = await dirOf(deps, entry, install, given);
39
34
  const pkg = await readManifest(dir);
35
+ assertSecrets(pkg, values.secrets);
40
36
  const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...values };
41
- const child = await deps.launch({ ...spec, origin: deps.origin() });
37
+ const child = await deps
38
+ .launch({ ...spec, origin: deps.origin(), storeOpenMs: deps.healthMs })
39
+ .catch((err) => Promise.reject(Object.assign(err, { message: redact(err.message, values.secrets) })));
42
40
  await healthy(child.port, deps.healthMs).catch(async (err) => {
43
41
  await child.stop();
44
42
  throw err;
45
43
  });
46
44
  Object.assign(entry, { dir, version: pkg.version });
47
- const lane = laneOf(child, pkg.version);
48
- void child.exited.then((how) => exitedEarly(deps, entry, lane, how));
45
+ const lane = laneOf(child);
46
+ const words = (how) => redact(reasonOf(how), values.secrets);
47
+ void child.exited.then((how) => exitedEarly(deps, entry, lane, words(how)));
48
+ healthyFor(deps, entry, lane);
49
49
  return lane;
50
50
  };
51
- // A child that exits while it is the route is failed; a retired one was detached first.
52
- const exitedEarly = (deps, entry, lane, how) => {
51
+ // A child that exits while it is the route restarts (C6); a retired one was detached first.
52
+ const exitedEarly = (deps, entry, lane, why) => {
53
53
  if (entry.lane !== lane)
54
54
  return;
55
- const why = how.signal ? `signal ${how.signal}` : `code ${how.code}`;
56
- Object.assign(entry, { lane: undefined, state: 'failed', error: `the process exited (${why})` });
57
- deps.log.warn('extension process exited', { id: entry.id });
55
+ entry.lane = undefined;
56
+ crashed(deps, entry, why, () => restartEntry(deps, entry));
58
57
  };
59
58
  const failed = (deps, entry, err) => {
60
59
  Object.assign(entry, { state: 'failed', error: err.message });
61
60
  deps.log.warn('extension failed to start', { id: entry.id, reason: entry.error });
62
61
  };
63
- // The install and values of installation.json, as they are on disk.
62
+ // The install and values of installation.json, as they are on disk; the error when it failed.
64
63
  export const startEntry = async (deps, entry) => {
65
64
  entry.state = 'starting';
66
65
  try {
67
66
  const values = await valuesOf(deps.configDir, entry.id);
68
67
  entry.lane = await launchFor(deps, entry, entry.install, values);
69
68
  Object.assign(entry, { state: 'running', error: undefined });
69
+ return undefined;
70
70
  }
71
71
  catch (err) {
72
72
  failed(deps, entry, err);
73
+ return err;
73
74
  }
74
75
  };
75
- // New requests of the extension wait here (the proxy gives up after GATE_MS) until release.
76
- const hold = (entry) => {
77
- let release = () => undefined;
78
- entry.gate = new Promise((resolve) => (release = resolve));
79
- return () => {
80
- entry.gate = undefined;
81
- release();
82
- };
76
+ // A restart that does not start counts as one more exit.
77
+ const restartEntry = async (deps, entry) => {
78
+ const err = await startEntry(deps, entry);
79
+ if (err)
80
+ crashed(deps, entry, err.message, () => restartEntry(deps, entry));
83
81
  };
84
82
  // The old install again after a refused change; a disabled one stays stopped.
85
- const restore = async (deps, entry) => {
83
+ export const restore = async (deps, entry) => {
86
84
  if (entry.install.enabled === false)
87
85
  entry.state = 'disabled';
88
86
  else
89
87
  await startEntry(deps, entry);
90
88
  };
91
- export const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
92
- code: 'START_FAILED',
93
- });
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);
89
+ // C6: the envelope of a refused start; reason is the child's own words.
90
+ export const startFailed = (entry, err) => {
91
+ const reason = err.message;
92
+ const details = { code: 'START_FAILED', reason };
93
+ return fail('VALIDATION_ERROR', `${entry.id} failed to start: ${reason}`, { details });
94
+ };
95
+ // One writer per data folder (the caller holds the gate): stop the old child, start the new one.
96
+ export const swap = async (deps, entry, to, undo = async () => undefined) => {
98
97
  try {
99
98
  await halt(entry, deps.drainMs);
100
99
  entry.lane = await launchFor(deps, entry, to.install, to.values, to.dir);
101
100
  Object.assign(entry, { state: 'running', error: undefined });
101
+ resetRestarts(entry);
102
102
  }
103
103
  catch (err) {
104
+ await undo();
104
105
  await restore(deps, entry);
105
106
  throw startFailed(entry, err);
106
107
  }
107
- finally {
108
- release();
109
- }
110
- };
111
- // Detached first, so its exit is not a failure; then drained and stopped.
112
- export const halt = async (entry, drainMs) => {
113
- const lane = entry.lane;
114
- entry.lane = undefined;
115
- await retire(lane, drainMs);
116
108
  };
@@ -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,4 @@
1
1
  export declare const DATA_DIR_LOCKED = "DATA_DIR_LOCKED";
2
- export declare const lockDataDir: (dataDir: string) => Promise<() => Promise<void>>;
2
+ export declare const EMPTY_LOCK_MS = 1000;
3
+ export declare const clearOldLock: (lock: string) => Promise<void>;
4
+ export declare const lockDataDir: (dataDir: string, lock?: string) => Promise<() => Promise<void>>;
@@ -1,54 +1,106 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { rmSync } from 'node:fs';
3
- import { link, readFile, rename, unlink, writeFile } from 'node:fs/promises';
2
+ import { readFileSync, rmSync } from 'node:fs';
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();
8
+ // Linux: an exited child not reaped yet (state Z) answers kill(0) but holds nothing.
9
+ const zombie = (pid) => {
10
+ if (process.platform !== 'linux')
11
+ return false;
12
+ try {
13
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
14
+ return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ };
7
20
  const alive = (pid) => {
8
21
  try {
9
- return process.kill(pid, 0);
22
+ return process.kill(pid, 0) && !zombie(pid);
10
23
  }
11
24
  catch (err) {
12
25
  return err.code === 'EPERM';
13
26
  }
14
27
  };
15
- const holder = async (file) => Number(await readFile(file, 'utf8').catch(() => '0'));
28
+ // A lock made with wx is empty until its pid is written (slow on a network volume): being written
29
+ // for EMPTY_LOCK_MS, then stale.
30
+ export const EMPTY_LOCK_MS = 1_000;
31
+ const pidIn = (file) => readFile(file, 'utf8').catch(() => '0');
32
+ const holder = async (file) => {
33
+ const until = Date.now() + EMPTY_LOCK_MS;
34
+ let pid = await pidIn(file);
35
+ while (pid === '' && Date.now() < until) {
36
+ await sleep(25);
37
+ pid = await pidIn(file);
38
+ }
39
+ return Number(pid);
40
+ };
16
41
  const live = (lock, pid) => pid === process.pid ? held.has(lock) : pid > 0 && alive(pid);
17
- const locked = (lock, pid) => Object.assign(new Error(`${lock.slice(0, -5)} is open in process ${pid}`), {
42
+ const locked = (lock, pid) => Object.assign(new Error(`${lock.replace(/[/\\]?(store)?\.lock$/, '')} is open in process ${pid}`), {
18
43
  code: DATA_DIR_LOCKED,
44
+ pid,
19
45
  });
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));
46
+ const exists = (err) => err.code === 'EEXIST';
47
+ // No hard links on the volume (some network or FUSE mounts): an exclusive create, then the pid.
48
+ const create = async (lock, pid) => {
25
49
  try {
26
- await link(tmp, lock);
27
- held.add(lock);
50
+ await writeFile(lock, String(pid), { flag: 'wx' });
28
51
  return true;
29
52
  }
30
53
  catch (err) {
31
- if (err.code !== 'EEXIST')
54
+ if (!exists(err))
32
55
  throw err;
33
56
  return false;
34
57
  }
58
+ };
59
+ // The lock file at once (a link of a full file), or by create where links fail; false: it exists.
60
+ const place = async (from, lock, pid) => {
61
+ try {
62
+ await link(from, lock);
63
+ return true;
64
+ }
65
+ catch (err) {
66
+ return exists(err) ? false : create(lock, pid);
67
+ }
68
+ };
69
+ const unique = (file) => `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
70
+ // A full lock file appears at once or not at all: written aside, then linked (fails if one exists).
71
+ const take = async (lock) => {
72
+ const tmp = unique(lock);
73
+ await writeFile(tmp, String(process.pid));
74
+ try {
75
+ const taken = await place(tmp, lock, process.pid);
76
+ if (taken)
77
+ held.add(lock);
78
+ return taken;
79
+ }
35
80
  finally {
36
81
  await unlink(tmp).catch(() => undefined);
37
82
  }
38
83
  };
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);
84
+ // A guard left by a breaker that died is removed and taken once more.
85
+ const takeDeadGuard = async (guard) => {
86
+ if (live(guard, await holder(guard)))
87
+ return false;
88
+ await unlink(guard).catch(() => undefined);
89
+ return take(guard);
90
+ };
91
+ // One breaker at a time (<lock>.break): the lock is removed only while it still names the dead pid.
92
+ const breakStale = async (lock, pid) => {
93
+ const guard = `${lock}.break`;
94
+ if (!(await take(guard)) && !(await takeDeadGuard(guard)))
95
+ throw locked(lock, await holder(guard));
96
+ try {
97
+ if ((await holder(lock)) === pid)
98
+ await unlink(lock).catch(() => undefined);
99
+ }
100
+ finally {
101
+ rmSync(guard, { force: true });
102
+ held.delete(guard);
50
103
  }
51
- await unlink(moved);
52
104
  };
53
105
  const turns = new Map();
54
106
  // One taker per lock in this process: none sees our pid in the file before it is in held.
@@ -59,19 +111,26 @@ const inTurn = (lock, fn) => {
59
111
  void tail.then(() => turns.get(lock) === tail && turns.delete(lock));
60
112
  return run;
61
113
  };
114
+ // A lock of an older kit (beside the folder, out of a sealed child's reach): dead is removed, live refuses.
115
+ export const clearOldLock = async (lock) => {
116
+ const pid = await holder(lock);
117
+ if (pid > 0 && live(lock, pid))
118
+ throw locked(lock, pid);
119
+ if (pid > 0)
120
+ await unlink(lock).catch(() => undefined);
121
+ };
62
122
  const acquire = async (lock) => {
63
123
  if (await take(lock))
64
124
  return;
65
125
  const pid = await holder(lock);
66
126
  if (live(lock, pid))
67
127
  throw locked(lock, pid);
68
- await clearStale(lock, pid);
128
+ await breakStale(lock, pid);
69
129
  if (!(await take(lock)))
70
130
  throw locked(lock, await holder(lock));
71
131
  };
72
- // PGlite has one writer per folder: <dataDir>.lock holds the pid; a dead holder's lock is taken over.
73
- export const lockDataDir = async (dataDir) => {
74
- const lock = `${dataDir}.lock`;
132
+ // PGlite has one writer per folder: the lock (<dataDir>.lock unless given) holds the pid; a dead holder's lock is taken over.
133
+ export const lockDataDir = async (dataDir, lock = `${dataDir}.lock`) => {
75
134
  await inTurn(lock, () => acquire(lock));
76
135
  // Sync, so no other taker in this process sees the file without its entry in held.
77
136
  return async () => {
@@ -1,15 +1,17 @@
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;
7
6
  port: number;
8
7
  bind: string;
9
8
  dataDir: string;
9
+ runDir: string;
10
10
  settings: Record<string, unknown>;
11
11
  secretsDir: string;
12
12
  origin: string;
13
+ drainMs: number;
14
+ storeOpenMs: number;
13
15
  };
14
16
  export declare const guardOf: (env: Env, { bind, dir }: {
15
17
  bind: string;
@@ -5,21 +5,29 @@ import { readOpenapi } from '../discovery/openapi.js';
5
5
  import {} from '../log/log.js';
6
6
  import {} from '../manifest/manifest.schema.js';
7
7
  import { portFromEnv } from '../runtime/build-info.js';
8
+ import { GRACE_MS } from '../server/serve.js';
9
+ import { CONTAINER_PORT } from '../tool/container-recipe.js';
8
10
  import {} from './host-extension.js';
9
- export const HOST_PORT = 8080;
11
+ import { STORE_OPEN_MS } from './host-store.js';
10
12
  export const BIND_REFUSED = 'AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off';
11
13
  const TOKEN_ENV = ['AGENTAGE_ISSUER', 'AGENTAGE_AUDIENCE', 'AGENTAGE_ORIGIN'];
14
+ // A limit: a positive integer of ms, else the default.
15
+ const msOf = (value = '', fallback) => /^[1-9][0-9]*$/.test(value) ? Number(value) : fallback;
12
16
  // The entry's env with its defaults: port 8080, the current folder, loopback.
13
17
  export const hostEnvOf = (env) => {
14
- const port = portFromEnv(env, HOST_PORT);
18
+ const port = portFromEnv(env, CONTAINER_PORT);
15
19
  return {
16
20
  dir: env['AGENTAGE_EXTENSION_DIR'] || process.cwd(),
17
21
  port,
18
22
  bind: env['AGENTAGE_HOST_BIND'] === 'all' ? '0.0.0.0' : '127.0.0.1',
19
23
  dataDir: env['AGENTAGE_DATA_DIR'] ?? '',
24
+ // C2: the daemon's run/{id}; the store lock goes there (a sealed child cannot write beside data/{id}).
25
+ runDir: env['AGENTAGE_RUN_DIR'] ?? '',
20
26
  settings: env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {},
21
27
  secretsDir: env['AGENTAGE_SECRETS_DIR'] || SECRETS_DIR,
22
28
  origin: env['AGENTAGE_ORIGIN'] || `http://127.0.0.1${port ? `:${port}` : ''}`,
29
+ drainMs: msOf(env['AGENTAGE_DRAIN_MS'], GRACE_MS),
30
+ storeOpenMs: msOf(env['AGENTAGE_STORE_OPEN_MS'], STORE_OPEN_MS),
23
31
  };
24
32
  };
25
33
  // Loopback: no token check. Every address: the cloud part's check, or an explicit AGENTAGE_HOST_AUTH=off.
@@ -1,18 +1,25 @@
1
1
  import { type Express } from 'express';
2
+ import { type BuildInfo } from '../discovery/discovery.js';
2
3
  import { type HealthBody } from '../health/health.schema.js';
3
4
  import { type Log } from '../log/log.js';
4
5
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
6
+ import { type HostPartKind } from '../manifest/parts.js';
5
7
  import { type PartAppBase } from '../server/app.js';
6
8
  export interface HostOptions {
7
9
  dataDir: string;
10
+ runDir?: string;
8
11
  settings?: Record<string, unknown>;
9
12
  secrets?: Record<string, string>;
10
13
  onExit?: () => void;
11
14
  origin?: string;
15
+ localOnly?: boolean;
16
+ localPorts?: number[];
17
+ storeOpenMs?: number;
12
18
  }
13
19
  export interface HostedExtension {
14
20
  id: string;
15
21
  version: string;
22
+ parts: HostPartKind[];
16
23
  app: Express;
17
24
  stop(): Promise<void>;
18
25
  health(): Promise<HealthBody>;
@@ -20,6 +27,7 @@ export interface HostedExtension {
20
27
  export interface HostExtras {
21
28
  secretsDir?: string;
22
29
  guard?: (pkg: ExtensionPackage, log: Log) => Promise<Partial<PartAppBase>>;
30
+ build?: BuildInfo;
23
31
  }
24
32
  export declare const hostWith: (dir: string, opts: HostOptions, extras: HostExtras) => Promise<HostedExtension>;
25
33
  export declare const hostExtension: (dir: string, opts: HostOptions) => Promise<HostedExtension>;
@@ -1,21 +1,19 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import {} from 'express';
3
- import { createContext } from '../context/context.js';
4
- import { readSecrets, secretsFrom } from '../context/secrets.js';
5
- import { settingsOf } from '../context/settings.js';
6
- import { readOpenapi } from '../discovery/openapi.js';
3
+ import {} from '../discovery/discovery.js';
7
4
  import { healthBody } from '../health/health.js';
8
5
  import {} from '../health/health.schema.js';
9
6
  import { createLog } from '../log/log.js';
10
7
  import {} from '../manifest/manifest.schema.js';
11
- import { normalizeParts } from '../manifest/parts.js';
8
+ import {} from '../manifest/parts.js';
12
9
  import { readManifest } from '../manifest/read-manifest.js';
13
10
  import { buildInfoFromEnv } from '../runtime/build-info.js';
14
- import { RUNNERS } from '../runtime/part-runners.js';
15
- import { createPartApp } from '../server/app.js';
11
+ import {} from '../server/app.js';
16
12
  import { storeCheck } from '../store/store.js';
17
- import {} from '../store/pglite-store.js';
18
- import { openHostStore } from './host-store.js';
13
+ import { hostClockRate } from '../worker/clock.js';
14
+ import { localOnly } from './daemon/guard.js';
15
+ import { hostPartsOf } from './host-parts.js';
16
+ import { openHostStore, STORE_OPEN_MS } from './host-store.js';
19
17
  const once = (fn) => {
20
18
  let done = false;
21
19
  return () => {
@@ -25,62 +23,49 @@ const once = (fn) => {
25
23
  fn();
26
24
  };
27
25
  };
28
- const secretsOf = ({ pkg, opts, extras }) => extras.secretsDir
29
- ? readSecrets(pkg, 'api', extras.secretsDir)
30
- : secretsFrom(pkg, 'api', async (name) => opts.secrets?.[name] ?? '');
31
- // createContext with the host's values: settings and secrets as given, no platform.
32
- const contextOf = async (h, checks) => createContext({
33
- pkg: h.pkg,
34
- part: 'api',
35
- origin: h.opts.origin ?? 'http://127.0.0.1',
36
- commit: buildInfoFromEnv({}).commit,
37
- log: h.log,
38
- settings: settingsOf(h.pkg, h.opts.settings ?? {}, h.log),
39
- store: h.store,
40
- secrets: await secretsOf(h),
41
- checks,
42
- onExit: h.onExit,
43
- });
44
- // The api part of the package; a package without one serves /health only.
45
- const appOf = async (h, base) => {
46
- if (!normalizeParts(h.pkg.agentage.parts).code.api)
47
- return createPartApp({ ...base, part: 'api', mount: () => undefined });
48
- const ctx = await contextOf(h, base.checks ?? {});
49
- const openapi = await readOpenapi(h.dir);
50
- return (await RUNNERS.api({ dir: h.dir, pkg: h.pkg, env: {}, ctx: () => ctx, base, openapi }))
51
- .app;
52
- };
53
26
  const baseOf = async (h) => {
54
27
  const guard = (await h.extras.guard?.(h.pkg, h.log)) ?? {};
55
28
  const checks = { ...(h.store && { store: storeCheck(h.store) }), ...guard.checks };
56
29
  const resolved = { instance: randomBytes(4).toString('hex'), startedAt: Date.now() };
57
- const build = buildInfoFromEnv({});
58
- return { pkg: h.pkg, log: h.log, build, onExit: h.onExit, ...guard, checks, ...resolved };
30
+ const clockRate = hostClockRate();
31
+ const guards = h.opts.localOnly ? [localOnly(undefined, h.opts.localPorts)] : undefined;
32
+ const { pkg, log, build, onExit } = h;
33
+ return { pkg, log, build, onExit, guards, ...guard, checks, clockRate, ...resolved };
59
34
  };
60
- const hostedOf = (h, app, base) => {
35
+ // The jobs stop before the store closes: a tick never writes to a closed store.
36
+ const hostedOf = (h, hosted, base) => {
61
37
  const { id } = h.pkg.agentage;
62
38
  const { version } = h.pkg;
63
- const { instance = '', startedAt = 0, build, checks } = base;
64
- const health = () => healthBody({ extension: id, part: 'api', version, build, checks, instance, startedAt });
39
+ const { app, parts } = hosted;
40
+ const { instance = '', startedAt = 0, build, checks, clockRate } = base;
41
+ const at = { instance, startedAt, clockRate };
42
+ const health = () => healthBody({ extension: id, part: 'api', parts, version, build, checks, ...at });
65
43
  let stopped;
66
- const stop = () => (stopped ??= h.store ? h.store.close() : Promise.resolve());
67
- return { id, version, app, health, stop };
44
+ const close = () => (hosted.stop(), h.store ? h.store.close() : Promise.resolve());
45
+ const stop = () => (stopped ??= close());
46
+ return { id, version, parts, app, health, stop };
68
47
  };
69
48
  // hostExtension with the extras of the entry (dist/host/main.js).
70
49
  export const hostWith = async (dir, opts, extras) => {
71
50
  const pkg = await readManifest(dir);
72
51
  const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
73
- const store = await openHostStore(dir, pkg, opts.dataDir, log);
52
+ const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
53
+ const at = { dir, dataDir: opts.dataDir, runDir: opts.runDir, openMs };
54
+ const store = await openHostStore(pkg, at, log);
74
55
  const onExit = once(opts.onExit ?? (() => undefined));
75
- const h = { dir, pkg, log, opts, extras, store, onExit };
56
+ const build = extras.build ?? buildInfoFromEnv({});
57
+ const h = { dir, pkg, log, opts, extras, store, onExit, build };
76
58
  try {
77
59
  const base = await baseOf(h);
78
- return hostedOf(h, await appOf(h, base), base);
60
+ const hosted = await hostPartsOf(h, base);
61
+ // After every create and the store open: the migrations ran or a job's first query waits on them.
62
+ hosted.start();
63
+ return hostedOf(h, hosted, base);
79
64
  }
80
65
  catch (err) {
81
66
  await store?.close();
82
67
  throw err;
83
68
  }
84
69
  };
85
- // One extension in this process: its api at /api/{id}/*, no token check, its own settings, secrets, store and log.
70
+ // One extension in this process: api at /api/{id}/*, mcp at /mcp/{id}, the worker jobs, one store, no token check.
86
71
  export const hostExtension = (dir, opts) => hostWith(dir, opts, {});