@parcha/agentrun-serve 0.1.0-beta.32 → 0.1.0-beta.33

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 (163) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +78 -46
  3. package/dist/adapters.d.ts +0 -3
  4. package/dist/adapters.js +0 -7
  5. package/dist/agents.d.ts +1 -1
  6. package/dist/api-only.d.ts +14 -0
  7. package/dist/api-only.js +33 -0
  8. package/dist/archil-routes.d.ts +1 -1
  9. package/dist/box-egress-vm.d.ts +0 -8
  10. package/dist/box-egress-vm.js +0 -10
  11. package/dist/box-egress.d.ts +0 -4
  12. package/dist/box-egress.js +1 -16
  13. package/dist/box-paths.d.ts +25 -2
  14. package/dist/box-paths.js +79 -11
  15. package/dist/box-relay.d.ts +0 -11
  16. package/dist/box-relay.js +0 -20
  17. package/dist/box-settings.d.ts +46 -0
  18. package/dist/box-settings.js +107 -0
  19. package/dist/boxes.d.ts +4 -1
  20. package/dist/browser-cost.js +2 -1
  21. package/dist/browser-person.d.ts +0 -2
  22. package/dist/browser-person.js +0 -2
  23. package/dist/budget.d.ts +0 -4
  24. package/dist/budget.js +0 -7
  25. package/dist/cap.d.ts +0 -7
  26. package/dist/cap.js +0 -22
  27. package/dist/cli.js +23 -8
  28. package/dist/computers.d.ts +1 -1
  29. package/dist/console/assets/index-Dn0ngwG9.js +535 -0
  30. package/dist/console/assets/index-DvW6Aled.css +1 -0
  31. package/dist/console/index.html +2 -2
  32. package/dist/daytona-api.d.ts +0 -11
  33. package/dist/daytona-api.js +1 -82
  34. package/dist/docker-host-addresses.d.ts +37 -0
  35. package/dist/docker-host-addresses.js +110 -0
  36. package/dist/files.d.ts +0 -8
  37. package/dist/files.js +0 -17
  38. package/dist/github-connection.d.ts +1 -1
  39. package/dist/github-connection.js +1 -1
  40. package/dist/harness-install.d.ts +23 -0
  41. package/dist/harness-install.js +99 -4
  42. package/dist/harness.d.ts +4 -3
  43. package/dist/harness.js +16 -1
  44. package/dist/import.js +52 -13
  45. package/dist/learn/secrets.d.ts +2 -1
  46. package/dist/learn/secrets.js +19 -6
  47. package/dist/learned-workflow.d.ts +5 -4
  48. package/dist/learned-workflow.js +6 -3
  49. package/dist/learning-routes.d.ts +9 -46
  50. package/dist/learning-routes.js +25 -29
  51. package/dist/learning-run.d.ts +4 -231
  52. package/dist/learning-run.js +7 -651
  53. package/dist/live/translate.js +1 -1
  54. package/dist/mcp-gateway.d.ts +0 -3
  55. package/dist/mcp-gateway.js +0 -13
  56. package/dist/mcp-probe.d.ts +2 -2
  57. package/dist/mcp-probe.js +2 -2
  58. package/dist/mcp-servers-store.js +1 -1
  59. package/dist/openapi.js +3 -3
  60. package/dist/page.js +3 -1
  61. package/dist/paid-calls.js +3 -2
  62. package/dist/pause.d.ts +0 -2
  63. package/dist/pause.js +1 -8
  64. package/dist/place.d.ts +0 -5
  65. package/dist/place.js +0 -10
  66. package/dist/print.d.ts +2 -1
  67. package/dist/print.js +4 -2
  68. package/dist/run-db.d.ts +0 -2
  69. package/dist/run-db.js +0 -4
  70. package/dist/run-learning-served.d.ts +38 -0
  71. package/dist/run-learning-served.js +9 -0
  72. package/dist/run-secrets.d.ts +33 -0
  73. package/dist/run-secrets.js +53 -0
  74. package/dist/run-timeline-served.js +5 -2
  75. package/dist/run-view.d.ts +5 -9
  76. package/dist/run-view.js +4 -22
  77. package/dist/runner/adapter-loop.d.ts +8 -2
  78. package/dist/runner/adapter-loop.js +44 -12
  79. package/dist/runner/adapter-run-spec.d.ts +8 -0
  80. package/dist/runner/adapter-run-spec.js +6 -5
  81. package/dist/runner/adapters/pi.d.ts +4 -0
  82. package/dist/runner/adapters/pi.js +4 -1
  83. package/dist/runner/beside.js +19 -8
  84. package/dist/runner/claim-secrets.js +1 -1
  85. package/dist/runner/cli-run-spec.js +15 -1
  86. package/dist/runner/journal-kinds.d.ts +6 -0
  87. package/dist/runner/live-ticker.d.ts +1 -1
  88. package/dist/runner/live-ticker.js +28 -4
  89. package/dist/runner/loop-contract.d.ts +3 -2
  90. package/dist/runner/main.d.ts +11 -4
  91. package/dist/runner/main.js +39 -10
  92. package/dist/runner/mcp-claim.d.ts +1 -1
  93. package/dist/runner/mcp-claim.js +1 -1
  94. package/dist/runner/model-route.js +21 -2
  95. package/dist/runner/redact.d.ts +8 -2
  96. package/dist/runner/redact.js +11 -2
  97. package/dist/runner/workflow-spec.js +5 -9
  98. package/dist/runs-over-store.d.ts +1 -1
  99. package/dist/runs-over-store.js +16 -5
  100. package/dist/seal-key.d.ts +54 -15
  101. package/dist/seal-key.js +272 -84
  102. package/dist/sealed-settings.d.ts +2 -2
  103. package/dist/sealed-settings.js +3 -10
  104. package/dist/secrets.d.ts +2 -10
  105. package/dist/secrets.js +21 -17
  106. package/dist/server-secrets-store.js +1 -1
  107. package/dist/server-secrets.js +3 -0
  108. package/dist/server.d.ts +10 -6
  109. package/dist/server.js +89 -41
  110. package/dist/store/index.d.ts +1 -1
  111. package/dist/store/index.js +1 -1
  112. package/dist/store/open.d.ts +12 -2
  113. package/dist/store/open.js +23 -3
  114. package/dist/store/postgres/migrate.js +18 -1
  115. package/dist/store/sqlite/store.js +23 -8
  116. package/dist/store/store.d.ts +3 -0
  117. package/dist/store-reads/journal.d.ts +16 -0
  118. package/dist/store-reads/journal.js +82 -6
  119. package/dist/store-view.js +38 -5
  120. package/dist/tool-keys.d.ts +4 -3
  121. package/dist/tool-keys.js +7 -4
  122. package/dist/tools.d.ts +1 -1
  123. package/dist/tools.js +4 -1
  124. package/dist/trigger-schedule.js +2 -1
  125. package/dist/trigger-secrets-shown.js +5 -1
  126. package/dist/workspace/computer-deps.d.ts +29 -0
  127. package/dist/workspace/computer-deps.js +48 -1
  128. package/dist/workspace/computer-for-claim.d.ts +7 -3
  129. package/dist/workspace/computer-for-claim.js +1 -1
  130. package/dist/workspace/computer-providers.d.ts +6 -2
  131. package/dist/workspace/computer-providers.js +1 -1
  132. package/dist/workspace/index.d.ts +1 -1
  133. package/dist/workspace/index.js +1 -1
  134. package/dist/workspace.d.ts +0 -3
  135. package/dist/workspace.js +0 -3
  136. package/launcher/agentrun-serve +6 -33
  137. package/package.json +14 -14
  138. package/templates/inbound-lead/agent.md +1 -1
  139. package/templates/kyb/agent.md +1 -1
  140. package/dist/app.d.ts +0 -5
  141. package/dist/app.js +0 -514
  142. package/dist/bounds.d.ts +0 -26
  143. package/dist/bounds.js +0 -137
  144. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  145. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  146. package/dist/content-filter.d.ts +0 -7
  147. package/dist/content-filter.js +0 -23
  148. package/dist/disk.d.ts +0 -33
  149. package/dist/disk.js +0 -85
  150. package/dist/door-line.d.ts +0 -23
  151. package/dist/door-line.js +0 -83
  152. package/dist/harness-app.d.ts +0 -69
  153. package/dist/harness-app.js +0 -1162
  154. package/dist/request-start.d.ts +0 -27
  155. package/dist/request-start.js +0 -381
  156. package/dist/run-box.d.ts +0 -205
  157. package/dist/run-box.js +0 -661
  158. package/dist/run-holder.d.ts +0 -52
  159. package/dist/run-holder.js +0 -139
  160. package/dist/runs.d.ts +0 -1200
  161. package/dist/runs.js +0 -4103
  162. package/dist/served-only.d.ts +0 -5
  163. package/dist/served-only.js +0 -12
package/dist/seal-key.js CHANGED
@@ -1,26 +1,47 @@
1
1
  // The seal key every secret is kept under (tool keys, MCP credentials, sign-ins, trigger secrets: store/seal.ts). The
2
- // server never starts without one: AGENTRUN_SEAL_KEY as it was handed (the launcher's pipe, or the environment), else
3
- // the one in agentrun/seal.key under the config home (XDG_CONFIG_HOME, else ~/.config), made there at the first start.
4
- // The same rules as the launcher's (launcher/agentrun-serve):
2
+ // server never starts without one: AGENTRUN_SEAL_KEY as it was handed (the launcher's pipe, or the environment), else the
3
+ // one in seal/seal.key in the data directory, beside the store, made there at the server's first start. There is no other
4
+ // place a key is read from. It lives and dies with the data (a disk, a volume): a copy of the data directory is a copy of
5
+ // the secrets, so it is backed up with them.
5
6
  // - made as 32 random bytes in base64, 0600, in a directory of its own that is 0700, written whole beside its name and
6
7
  // then linked to it, so two starts at once read one key, and only its path is ever printed;
7
8
  // - a plain mkdir's directory (0755) with no key yet, this user's own, is tightened to 0700 before the key is made;
8
- // - a key or a directory another user can read is refused, never changed; a linked directory is refused, never followed.
9
- // It is outside the data directory on purpose: a copy of that holds the secrets as ciphertext alone.
10
- import { randomBytes } from "node:crypto";
11
- import { chmodSync, closeSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
9
+ // - a key or a directory another user can read is refused, never changed; a linked directory, or one another user owns,
10
+ // is refused, never followed or written into.
11
+ // The store records the key's fingerprint (an HMAC of a fixed label under the key: never the key, nor a hash of it alone),
12
+ // and every process that opens the store (the server, a runner, the `import` command) checks the key it holds against it
13
+ // (bootSealKey). A store whose secrets were sealed with another key is refused, in words, and no key is ever made over
14
+ // sealed secrets, in the store or beside it in the data directory: a lost key file is not replaced by a new one. A store
15
+ // with no fingerprint takes a key that opens every value it keeps sealed, or any key when it keeps none. The server's
16
+ // start makes a key and records it (and the import's, which sets a data directory up as the server does); a runner reads
17
+ // one and checks it, and never makes or records one. Several data directories in one process each keep their own key.
18
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
19
+ import { chmodSync, closeSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, writeSync } from "node:fs";
12
20
  import { join } from "node:path";
21
+ import { unseal } from "@parcha/pi-durable-agent";
13
22
  import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
14
- import { handedSecret, holdMadeSecret } from "./secrets.js";
15
- export const SEAL_KEY_DIR = "agentrun";
23
+ import { handedSecret, holdSealKey } from "./secrets.js";
24
+ import { webhookSecretIn } from "./webhooks.js";
25
+ /** The seal key's own directory in the data directory, and its file there. */
26
+ export const SEAL_KEY_DIR = "seal";
16
27
  export const SEAL_KEY_FILE = "seal.key";
28
+ /** The store setting that records the key's fingerprint. */
29
+ export const SEAL_KEY_SETTING = "seal_key";
30
+ /** The fixed label the fingerprint is an HMAC of, under the key. */
31
+ const FINGERPRINT_LABEL = "agentrun seal key fingerprint v1";
32
+ /** The refusal of a store whose secrets another key sealed, word for word. */
33
+ export const SEALED_ELSEWHERE = `this store's secrets were sealed with another key; hand the server the original ${SEAL_KEY_ENV}`;
17
34
  /** The server has no seal key it can use, in words: it does not start. */
18
35
  export class SealKeyRefused extends Error {
19
36
  name = "SealKeyRefused";
20
37
  }
21
- /** The config home a seal key is kept under: XDG_CONFIG_HOME, else ~/.config; undefined with neither. */
22
- export const sealKeyHome = (env) => env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, ".config") : undefined);
23
- const HOW = `Hand the server ${SEAL_KEY_ENV} (32 random bytes in base64, e.g. \`openssl rand -base64 32\`), or let it keep one in ${SEAL_KEY_DIR}/${SEAL_KEY_FILE} under $XDG_CONFIG_HOME (~/.config by default), made at the first start.`;
38
+ /** The key held is not the one the store's secrets were sealed with: it does not start. */
39
+ export class SealKeyNotTheStores extends SealKeyRefused {
40
+ name = "SealKeyNotTheStores";
41
+ }
42
+ /** Where the data directory `dataDir` keeps its seal key. */
43
+ export const sealKeyPath = (dataDir) => join(dataDir, SEAL_KEY_DIR, SEAL_KEY_FILE);
44
+ const HOW = `Hand the server ${SEAL_KEY_ENV} (32 random bytes in base64, e.g. \`openssl rand -base64 32\`), or let it keep one in ${SEAL_KEY_DIR}/${SEAL_KEY_FILE} in its data directory, made at the first start.`;
24
45
  const refused = (why) => new SealKeyRefused(`No seal key: ${why}. ${HOW}`);
25
46
  function lstatOf(path) {
26
47
  try {
@@ -37,105 +58,272 @@ function lstatOf(path) {
37
58
  /** No group or other permission bits: only its owner can read it. */
38
59
  const ownerOnly = (stats) => (stats.mode & 0o077) === 0;
39
60
  const mine = (stats) => typeof process.getuid !== "function" || stats.uid === process.getuid();
40
- /**
41
- * The server's seal key: `given` (AGENTRUN_SEAL_KEY as it was handed) when set, else the one kept under `configHome`,
42
- * made there at the first start. Throws SealKeyRefused, in words, when there is none it can use: the server does not start.
43
- */
44
- export function ensureSealKey(given, { configHome }) {
45
- if (given) {
46
- const key = sealKeyOf(given);
47
- if (!key)
48
- throw refused(`${SEAL_KEY_ENV} is set but is not 32 bytes in base64`);
49
- return { key, text: given, path: null, generated: false };
61
+ const linked = (dir) => refused(`${dir} is a link, and a seal key's directory is never followed through one: make it a directory of its own (mode 0700)`);
62
+ /** The key kept in `dir`, checked: undefined when there is none (no directory, or no file in it). Throws SealKeyRefused
63
+ * for a linked directory, a key or directory another user can read, or a file that holds no key: never changed. */
64
+ function keptIn(dir) {
65
+ const file = join(dir, SEAL_KEY_FILE);
66
+ const held = lstatOf(dir);
67
+ if (!held)
68
+ return undefined;
69
+ if (held.isSymbolicLink())
70
+ throw linked(dir);
71
+ if (!held.isDirectory())
72
+ throw refused(`${dir} is not a directory`);
73
+ const stats = lstatOf(file);
74
+ if (!stats)
75
+ return undefined;
76
+ if (!mine(held) || !ownerOnly(held)) {
77
+ throw refused(`${dir} can be read by another user, or is not this user's: make it 0700 (chmod 700 ${dir}); it is never changed for you once a key is in it`);
50
78
  }
51
- if (!configHome)
52
- throw refused(`${SEAL_KEY_ENV} is not set, and there is no config directory to keep one in (XDG_CONFIG_HOME or HOME)`);
53
- const dir = join(configHome, SEAL_KEY_DIR);
79
+ if (!stats.isFile() || !mine(stats) || !ownerOnly(stats)) {
80
+ throw refused(`${file} is not a file only this user can read: make it 0600 (chmod 600 ${file})`);
81
+ }
82
+ const text = readFileSync(file, "utf8").split("\n")[0].trim();
83
+ const key = sealKeyOf(text);
84
+ if (!key)
85
+ throw refused(`${file} does not hold 32 bytes in base64`);
86
+ return { key, text, path: file, generated: false };
87
+ }
88
+ /** Writes `text` as the key in `dir` (made 0700, or a plain mkdir's directory of this user's tightened to it), whole
89
+ * beside its name and then linked, so a start racing another reads the one there. Whether this call wrote it. */
90
+ function writeIn(dir, text) {
54
91
  const file = join(dir, SEAL_KEY_FILE);
55
92
  const before = lstatOf(dir);
56
93
  if (before?.isSymbolicLink())
57
- throw refused(`${dir} is a link, and a seal key's directory is never followed through one: make it a directory of its own (mode 0700)`);
94
+ throw linked(dir);
58
95
  if (before && !before.isDirectory())
59
96
  throw refused(`${dir} is not a directory`);
60
- let generated = false;
61
- if (!lstatOf(file)) {
62
- // A plain mkdir's directory, this user's own, with no key yet: tightened before a key is written in it.
63
- if (before && mine(before) && !ownerOnly(before))
64
- chmodSync(dir, 0o700);
65
- if (!before) {
66
- try {
67
- mkdirSync(dir, { recursive: true, mode: 0o700 });
68
- }
69
- catch (error) {
70
- throw refused(`${dir} could not be made (${error.code ?? String(error)})`);
71
- }
72
- }
73
- const text = randomBytes(32).toString("base64");
74
- const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}`;
97
+ if (before && !mine(before))
98
+ throw refused(`${dir} is not this user's: a seal key is never written into another user's directory`);
99
+ // A plain mkdir's directory, this user's own, with no key yet: tightened before a key is written in it.
100
+ if (before && mine(before) && !ownerOnly(before))
101
+ chmodSync(dir, 0o700);
102
+ if (!before) {
75
103
  try {
76
- const fd = openSync(temp, "wx", 0o600);
77
- try {
78
- writeSync(fd, `${text}\n`);
79
- }
80
- finally {
81
- closeSync(fd);
82
- }
83
- try {
84
- linkSync(temp, file);
85
- generated = true;
86
- }
87
- catch (error) {
88
- // Another start made it first: each start reads the one there.
89
- if (error.code !== "EEXIST")
90
- throw error;
91
- }
104
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
92
105
  }
93
106
  catch (error) {
94
- throw refused(`${file} could not be written (${error.code ?? String(error)})`);
107
+ throw refused(`${dir} could not be made (${error.code ?? String(error)})`);
108
+ }
109
+ }
110
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}`;
111
+ try {
112
+ const fd = openSync(temp, "wx", 0o600);
113
+ try {
114
+ writeSync(fd, `${text}\n`);
95
115
  }
96
116
  finally {
97
- rmSync(temp, { force: true });
117
+ closeSync(fd);
118
+ }
119
+ try {
120
+ linkSync(temp, file);
121
+ return true;
122
+ }
123
+ catch (error) {
124
+ // Another start made it first: each start reads the one there.
125
+ if (error.code !== "EEXIST")
126
+ throw error;
127
+ return false;
98
128
  }
99
129
  }
100
- const held = lstatOf(dir);
101
- if (!held || held.isSymbolicLink() || !held.isDirectory() || !mine(held) || !ownerOnly(held)) {
102
- throw refused(`${dir} can be read by another user, or is not this user's: make it 0700 (chmod 700 ${dir}); it is never changed for you once a key is in it`);
130
+ catch (error) {
131
+ throw refused(`${file} could not be written (${error.code ?? String(error)})`);
103
132
  }
104
- const stats = lstatOf(file);
105
- if (!stats || !stats.isFile() || !mine(stats) || !ownerOnly(stats)) {
106
- throw refused(`${file} is not a file only this user can read: make it 0600 (chmod 600 ${file}), or remove it to have a new one made at the next start`);
133
+ finally {
134
+ rmSync(temp, { force: true });
107
135
  }
108
- const text = readFileSync(file, "utf8").split("\n")[0].trim();
109
- const key = sealKeyOf(text);
110
- if (!key)
111
- throw refused(`${file} does not hold 32 bytes in base64: remove it to have a new one made at the next start (the secrets kept under the old one will not open)`);
112
- return { key, text, path: file, generated };
136
+ }
137
+ /** The key file's rules alone, with no store to check against: `given` (AGENTRUN_SEAL_KEY as it was handed) when set,
138
+ * else the one kept in `dataDir`, made there when there is none. A start never calls this by itself: bootSealKey checks
139
+ * the key against the store first, and makes one only for a store that holds no secret. */
140
+ export function ensureSealKey(given, { dataDir }) {
141
+ if (given) {
142
+ const key = sealKeyOf(given);
143
+ if (!key)
144
+ throw refused(`${SEAL_KEY_ENV} is set but is not 32 bytes in base64`);
145
+ return { key, text: given, path: null, generated: false };
146
+ }
147
+ const dir = join(dataDir, SEAL_KEY_DIR);
148
+ const kept = keptIn(dir);
149
+ if (kept)
150
+ return kept;
151
+ const generated = writeIn(dir, randomBytes(32).toString("base64"));
152
+ const made = keptIn(dir);
153
+ if (!made)
154
+ throw refused(`${join(dir, SEAL_KEY_FILE)} could not be read back`);
155
+ return { ...made, generated };
156
+ }
157
+ /** The fingerprint the store records of `key`: an HMAC of a fixed label under it. Neither the key nor a hash of it alone. */
158
+ export const sealKeyFingerprint = (key) => createHmac("sha256", key).update(FINGERPRINT_LABEL).digest("base64url");
159
+ /** The fingerprint a store setting's value records: undefined with none, null for one that does not read. */
160
+ function recordedIn(value) {
161
+ if (value === undefined)
162
+ return undefined;
163
+ const record = value;
164
+ return record?.v === 1 && typeof record.fingerprint === "string" ? record.fingerprint : null;
165
+ }
166
+ const sameText = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
167
+ function opensUnder(key, sealed, aad) {
168
+ try {
169
+ unseal(key, Buffer.from(sealed), aad);
170
+ return true;
171
+ }
172
+ catch {
173
+ return false;
174
+ }
175
+ }
176
+ /** The values data directory `dataDir` keeps sealed beside the store, under the same key: the outbound webhook's signing
177
+ * secret (webhooks.ts) and any trigger settings file (sealed-settings.ts), each a check of whether a key opens it. */
178
+ function sealedBeside(dataDir) {
179
+ const checks = [];
180
+ if (webhookSecretIn(dataDir, {}) !== undefined)
181
+ checks.push((key) => "secret" in (webhookSecretIn(dataDir, { [SEAL_KEY_ENV]: key.toString("base64") }) ?? {}));
182
+ let names = [];
183
+ try {
184
+ names = readdirSync(dataDir);
185
+ }
186
+ catch {
187
+ // No data directory yet: nothing kept beside the store.
188
+ }
189
+ for (const name of names) {
190
+ const adapter = /^trigger-settings-(.+)\.json$/.exec(name)?.[1];
191
+ if (adapter === undefined)
192
+ continue;
193
+ let values;
194
+ try {
195
+ values = JSON.parse(readFileSync(join(dataDir, name), "utf8")).values;
196
+ }
197
+ catch {
198
+ continue;
199
+ }
200
+ if (!values || typeof values !== "object")
201
+ continue;
202
+ for (const [scope, fields] of Object.entries(values)) {
203
+ if (!fields || typeof fields !== "object")
204
+ continue;
205
+ for (const [field, sealed] of Object.entries(fields)) {
206
+ if (typeof sealed === "string")
207
+ checks.push((key) => opensUnder(key, Buffer.from(sealed, "base64"), `trigger-settings|${adapter}|${scope}|${field}`));
208
+ }
209
+ }
210
+ }
211
+ return checks;
212
+ }
213
+ async function storeSealOf(store, dataDir) {
214
+ const fingerprint = recordedIn(await store.settings.get(SEAL_KEY_SETTING));
215
+ if (fingerprint !== undefined)
216
+ return { fingerprint, sealed: [] };
217
+ const rows = (await store.sealedSecrets.all()).map((row) => (key) => opensUnder(key, row.sealed, row.aad));
218
+ return { fingerprint, sealed: [...rows, ...sealedBeside(dataDir)] };
219
+ }
220
+ const holdsSecrets = (seal) => seal.fingerprint !== undefined || seal.sealed.length > 0;
221
+ /** Whether `key` is the store's, or why not: the one its fingerprint records; with none recorded, one that opens every
222
+ * value it keeps sealed (some opening and some not is values sealed under more than one key: no key is taken over
223
+ * that), or any key for a store that keeps none. */
224
+ function notTheStoresWhy(seal, key) {
225
+ if (seal.fingerprint === null)
226
+ return ` (the store's record of its key, setting ${SEAL_KEY_SETTING}, does not read)`;
227
+ if (seal.fingerprint !== undefined)
228
+ return sameText(seal.fingerprint, sealKeyFingerprint(key)) ? undefined : "";
229
+ const shut = seal.sealed.filter((opens) => !opens(key)).length;
230
+ if (shut === 0)
231
+ return undefined;
232
+ return shut === seal.sealed.length ? "" : ` (${shut} of the ${seal.sealed.length} values it keeps sealed do not open under this key: they were sealed under more than one)`;
233
+ }
234
+ const notTheStores = (why) => new SealKeyNotTheStores(`${SEALED_ELSEWHERE}. ${why}`);
235
+ const PUT_BACK = `put the original there (mode 0600, in a 0700 directory), or hand it as ${SEAL_KEY_ENV}`;
236
+ async function sealKeyFor(store, dataDir, given, role, write) {
237
+ const kept = await storeSealOf(store, dataDir);
238
+ const dir = join(dataDir, SEAL_KEY_DIR);
239
+ const file = join(dir, SEAL_KEY_FILE);
240
+ let seal;
241
+ if (given) {
242
+ const key = sealKeyOf(given);
243
+ if (!key)
244
+ throw refused(`${SEAL_KEY_ENV} is set but is not 32 bytes in base64`);
245
+ const why = notTheStoresWhy(kept, key);
246
+ if (why !== undefined)
247
+ throw notTheStores(`The ${SEAL_KEY_ENV} handed now is not it${why}.`);
248
+ seal = { key, text: given, path: null, generated: false };
249
+ }
250
+ else {
251
+ seal = keptIn(dir);
252
+ if (seal) {
253
+ const why = notTheStoresWhy(kept, seal.key);
254
+ if (why !== undefined)
255
+ throw notTheStores(`${file} holds another key${why}: ${PUT_BACK}.`);
256
+ }
257
+ else if (holdsSecrets(kept)) {
258
+ // No key here, over a store that holds secrets: never a new one.
259
+ throw notTheStores(`There is no key in ${file}: ${PUT_BACK}.`);
260
+ }
261
+ else if (role === "runner") {
262
+ // A runner never makes a key: it reads the one the server made.
263
+ throw refused(`there is none in ${file}, and this store records none: start the server on this data directory first, which makes it, or hand ${SEAL_KEY_ENV}`);
264
+ }
265
+ else {
266
+ // A store that holds no secret: its key is made here, at the server's first start (or the import's, which sets a data
267
+ // directory up as the server does when none has); a dry run makes none, and has none.
268
+ if (!write)
269
+ return undefined;
270
+ seal = ensureSealKey(undefined, { dataDir });
271
+ }
272
+ }
273
+ if (write && role !== "runner" && kept.fingerprint === undefined) {
274
+ // Recorded once: the first server to record it wins, and one that loses to another key's record is refused.
275
+ const fingerprint = sealKeyFingerprint(seal.key);
276
+ const now = recordedIn(await store.settings.putIfAbsent(SEAL_KEY_SETTING, { v: 1, fingerprint }));
277
+ if (now === undefined || now === null || !sameText(now, fingerprint)) {
278
+ // A key this start made for a store another process recorded first seals nothing: it goes.
279
+ if (seal.generated && seal.path)
280
+ rmSync(seal.path, { force: true });
281
+ throw notTheStores("Another process recorded its key in this store first.");
282
+ }
283
+ }
284
+ return seal;
285
+ }
286
+ /** `env` (one withSecrets made) with `text` as its seal key, read by name and never enumerated, as withSecrets gives a
287
+ * secret: so what reads the key from it gets the one its start checked against its store. */
288
+ export function withSealKey(env, text) {
289
+ // A copy, every property as it is (a withSecrets secret stays unenumerable, its saved-keys mark too), the key in place of
290
+ // whatever it held.
291
+ const out = {};
292
+ for (const name of Reflect.ownKeys(env))
293
+ if (name !== SEAL_KEY_ENV)
294
+ Object.defineProperty(out, name, Object.getOwnPropertyDescriptor(env, name));
295
+ Object.defineProperty(out, SEAL_KEY_ENV, { value: text, enumerable: false, writable: false, configurable: false });
296
+ return out;
113
297
  }
114
298
  /** The line a start prints about its seal key: where it is, never the key. */
115
299
  export function sealKeyLine(seal) {
116
300
  if (!seal.path)
117
301
  return `agentrun-serve: the seal key is ${SEAL_KEY_ENV}, as it was handed`;
118
- return `agentrun-serve: ${seal.generated ? "made a new seal key" : "the seal key is"} at ${seal.path} (0600): every secret saved here opens with it alone, so keep it, and keep it apart from the data directory`;
119
- }
120
- /** The seal key every entry point boots the one way — the server, the runner and the `import` command all call this, so
121
- * there is one rule, not three copies: the key handed over (AGENTRUN_SEAL_KEY), else the one kept under the config home of
122
- * `env` (made at the first boot, only its path printed). A made key is held back as this process's own secret, so the
123
- * environment it reads next (withSecrets) carries it. Throws with the start message when there is none and none can be made.
124
- * `say` takes the made-key line (stderr by default). */
125
- export function bootSealKey(env = process.env, say = (line) => void process.stderr.write(line)) {
126
- const handed = handedSecret(SEAL_KEY_ENV);
302
+ return `agentrun-serve: ${seal.generated ? "made a new seal key" : "the seal key is"} at ${seal.path} (0600), beside the store: every secret saved here opens with it alone, so back it up with the data directory, and keep the two together`;
303
+ }
304
+ /** A refusal in the words a start says: a key that is not the store's, or none it can use. */
305
+ function startRefusal(error) {
306
+ if (error instanceof SealKeyNotTheStores)
307
+ return new SealKeyNotTheStores(`agentrun-serve does not start: ${error.message}`, { cause: error });
308
+ return new SealKeyRefused(`agentrun-serve does not start without a seal key. ${error.message}`, { cause: error });
309
+ }
310
+ export async function bootSealKey(store, dataDir, options = {}) {
311
+ const given = "given" in options ? options.given : handedSecret(SEAL_KEY_ENV);
312
+ const say = options.say ?? ((line) => void process.stderr.write(line));
127
313
  let seal;
128
314
  try {
129
- seal = ensureSealKey(handed, { configHome: sealKeyHome(env) });
315
+ seal = await sealKeyFor(store, dataDir, given, options.role ?? "server", options.write !== false);
130
316
  }
131
317
  catch (error) {
132
318
  if (error instanceof SealKeyRefused)
133
- throw new Error(`agentrun-serve does not start without a seal key. ${error.message}`, { cause: error });
319
+ throw startRefusal(error);
134
320
  throw error;
135
321
  }
136
- if (!handed)
137
- holdMadeSecret(SEAL_KEY_ENV, seal.text);
322
+ if (!seal)
323
+ return undefined;
324
+ // On this process's redaction list while it is open (secrets.ts holdSealKey); each holder passes its own key on.
325
+ const release = holdSealKey(seal.text);
138
326
  if (seal.generated)
139
327
  say(`${sealKeyLine(seal)}\n`);
140
- return seal;
328
+ return { ...seal, release };
141
329
  }
@@ -31,7 +31,7 @@ export declare class SealedSettings {
31
31
  private readonly retiredPem;
32
32
  /** Why the file does not read: nothing is made, rotated or removed, nothing it holds is read, and it is never written over. */
33
33
  private readonly unreadable?;
34
- constructor(data: string, adapterId: string, spec: SettingsSpec, key: Buffer | undefined, say: (fields: Record<string, string>) => void);
34
+ constructor(data: string, adapterId: string, spec: SettingsSpec, key: Buffer, say: (fields: Record<string, string>) => void);
35
35
  /** A new secret for `scope`'s `field` (one the spec mints), written sealed before it is answered: its only showing. */
36
36
  mint(scope: string, field: string): string;
37
37
  /** A given value for `scope`'s `field` (a sender's signing secret, a bot's token), written sealed. One under its
@@ -52,7 +52,7 @@ export declare class SealedSettings {
52
52
  * the short last one too, listed with no floor (server-secrets.ts `whole`). */
53
53
  pemValues(): string[];
54
54
  private retire;
55
- /** Why nothing can be written here (no seal key, or a file that does not read), as the refusal a write would throw;
55
+ /** Why nothing can be written here (a file that does not read), as the refusal a write would throw;
56
56
  * undefined when one can be. */
57
57
  unwritable(): ApiError | undefined;
58
58
  private writable;
@@ -1,7 +1,7 @@
1
1
  // A trigger source's sealed settings (trigger-adapter.ts `settings`): the trigger kernel's one store of them. One file
2
2
  // per adapter, DIR/trigger-settings-<adapter>.json, holding each scope's fields (the server's, or one trigger's, by its
3
- // id) sealed under the seal key (tool-keys.ts), each bound to its adapter, scope and field by its AAD. With no seal key
4
- // none is kept, never in the clear. A file that does not read is never written over: nothing is made or removed until
3
+ // id) sealed under the seal key (tool-keys.ts), each bound to its adapter, scope and field by its AAD. There is always a
4
+ // seal key (seal-key.ts), so none is kept in the clear. A file that does not read is never written over: nothing is made or removed until
5
5
  // it is fixed. A value that does not open under this server's seal key is said once, kept sealed as it is, and reads as
6
6
  // unset.
7
7
  import { readFileSync } from "node:fs";
@@ -62,13 +62,8 @@ export class SealedSettings {
62
62
  return;
63
63
  }
64
64
  this.sealed = read.sealed;
65
- if (!this.key && Object.values(this.sealed).some((fields) => Object.keys(fields).length)) {
66
- say({ condition: "trigger_settings_no_seal_key", adapter: adapterId, file: this.file, effect: `this server was handed no ${SEAL_KEY_ENV}: none of its sealed settings is read` });
67
- }
68
65
  for (const [scope, fields] of Object.entries(this.sealed)) {
69
66
  for (const [field, value] of Object.entries(fields)) {
70
- if (!this.key)
71
- continue;
72
67
  try {
73
68
  (this.opened[scope] ??= {})[field] = unseal(this.key, Buffer.from(value, "base64"), aad(adapterId, scope, field)).toString("utf8");
74
69
  }
@@ -154,7 +149,7 @@ export class SealedSettings {
154
149
  for (const secret of this.secretsOf(field, value))
155
150
  this.retired.add(secret);
156
151
  }
157
- /** Why nothing can be written here (no seal key, or a file that does not read), as the refusal a write would throw;
152
+ /** Why nothing can be written here (a file that does not read), as the refusal a write would throw;
158
153
  * undefined when one can be. */
159
154
  unwritable() {
160
155
  try {
@@ -168,8 +163,6 @@ export class SealedSettings {
168
163
  writable() {
169
164
  if (this.unreadable)
170
165
  throw new ApiError("store_unreadable", `${settingsFile(this.adapterId)} in the data directory does not read (${this.unreadable}); it is never written over, so no ${this.adapterId} trigger's secret is made or rotated. Fix it or move it away, then restart.`);
171
- if (!this.key)
172
- throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so it keeps no ${this.adapterId} trigger's secret: it never keeps one in the clear.`);
173
166
  }
174
167
  write(sealed) {
175
168
  writeDurableSync(this.file, `${JSON.stringify({ v: 1, values: sealed }, null, 2)}\n`);
package/dist/secrets.d.ts CHANGED
@@ -23,8 +23,8 @@ export type StoredKeys = (name: string) => string | undefined;
23
23
  * every other key, token, secret or password `env` names. One shorter than the checker's MIN_SECRET,
24
24
  * whitespace aside, matches too much text by chance to be refused, and is left out. */
25
25
  export declare const hostSecrets: (env: NodeJS.ProcessEnv, stored?: StoredKeys) => string[];
26
- /** Holds a secret this process made (seal-key.ts' generated seal key), read by name like one it was handed. */
27
- export declare function holdMadeSecret(name: string, value: string): void;
26
+ /** Lists `text` among this process's seal keys, for redaction alone, until the returned release is called. */
27
+ export declare function holdSealKey(text: string): () => void;
28
28
  /** A secret this process was handed (over its pipe, or in its environment), never one it made itself: what a start asks
29
29
  * to tell a handed seal key from none, so a second server in one process makes or reads its own and is not handed the
30
30
  * first one's. */
@@ -58,14 +58,6 @@ export declare function mcpCredentials(): Record<string, {
58
58
  export declare const mcpSecretValues: (credentials: Record<string, {
59
59
  headers?: Record<string, string>;
60
60
  }>) => string[];
61
- /** The pipe's MCP entry for `credentials`, to follow the secrets `handover` encodes. */
62
- export declare const mcpHandover: (credentials: Record<string, unknown>) => Buffer;
63
- /** A run's saved sign-in as its pipe carries it, after its secrets (handover). */
64
- export declare const handoverSignIn: (value: {
65
- provider: string;
66
- ref: string;
67
- save: boolean;
68
- }) => Buffer;
69
61
  /** The saved sign-in this run's process was handed over its pipe, if any: read by the browser tool alone. */
70
62
  export declare function handedSignIn(): {
71
63
  provider: string;
package/dist/secrets.js CHANGED
@@ -94,23 +94,31 @@ const SECRET_NAME = /(?:^|_)(?:KEY|TOKEN|SECRET|PASSWORD)$/i;
94
94
  * every other key, token, secret or password `env` names. One shorter than the checker's MIN_SECRET,
95
95
  * whitespace aside, matches too much text by chance to be refused, and is left out. */
96
96
  export const hostSecrets = (env, stored) => {
97
- const held = [...SECRET_NAMES.flatMap((name) => [secret(name) ?? "", stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials())];
97
+ const held = [...SECRET_NAMES.flatMap((name) => [secret(name) ?? "", stored?.(name) ?? ""]), ...mcpSecretValues(mcpCredentials()), ...sealKeys.keys()];
98
98
  const named = Object.entries(env).filter(([name]) => SECRET_NAME.test(name) && !SECRET_NAMES.includes(name)).map(([, value]) => value ?? "");
99
99
  return [...new Set([...held, ...named])].filter((value) => value.replace(/\s+/g, "").length >= MIN_SECRET);
100
100
  };
101
- /** The secrets this process made itself for want of one it was handed: the seal key a start keeps under the config home
102
- * (seal-key.ts) when none was given. Read last, after the handed and the environment's, so a given one always wins;
103
- * never in the environment, so no child inherits it. */
104
- const made = new Map();
105
- /** Holds a secret this process made (seal-key.ts' generated seal key), read by name like one it was handed. */
106
- export function holdMadeSecret(name, value) {
107
- if (!SECRET_NAMES.includes(name))
108
- throw new Error(`${name} is not a secret the launcher lists`);
109
- made.set(name, value);
101
+ /** The seal keys this process's open stores were booted with (seal-key.ts bootSealKey), by how many hold each: several
102
+ * data directories in one process each keep their own. Never read as a secret by name (each holder passes its own key
103
+ * on): only listed by hostSecrets, so what a run writes is cut of every one. */
104
+ const sealKeys = new Map();
105
+ /** Lists `text` among this process's seal keys, for redaction alone, until the returned release is called. */
106
+ export function holdSealKey(text) {
107
+ sealKeys.set(text, (sealKeys.get(text) ?? 0) + 1);
108
+ let released = false;
109
+ return () => {
110
+ if (released)
111
+ return;
112
+ released = true;
113
+ const left = (sealKeys.get(text) ?? 1) - 1;
114
+ if (left > 0)
115
+ sealKeys.set(text, left);
116
+ else
117
+ sealKeys.delete(text);
118
+ };
110
119
  }
111
- /** A secret this process was started with: as handed over, else (no launcher) as its environment has it now, else one it
112
- * made itself (holdMadeSecret). */
113
- const own = (name) => held.get(name) ?? process.env[name] ?? made.get(name);
120
+ /** A secret this process was started with: as handed over, else (no launcher) as its environment has it now. */
121
+ const own = (name) => held.get(name) ?? process.env[name];
114
122
  /** A secret this process was handed (over its pipe, or in its environment), never one it made itself: what a start asks
115
123
  * to tell a handed seal key from none, so a second server in one process makes or reads its own and is not handed the
116
124
  * first one's. */
@@ -168,10 +176,6 @@ export function mcpCredentials() {
168
176
  }
169
177
  /** Every header value of `credentials`: what a secret scan refuses. */
170
178
  export const mcpSecretValues = (credentials) => Object.values(credentials).flatMap((server) => Object.values(server.headers ?? {})).flatMap((value) => [value, value.replace(/^Bearer\s+/i, "")]);
171
- /** The pipe's MCP entry for `credentials`, to follow the secrets `handover` encodes. */
172
- export const mcpHandover = (credentials) => encode([[MCP_AUTH, JSON.stringify(credentials)]]);
173
- /** A run's saved sign-in as its pipe carries it, after its secrets (handover). */
174
- export const handoverSignIn = (value) => encode([[SIGN_IN_PAIR, JSON.stringify(value)]]);
175
179
  /** The saved sign-in this run's process was handed over its pipe, if any: read by the browser tool alone. */
176
180
  export function handedSignIn() {
177
181
  try {
@@ -35,7 +35,7 @@ export async function openServerSecretsOverStore(store, data, env, adapters, say
35
35
  secrets.add("files", () => [kept(TOKEN_FILE), kept(SESSION_SECRET_FILE)]);
36
36
  const webhook = webhookSecretIn(data, env);
37
37
  secrets.add("webhook", () => (webhook && "secret" in webhook ? [webhook.secret] : []));
38
- // The server always has its seal key (seal-key.ts ensureSealKey, at its start): no setting is ever kept in the clear.
38
+ // The server always has its seal key (seal-key.ts bootSealKey, at its start): no setting is ever kept in the clear.
39
39
  const key = sealKeyOf(env[SEAL_KEY_ENV]);
40
40
  if (!key)
41
41
  throw new Error(`the server starts with its seal key (${SEAL_KEY_ENV}), made at the first start when none is handed over`);
@@ -58,7 +58,10 @@ export function openServerSecrets(data, env, adapters, say = () => { }) {
58
58
  const leftover = join(data, "trigger-secrets.json");
59
59
  if (existsSync(leftover))
60
60
  say({ condition: "trigger_secrets_left_over", file: leftover, effect: "not read: give each webhook trigger made before a new secret with POST /v2/triggers/{id}/secret, or make it again" });
61
+ // There is always a seal key (seal-key.ts): every caller hands this one.
61
62
  const key = sealKeyOf(env[SEAL_KEY_ENV]);
63
+ if (!key)
64
+ throw new Error(`the server's own secrets open only under its seal key (${SEAL_KEY_ENV}), and none was handed`);
62
65
  const settings = new Map();
63
66
  for (const adapter of adapters) {
64
67
  if (!adapter.settings)