@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44

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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
package/dist/cli.js CHANGED
@@ -10,20 +10,21 @@ import { spawn } from "node:child_process";
10
10
  import { accessSync, chmodSync, constants as fsConstants, statSync, writeFileSync } from "node:fs";
11
11
  import { dirname, join, resolve } from "node:path";
12
12
  import { defaultData, removeOwnRecord, SERVER_FILE, writeDurableSync } from "./server-fs.js";
13
- import { startedWith } from "./adapters.js";
14
13
  import { REPEAT_MS, stopOnSignals } from "./stop-signals.js";
15
- import { canOpen } from "./host.js";
16
14
  import { resetPassword } from "./owner.js";
17
15
  import { banner } from "./print.js";
18
16
  import { parseTokens } from "./api-token.js";
19
- import { DEFAULT_PORT, fauxEnvOf, startServe } from "./server.js";
20
- import { besideRunnerOptions, besideStopping, runnerBeside } from "./runner/beside.js";
21
17
  import { apiOnlyFrom } from "./api-only.js";
18
+ import { harnessModulesOf } from "./harness-table.js";
22
19
  import { surviveClosedPipes } from "./closed-pipes.js";
20
+ import { startTelemetry } from "./telemetry.js";
21
+ // The rest of the server (server.js, the runner, the harness adapters) loads after the port is bound (listen-first.ts):
22
+ // on a slow disk that load is most of a start. Nothing above loads more than a few files.
23
+ import { DEFAULT_HOST, DEFAULT_PORT, listenFirst, urlOf } from "./listen-first.js";
23
24
  // A stdout or stderr its reader closed loses the lines written after, never the process (closed-pipes.ts): for every
24
25
  // command, the server and the runner alike.
25
26
  surviveClosedPipes();
26
- const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--open] [--faux MODULE] [--faux-browser MODULE] [--faux-github] [--allow-host NAME ...] [--max-runs N] [--drain-timeout D] [--documents DIR] [--allow-code-nodes] [--learning on|off] [--learning-budget BYTES] [--grade-model MODEL] [--no-runner]
27
+ const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--open] [--faux MODULE] [--faux-browser MODULE] [--faux-github] [--allow-host NAME ...] [--max-runs N] [--drain-timeout D] [--documents DIR] [--allow-code-nodes] [--learning on|off] [--learning-budget BYTES] [--grade-model MODEL] [--no-runner] [--harness-module MODULE ...]
27
28
  agentrun-serve reset-password [--data DIR]
28
29
  agentrun-serve validate-template DIR
29
30
  agentrun-serve eval-template DIR [--case NAME ...] [--runs N] [--server URL | --on-data DIR] [--grader-model PROVIDER/MODEL] [--report FILE] [--faux MODULE]
@@ -62,6 +63,11 @@ const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--
62
63
  notes changed last, whole, while they fit
63
64
  --grade-model MODEL the model that grades what a run proposes to learn (default AGENTRUN_SERVE_GRADE_MODEL, else the
64
65
  strong tier, AGENT_MODEL_STRONG, else each run's own model), named as the strong tier takes one
66
+ --harness-module MODULE
67
+ a harness module to add harnesses from (repeatable; default AGENTRUN_SERVE_HARNESS_MODULES, comma-
68
+ separated): a path, or a package installed with npm install --prefix DIR/harnesses PACKAGE, whose
69
+ entries(builtins) export adds harnesses of its own to this server and its runner. It never replaces
70
+ a built-in harness (pi, claude-agent, codex, opencode); one that does, or is missing, refuses the start
65
71
  --no-runner run the server alone, with no runner beside it (default: one runner beside the server); start one or
66
72
  more \`agentrun-serve runner --data DIR\` processes on the same data directory to claim and run runs;
67
73
  each holds at most --loops N runs (default AGENTRUN_MAX_RUNS, else as many pi runs as its host's
@@ -83,6 +89,10 @@ AGENTRUN_FREE_MODEL_REQUESTS (default 60) is the most requests on free models ($
83
89
  or not (ChatGPT-plan requests don't count): the next is not sent and the run fails, spend_cap_reached. stdout gets one line per request, per run start and
84
90
  end, and per refused credential; AGENTRUN_LOG=quiet leaves out the request lines.
85
91
 
92
+ AGENTRUN_TELEMETRY=0 (or DO_NOT_TRACK=1) turns off the anonymous usage counts (docs/telemetry.md): a random id, the
93
+ version, the platform and how many runs as a range, never prompts, files or keys. Off in CI and under --faux too;
94
+ AGENTRUN_TELEMETRY=debug prints each event on stderr and sends none.
95
+
86
96
  AGENTRUN_API_ONLY=1 serves the run routes alone, for a server behind its caller's backend: a run's launch, read, list,
87
97
  timeline, messages, stop, cancel, kill and cap raise, its files and uploads, an agent's Archil disk, capabilities, health
88
98
  and usage. Every other address (the page, sign-in, setup, settings, MCP, triggers and their hooks, the rest of agents)
@@ -293,6 +303,7 @@ try {
293
303
  "grade-model": { type: "string" },
294
304
  "learning-budget": { type: "string" },
295
305
  "no-runner": { type: "boolean", default: false },
306
+ "harness-module": { type: "string", multiple: true, default: [] },
296
307
  help: { type: "boolean", short: "h", default: false },
297
308
  },
298
309
  }));
@@ -373,6 +384,20 @@ catch (error) {
373
384
  process.exit(2);
374
385
  }
375
386
  const accounts = !apiOnly && process.env.AGENTRUN_ACCOUNTS !== "0";
387
+ // The address first (listen-first.ts): the port bound and named before the rest of the server loads, then answering that
388
+ // the server is warming until it takes the socket over. A port already taken is left to the start's own listen below,
389
+ // which waits for a server it replaces, as it always has: no early line then. The banner's "Open " line still means ready.
390
+ let early;
391
+ try {
392
+ early = await listenFirst({ host: values.listen ?? DEFAULT_HOST, port, data, env: process.env });
393
+ }
394
+ catch (error) {
395
+ console.error(`agentrun-serve: ${error.message}`);
396
+ process.exit(1);
397
+ }
398
+ if (early)
399
+ console.log(`Starting ${publicUrl ?? urlOf(early, values.listen ?? DEFAULT_HOST)}/ (warming: health says so and the API answers 503 until the server is ready)`);
400
+ const [{ fauxEnvOf, startServe }, { besideRunnerOptions, besideStopping, runnerBeside }, { startedWith }, { canOpen }] = await Promise.all([import("./server.js"), import("./runner/beside.js"), import("./adapters.js"), import("./host.js")]);
376
401
  // How it was started, for the hints that start it again (adapters.ts npxLine): itself and its runs read it.
377
402
  Object.assign(process.env, startedWith({ ...(values.port !== undefined ? { port: values.port } : {}), open: values.open === true }));
378
403
  let serve;
@@ -386,8 +411,10 @@ try {
386
411
  console.error(`agentrun-serve: ${error.message}`);
387
412
  process.exit(1);
388
413
  },
389
- data, port, ...(values.port === undefined ? { nextFreePort: true } : {}), ...(values.listen ? { host: values.listen } : {}), ...(given ? { token: given } : {}), ...(givenList ? { tokens: givenList } : {}), ...(values.faux ? { faux: values.faux } : {}), ...(values["faux-browser"] ? { fauxBrowser: values["faux-browser"] } : {}), ...(values["faux-github"] ? { fauxGitHub: true } : {}), allowHosts: values["allow-host"],
414
+ data, port, ...(values.port === undefined ? { nextFreePort: true } : {}), ...(early ? { listener: early } : {}), ...(values.listen ? { host: values.listen } : {}), ...(given ? { token: given } : {}), ...(givenList ? { tokens: givenList } : {}), ...(values.faux ? { faux: values.faux } : {}), ...(values["faux-browser"] ? { fauxBrowser: values["faux-browser"] } : {}), ...(values["faux-github"] ? { fauxGitHub: true } : {}), allowHosts: values["allow-host"],
390
415
  ...(values["max-runs"] !== undefined ? { maxRuns: Number(values["max-runs"]) } : {}),
416
+ // The owner's harness modules: --harness-module, else AGENTRUN_SERVE_HARNESS_MODULES (harness-table.ts).
417
+ ...(harnessModulesOf(values["harness-module"], process.env).length ? { harnessModules: harnessModulesOf(values["harness-module"], process.env) } : {}),
391
418
  ...(values["drain-timeout"] ? { drainTimeout: values["drain-timeout"] } : {}), ...(values.documents ? { documents: values.documents } : {}), ...(values["allow-code-nodes"] ? { allowCodeNodes: true } : {}), ...(values.learning !== undefined ? { learning: values.learning } : {}), ...(values["grade-model"] ? { gradeModel: values["grade-model"] } : {}), ...(budget !== undefined ? { learningBudget: Number(budget) } : {}), log: (line) => void process.stdout.write(`${line}\n`),
392
419
  // The public address is the server's with accounts on or off: the Host names it serves, the webhook URLs it gives.
393
420
  ...(publicUrl ? { publicUrl } : {}),
@@ -408,6 +435,9 @@ catch (error) {
408
435
  // (besideRunnerOptions): at most --max-runs runs at once, the rest waiting queued, and on the stop each busy run finishes
409
436
  // its turn for up to --drain-timeout.
410
437
  let runnerProc;
438
+ // Anonymous usage counts (telemetry.ts, docs/telemetry.md): off with AGENTRUN_TELEMETRY=0 or DO_NOT_TRACK=1, in CI and
439
+ // under --faux. It hears each run's end from the runner beside the server; with --no-runner it counts no runs.
440
+ const telemetry = startTelemetry({ data: resolve(data), ...(values.faux ? { faux: true } : {}) });
411
441
  const { loops, drainMs } = besideRunnerOptions(serveOptions, process.env);
412
442
  // A stop asked during the server's start starts no runner: nothing is claimed for the stop to cut.
413
443
  if (!values["no-runner"] && askedAt === undefined) {
@@ -421,7 +451,7 @@ if (!values["no-runner"] && askedAt === undefined) {
421
451
  // server's AttachHub: a paired computer's socket is in this process, so only this runner takes one (--no-runner's
422
452
  // separate runners refuse it in words). Its runs reach an MCP server on loopback only when this server is a local
423
453
  // install (Serve.localInstall).
424
- runnerProc = await runnerBeside(data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true, hub: serve.attachHub, dial: serve.dial, mcpLoopback: serve.localInstall, mcpOwn: serve.own });
454
+ runnerProc = await runnerBeside(data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true, hub: serve.attachHub, dial: serve.dial, mcpLoopback: serve.localInstall, mcpOwn: serve.own, onRunEnded: telemetry.runEnded });
425
455
  }
426
456
  catch (error) {
427
457
  console.error(`agentrun-serve: the runner could not start: ${error.message}`);
@@ -437,6 +467,9 @@ for (const line of banner({ url: serve.url, baseUrl: serve.baseUrl, data, token:
437
467
  // setup link with its code as the code was made (owner.ts).
438
468
  if (serve.setupUrl && serve.setupOpen)
439
469
  console.log(`Set your password: ${serve.setupUrl} (the first visit sets it)`);
470
+ // The notice of the anonymous counts, once, on stderr: the npx command passes stderr through and keeps stdout to itself.
471
+ if (telemetry.notice)
472
+ console.error(telemetry.notice);
440
473
  // The console's page, once the server listens: never its sign-in link, whose token would sit in the opener's arguments
441
474
  // and the browser's history.
442
475
  // API-only: there is no console, so nothing to open.
@@ -454,7 +487,8 @@ const stop = stopOnSignals({
454
487
  const busy = runnerProc?.runner.held().length ?? 0;
455
488
  if (busy > 0 && drainMs > 0)
456
489
  console.error(`agentrun-serve: stopping: waiting up to ${Math.ceil(drainMs / 1000)} s for ${busy} ${busy === 1 ? "run" : "runs"} to finish ${busy === 1 ? "its turn" : "their turns"}`);
457
- return Promise.all([runnerProc?.close() ?? Promise.resolve(), serve.close()]).then(() => undefined);
490
+ // The counts' last write (telemetry.ts) is waited for once the runner has said its last run's end.
491
+ return Promise.all([(runnerProc?.close() ?? Promise.resolve()).then(() => telemetry.close()), serve.close()]).then(() => undefined);
458
492
  },
459
493
  // The stop's deadline waits out the runner's whole close: its drain, then the stop of the loops left, so a run's end
460
494
  // and release are never cut short (besideStopping).
@@ -14,9 +14,10 @@ export type ComposioTool = {
14
14
  };
15
15
  /** A Composio call (asking): its JSON answer, or the refusal in words that name its step. */
16
16
  export type Ask = (step: string, method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown, missing?: string) => Promise<Json>;
17
- /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key, and end with
18
- * `outcome`, what the failure left (a save's: nothing was saved). */
19
- export declare function asking(control: ComposioControl, key: string, signal: AbortSignal | undefined, outcome?: string): Ask;
17
+ /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key nor a `sealed`
18
+ * value (a trigger's sealed config), and end with `outcome`, what the failure left (a save's: nothing was saved). A call
19
+ * with sealed values in play passes on none of Composio's words. */
20
+ export declare function asking(control: ComposioControl, key: string, signal: AbortSignal | undefined, outcome?: string, sealed?: readonly string[]): Ask;
20
21
  /** POST /settings/mcp-servers/composio/tools: a toolkit's actions, for the console's picker, and whether it needs no sign-in. */
21
22
  export declare function composioTools(body: unknown, control: ComposioControl, signal?: AbortSignal): Promise<{
22
23
  toolkit: string;
@@ -20,12 +20,18 @@ const MAX_TOOLS = 500;
20
20
  const WAIT_MS = 20_000;
21
21
  const text = (value) => (typeof value === "string" ? value : "");
22
22
  const issue = (field, reason, message) => ({ field, reason, message });
23
- /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key, and end with
24
- * `outcome`, what the failure left (a save's: nothing was saved). */
25
- export function asking(control, key, signal, outcome = "nothing was saved") {
23
+ /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key nor a `sealed`
24
+ * value (a trigger's sealed config), and end with `outcome`, what the failure left (a save's: nothing was saved). A call
25
+ * with sealed values in play passes on none of Composio's words. */
26
+ export function asking(control, key, signal, outcome = "nothing was saved", sealed = []) {
26
27
  const base = (control.baseUrl ?? BASE).replace(/\/+$/, "");
27
28
  const send = control.fetch ?? fetch;
28
- const scrub = (said) => said.split(key).join("[the key]").slice(0, 300);
29
+ // Composio's words may quote what it was sent, as sent, JSON-escaped or percent-encoded. With a sealed value in play
30
+ // (`sealed`) none of its words go on, as no match is sure to find every form of it; otherwise they go on with the key
31
+ // out in each of those forms.
32
+ const withheld = sealed.some(Boolean);
33
+ const forms = [...new Set([key, JSON.stringify(key).slice(1, -1), encodeURIComponent(key)])].filter(Boolean).sort((a, b) => b.length - a.length);
34
+ const scrub = (said) => forms.reduce((text, form) => text.split(form).join("[the key]"), said).slice(0, 300);
29
35
  return async (step, method, path, body, missing) => {
30
36
  let res;
31
37
  let raw;
@@ -59,6 +65,8 @@ export function asking(control, key, signal, outcome = "nothing was saved") {
59
65
  throw invalid([issue("api_key", "refused", `Composio refused the API key while ${step}: check it in Composio's dashboard.`)]);
60
66
  if (res.status === 404 && missing)
61
67
  throw invalid([issue("toolkit", "not_found", missing)]);
68
+ if (res.status >= 400 && res.status < 500 && withheld)
69
+ throw invalid([issue("body", "refused", `Composio refused the request while ${step} (HTTP ${res.status}): ${outcome}. Its answer is withheld because the request carried a sealed value.`)]);
62
70
  if (res.status >= 400 && res.status < 500)
63
71
  throw invalid([issue("body", "refused", `Composio refused the request while ${step} (${res.status})${said ? `: ${scrub(said)}` : ""}.`)]);
64
72
  throw new ApiError("upstream_failed", `Composio failed while ${step} (${res.status}): ${outcome}.`);
@@ -14,6 +14,7 @@ type Holder = {
14
14
  name: string;
15
15
  enabled: boolean;
16
16
  source: Source;
17
+ updatedAt?: number;
17
18
  };
18
19
  type Sealed = {
19
20
  get(scope: string, field: string): string | undefined;
@@ -34,7 +35,7 @@ export type ComposioTriggerDeps = {
34
35
  signal?: AbortSignal;
35
36
  say(fields: Record<string, string>): void;
36
37
  };
37
- /** An event of a toolkit as the console's form reads it. */
38
+ /** An event of a toolkit as the console's form reads it: `sealed`, the fields of its config a save seals. */
38
39
  export type ComposioEvent = {
39
40
  slug: string;
40
41
  name: string;
@@ -42,6 +43,7 @@ export type ComposioEvent = {
42
43
  instructions?: string;
43
44
  config: Json;
44
45
  polled: boolean;
46
+ sealed: string[];
45
47
  };
46
48
  export declare class ComposioTriggers implements TriggerUpstream {
47
49
  private readonly deps;
@@ -85,6 +87,19 @@ export declare class ComposioTriggers implements TriggerUpstream {
85
87
  /** The triggers that use saved server `name`: a server that has any is not deleted, nor saved off what they stand on
86
88
  * (`then`: what to do once they are gone), refused, naming them. */
87
89
  inUse(name: string, then?: string): Promise<void>;
90
+ /** At the server's start: each composio trigger kept with a credential of its config in the clear (made before the
91
+ * config was sealed) sealed now, its source rewritten (`rewrite`) as an answer shows it (shownSource: the mask in its
92
+ * place), and said with the trigger's id and the fields' names alone. Composio's instance is left as it is: it already
93
+ * holds the value. One that can't be sealed is said, still answered masked, and left for the next start. A trigger
94
+ * with nothing in the clear is passed over, so a second start does nothing. */
95
+ sealKept(rewrite: (id: string, source: Source) => Promise<void>): Promise<number>;
96
+ /** After the server's start, never holding it up: each composio trigger an earlier server kept with a value in the clear
97
+ * in a field only its event's schema marks (format: password, writeOnly: sealedSchemaFields; the name rule is
98
+ * sealKept's) sealed, as sealKept seals one. Each event's schema is read once from Composio with its server's key, its
99
+ * words withheld when the server's triggers hold sealed values. When a read fails (Composio down), that is said once,
100
+ * by a code, and those triggers are left for the next start. The rewrites run inside `around` (the store's
101
+ * secureRewrite), once, and only when there is one to make. */
102
+ sealMarked(rewrite: (id: string, source: Source, updatedAt: number | undefined, read: Source) => Promise<boolean>, around: (work: () => Promise<number>) => Promise<unknown>): Promise<void>;
88
103
  /** `step` run once the steps queued before it for the project of key `key` are done (failed or not), and before any
89
104
  * queued after it. The key is digested, never kept as it is. */
90
105
  private serial;
@@ -95,7 +110,10 @@ export declare class ComposioTriggers implements TriggerUpstream {
95
110
  private leftWith;
96
111
  /** Instance `instance` deleted on Composio or turned off, as `left` says; Composio's 404 to the delete: already gone. */
97
112
  private leave;
98
- /** Composio asked with the server's key; a failure's words end with what it left (`outcome`). */
113
+ /** The sealed config values `holders` keep here: what Composio may quote back about their instance. */
114
+ private sealedValues;
115
+ /** Composio asked with the server's key; a failure's words end with what it left (`outcome`), and pass on none of
116
+ * Composio's own with a value of `sealed` (a trigger's sealed config) in play. */
99
117
  private ask;
100
118
  private addressOf;
101
119
  /** The hook an address's path names (/v2/hooks/composio/{hook}), whatever its origin. */
@@ -15,12 +15,17 @@
15
15
  // rotate, the subscription's delete and the saved server's delete. Each reads the triggers holding what it would undo,
16
16
  // turn off or delete as they are then, so it never removes what another holds, a pause or resume sets the instance as
17
17
  // its triggers now stand, and a create re-reads its saved server before it saves, so no trigger outlives its server.
18
+ // - A config field named like a credential (trigger-composio.ts sealedConfigFields) is sealed at the create, each under
19
+ // its own scope of the same sealed settings (configScope), and the trigger keeps SEALED_MASK in its place, the field
20
+ // named in `sealed_config`: Composio's upsert alone gets the value. A PATCH that leaves it out or sends the mask keeps
21
+ // it; any other value is a change to the config, refused. The delete removes it. A trigger kept before this rule with
22
+ // its key in the clear is answered masked all the same (shownSource), and sealed at the next start (sealKept).
18
23
  // No public address (AGENTRUN_PUBLIC_URL): Composio can't reach this server, so making one is refused before Composio is
19
24
  // asked anything.
20
25
  import { createHash, randomBytes } from "node:crypto";
21
26
  import { ApiError, invalid } from "./errors.js";
22
27
  import { asking } from "./composio-preset.js";
23
- import { COMPOSIO_HOOK, COMPOSIO_SECRET, MOVE_FIELD } from "./trigger-composio.js";
28
+ import { COMPOSIO_HOOK, COMPOSIO_SECRET, CONFIG_SECRET, CONFIG_UNLISTED, configScope, configSecrets, MOVE_FIELD, SEALED_FIELD, SEALED_MASK, sealableValue, sealedConfigFields, sealedKept, sealedSchemaFields, shownSource } from "./trigger-composio.js";
24
29
  import { isObject } from "./validate.js";
25
30
  /** Where the owner does by hand what this server could not do on Composio. */
26
31
  const DASHBOARD = "https://platform.composio.dev";
@@ -34,6 +39,15 @@ const text = (value) => (typeof value === "string" ? value : "");
34
39
  const enc = encodeURIComponent;
35
40
  const newHook = () => `cph_${randomBytes(12).toString("hex")}`;
36
41
  const instanceOf = (source) => String(source.instance_id);
42
+ /** The config fields `source` keeps sealed (its sealed_config). */
43
+ const sealedOf = (source) => (Array.isArray(source[SEALED_FIELD]) ? source[SEALED_FIELD].filter((name) => typeof name === "string") : []);
44
+ /** The settings field a sealed config value is kept under: one the list of the server's secrets can hold (8 bytes or
45
+ * more, no whitespace), else the unlisted one. */
46
+ const configFieldFor = (value) => (!/\s/.test(value) && Buffer.byteLength(value, "utf8") >= 8 ? CONFIG_SECRET : CONFIG_UNLISTED);
47
+ /** `said` with each of `values` (sealed config values) put as the mask. */
48
+ /** An error's words for a log line: none with sealed config values (`values`) in play, as a quote of one may be in a form
49
+ * no match finds (JSON-escaped, encoded); its code alone then. */
50
+ const told = (error, values) => values.some(Boolean) ? `${error instanceof ApiError ? error.code : "error"} (its words are withheld: the config holds a sealed value)` : String(error?.message ?? error);
37
51
  /** Whether two JSON values are equal, an object's fields in any order. */
38
52
  function same(a, b) {
39
53
  if (a === b)
@@ -64,21 +78,43 @@ export class ComposioTriggers {
64
78
  async make(source, id, enabled, keep) {
65
79
  if (!this.deps.publicUrl)
66
80
  throw new ApiError("composio_no_public_url", "Composio can't reach this server: set its public URL first (AGENTRUN_PUBLIC_URL, the https address Composio sends events to), then make the trigger.");
67
- for (const field of ["instance_id", "hook"])
81
+ for (const field of ["instance_id", "hook", SEALED_FIELD])
68
82
  if (source[field] !== undefined)
69
83
  throw invalid([{ field: `source.${field}`, reason: "not_allowed", message: `${field} is set by this server when it makes the trigger on Composio: leave it out.` }]);
84
+ const config = source.config;
85
+ // A credential below the config's top level is refused: a create seals one as a top-level field alone (and Composio's
86
+ // trigger configs are flat), so none is kept here in the clear.
87
+ const deeper = configSecrets(config).filter((secret) => secret.path.length > 1);
88
+ if (deeper.length)
89
+ throw invalid(deeper.map((secret) => ({ field: `source.config.${secret.path.join(".")}`, reason: "not_allowed", message: `${secret.name} is a credential below the config's top level: this server seals a credential only as a top-level field of the config, so it can't keep this one. Give it as a top-level field, or leave it out.` })));
90
+ const named = sealedConfigFields(config);
91
+ const refuseMasked = (sealing) => {
92
+ const masked = sealing.filter((name) => config[name] === SEALED_MASK);
93
+ if (masked.length)
94
+ throw invalid(masked.map((name) => ({ field: `source.config.${name}`, reason: "invalid", message: `${name} is a credential: give its value. "${SEALED_MASK}" is what an answer shows in its place.` })));
95
+ };
96
+ refuseMasked(named);
70
97
  const server = String(source.server);
71
98
  const credential = await this.deps.credential(server, "field");
99
+ const event = String(source.event);
100
+ const missing = `Composio has no event ${event} for ${credential.toolkit}: pick one from the server's events.`;
72
101
  // Made, saved here, and undone when not saved, alone among the project's steps.
73
102
  return this.serial(credential.key, async () => {
74
- const ask = this.ask(credential, "nothing was saved");
103
+ // The event's schema first, a read: a field it marks as a credential (format: password, writeOnly) is sealed too,
104
+ // whatever its name (sealedSchemaFields).
105
+ const type = await this.ask(credential, "nothing was saved", named.map((name) => String(config[name])))(`reading ${event}'s config on Composio`, "GET", `/api/v3/triggers_types/${enc(event)}`, undefined, missing).catch((error) => {
106
+ throw onField(error, "source.event");
107
+ });
108
+ const sealing = [...new Set([...named, ...sealedSchemaFields(type.config).filter((name) => sealableValue(config[name]))])];
109
+ refuseMasked(sealing);
110
+ const values = sealing.map((name) => String(config[name]));
111
+ const ask = this.ask(credential, "nothing was saved", values);
75
112
  const undo = [];
76
113
  try {
77
114
  // The account first: a read, so a server not connected yet leaves nothing made on Composio.
78
115
  const account = await this.accountOf(ask, credential, server);
79
116
  const hook = await this.subscribe(ask, source[MOVE_FIELD] === true, undo);
80
- const event = String(source.event);
81
- const made = await ask(`turning on ${event} on Composio`, "POST", `/api/v3/trigger_instances/${enc(event)}/upsert`, { connected_account_id: account, user_id: credential.user, trigger_config: source.config }, `Composio has no event ${event} for ${credential.toolkit}: pick one from the server's events.`).catch((error) => {
117
+ const made = await ask(`turning on ${event} on Composio`, "POST", `/api/v3/trigger_instances/${enc(event)}/upsert`, { connected_account_id: account, user_id: credential.user, trigger_config: source.config }, missing).catch((error) => {
82
118
  throw onField(onField(error, "source.config"), "source.event");
83
119
  });
84
120
  const instance = text(made.trigger_id);
@@ -94,26 +130,45 @@ export class ComposioTriggers {
94
130
  const now = await this.deps.credential(server, "field");
95
131
  if (now.key !== credential.key)
96
132
  throw invalid([{ field: "source.server", reason: "invalid", message: `${server} was saved again with another Composio key while this trigger was being made: nothing was saved, make it again.` }]);
133
+ // Each credential of its config sealed, the trigger keeping the mask in its place: Composio's upsert above was the
134
+ // one place it went.
135
+ undo.push(async () => {
136
+ for (const name of sealing)
137
+ await this.deps.sealed.remove(configScope(id, name));
138
+ });
139
+ // A number is sealed as its decimal text; Composio got it, as a number, in the upsert above.
140
+ for (const name of sealing)
141
+ await this.deps.sealed.set(configScope(id, name), configFieldFor(String(config[name])), String(config[name]));
97
142
  const { [MOVE_FIELD]: _moved, ...kept } = source;
98
- return await keep({ ...kept, instance_id: instance, hook });
143
+ const shown = sealing.length ? { config: { ...config, ...Object.fromEntries(sealing.map((name) => [name, SEALED_MASK])) }, [SEALED_FIELD]: sealing } : {};
144
+ return await keep({ ...kept, ...shown, instance_id: instance, hook });
99
145
  }
100
146
  catch (error) {
101
147
  for (const step of undo.splice(0).reverse())
102
- await step().catch((undone) => this.deps.say({ condition: "composio_undo_failed", trigger: id, error: String(undone?.message ?? undone) }));
148
+ await step().catch((undone) => this.deps.say({ condition: "composio_undo_failed", trigger: id, error: told(undone, values) }));
103
149
  throw error;
104
150
  }
105
151
  });
106
152
  }
107
153
  patched(was, given) {
108
- const fixed = "A Composio trigger's server, event and config made its instance on Composio, so they stay: make a new trigger for another.";
154
+ const fixed = "A Composio trigger's server, event and config made its instance on Composio, so they stay: to change one (a sealed key too), delete the trigger and make a new one.";
109
155
  for (const field of ["server", "event", "instance_id", "hook"])
110
156
  if (given[field] !== undefined && given[field] !== was[field])
111
157
  throw invalid([{ field: `source.${field}`, reason: "not_allowed", message: fixed }]);
112
- if (!same(given.config, was.config))
158
+ // A sealed field left out, or sent as the mask an answer shows, keeps its value; any other value is a change. Read
159
+ // against the source as answered (shownSource), so one still kept in the clear compares as the answer showed it.
160
+ const shown = shownSource(was);
161
+ const sealed = sealedOf(shown);
162
+ const sent = given.config;
163
+ // At its own place: a top-level name, or a nested one's JSON Pointer (a trigger an earlier server kept).
164
+ const config = isObject(sent) && sealed.length ? sealedKept(sent, shown.config, sealed) : sent;
165
+ if (!same(config, shown.config))
113
166
  throw invalid([{ field: "source.config", reason: "not_allowed", message: fixed }]);
114
167
  if (given[MOVE_FIELD] !== undefined)
115
168
  throw invalid([{ field: `source.${MOVE_FIELD}`, reason: "not_allowed", message: `${MOVE_FIELD} is a create's alone.` }]);
116
- return { ...given, instance_id: was.instance_id, hook: was.hook };
169
+ const { [SEALED_FIELD]: _given, ...rest } = given;
170
+ const kept = sealedOf(was);
171
+ return { ...rest, config: was.config, ...(kept.length ? { [SEALED_FIELD]: kept } : {}), instance_id: was.instance_id, hook: was.hook };
117
172
  }
118
173
  async turned(source, id, on) {
119
174
  const instance = instanceOf(source);
@@ -127,7 +182,7 @@ export class ComposioTriggers {
127
182
  if (!holding.length)
128
183
  return;
129
184
  on = holding.some((h) => h.enabled);
130
- await this.ask(credential)(`turning the trigger instance ${on ? "on" : "off"}`, "PATCH", `/api/v3/trigger_instances/manage/${enc(instance)}`, { status: on ? "enable" : "disable" });
185
+ await this.ask(credential, "nothing was changed", this.sealedValues(holding))(`turning the trigger instance ${on ? "on" : "off"}`, "PATCH", `/api/v3/trigger_instances/manage/${enc(instance)}`, { status: on ? "enable" : "disable" });
131
186
  });
132
187
  return undefined;
133
188
  }
@@ -137,12 +192,17 @@ export class ComposioTriggers {
137
192
  }
138
193
  }
139
194
  async removed(source, id) {
195
+ // Its sealed config goes with it, whatever Composio says below; read first, so Composio's words about its instance are
196
+ // withheld (asking).
197
+ const values = this.sealedValues([{ id, source }]);
198
+ for (const name of sealedOf(source))
199
+ await this.deps.sealed.remove(configScope(id, name)).catch((error) => this.deps.say({ condition: "composio_sealed_config_not_removed", trigger: id, field: name, error: String(error?.message ?? error) }));
140
200
  const instance = instanceOf(source);
141
201
  let left = "delete";
142
202
  try {
143
203
  // Kept while another trigger holds it, and off once none of those is on, as a pause leaves it.
144
204
  const credential = await this.deps.credential(String(source.server), "field");
145
- await this.serial(credential.key, async () => this.leave(this.ask(credential), instance, (left = await this.leftWith(instance, id))));
205
+ await this.serial(credential.key, async () => this.leave(this.ask(credential, "nothing was changed", values), instance, (left = await this.leftWith(instance, id))));
146
206
  return undefined;
147
207
  }
148
208
  catch (error) {
@@ -165,7 +225,7 @@ export class ComposioTriggers {
165
225
  if (!isObject(item) || !text(item.slug))
166
226
  continue;
167
227
  const config = isObject(item.config) ? item.config : { type: "object", properties: {} };
168
- events.push({ slug: text(item.slug), name: text(item.name) || text(item.slug), description: text(item.description), ...(text(item.instructions) ? { instructions: text(item.instructions) } : {}), config, polled: item.type === "poll" });
228
+ events.push({ slug: text(item.slug), name: text(item.name) || text(item.slug), description: text(item.description), ...(text(item.instructions) ? { instructions: text(item.instructions) } : {}), config, polled: item.type === "poll", sealed: sealedSchemaFields(config) });
169
229
  }
170
230
  return { server: name, toolkit: credential.toolkit, events };
171
231
  }
@@ -174,7 +234,7 @@ export class ComposioTriggers {
174
234
  async triggersOf(name) {
175
235
  const credential = await this.deps.credential(name, "route");
176
236
  const mine = (await this.deps.holders()).filter((h) => h.source.server === name);
177
- const ask = this.ask(credential);
237
+ const ask = this.ask(credential, "nothing was changed", this.sealedValues(mine));
178
238
  // What Composio answered, and whether it answered for every instance: one it didn't answer for is unknown, not missing.
179
239
  const states = new Map();
180
240
  let read = false;
@@ -256,6 +316,107 @@ export class ComposioTriggers {
256
316
  if (using.length)
257
317
  throw new ApiError("composio_in_use", `${name} has Composio triggers: ${using.map((h) => h.name).join(", ")}. Delete ${using.length > 1 ? "them" : "it"} first, ${then}.`, { details: { triggers: using.map((h) => ({ id: h.id, name: h.name })) } });
258
318
  }
319
+ /** At the server's start: each composio trigger kept with a credential of its config in the clear (made before the
320
+ * config was sealed) sealed now, its source rewritten (`rewrite`) as an answer shows it (shownSource: the mask in its
321
+ * place), and said with the trigger's id and the fields' names alone. Composio's instance is left as it is: it already
322
+ * holds the value. One that can't be sealed is said, still answered masked, and left for the next start. A trigger
323
+ * with nothing in the clear is passed over, so a second start does nothing. */
324
+ async sealKept(rewrite) {
325
+ let done = 0;
326
+ for (const holder of await this.deps.holders()) {
327
+ // At any depth: an earlier server took a config with one below its top level, each sealed by its JSON Pointer.
328
+ const clear = configSecrets(holder.source.config);
329
+ if (!clear.length)
330
+ continue;
331
+ const names = clear.map((secret) => secret.name).join(",");
332
+ try {
333
+ for (const secret of clear)
334
+ await this.deps.sealed.set(configScope(holder.id, secret.name), configFieldFor(String(secret.value)), String(secret.value));
335
+ await rewrite(holder.id, shownSource(holder.source));
336
+ this.deps.say({ condition: "composio_config_sealed", trigger: holder.id, fields: names });
337
+ done++;
338
+ }
339
+ catch (error) {
340
+ this.deps.say({ condition: "composio_config_not_sealed", trigger: holder.id, fields: names, error: told(error, clear.map((secret) => String(secret.value))) });
341
+ }
342
+ }
343
+ return done;
344
+ }
345
+ /** After the server's start, never holding it up: each composio trigger an earlier server kept with a value in the clear
346
+ * in a field only its event's schema marks (format: password, writeOnly: sealedSchemaFields; the name rule is
347
+ * sealKept's) sealed, as sealKept seals one. Each event's schema is read once from Composio with its server's key, its
348
+ * words withheld when the server's triggers hold sealed values. When a read fails (Composio down), that is said once,
349
+ * by a code, and those triggers are left for the next start. The rewrites run inside `around` (the store's
350
+ * secureRewrite), once, and only when there is one to make. */
351
+ async sealMarked(rewrite, around) {
352
+ const eventOf = (holder) => `${String(holder.source.server)}\n${String(holder.source.event)}`;
353
+ // A top-level value in the clear its sealed_config doesn't name: one the schema may mark.
354
+ const plain = (source) => {
355
+ const sealed = new Set(sealedOf(source));
356
+ return isObject(source.config) ? Object.entries(source.config).filter(([name, value]) => !sealed.has(name) && value !== SEALED_MASK && sealableValue(value)).map(([name]) => name) : [];
357
+ };
358
+ const holders = (await this.deps.holders()).filter((holder) => plain(holder.source).length);
359
+ const marked = new Map();
360
+ let unread = 0;
361
+ let failed;
362
+ for (const event of new Set(holders.map(eventOf))) {
363
+ if (this.deps.signal?.aborted)
364
+ return;
365
+ const [server, slug] = event.split("\n");
366
+ try {
367
+ const credential = await this.deps.credential(server, "field");
368
+ const type = await this.ask(credential, "nothing was changed", this.sealedValues(holders.filter((holder) => eventOf(holder) === event)))(`reading ${slug}'s config on Composio`, "GET", `/api/v3/triggers_types/${enc(slug)}`);
369
+ marked.set(event, sealedSchemaFields(type.config));
370
+ }
371
+ catch (error) {
372
+ unread++;
373
+ failed ??= error;
374
+ }
375
+ }
376
+ if (unread && !this.deps.signal?.aborted)
377
+ this.deps.say({ condition: "composio_config_schemas_unread", events: String(unread), error: failed instanceof ApiError ? failed.code : "error" });
378
+ const due = (holder) => plain(holder.source).filter((name) => marked.get(eventOf(holder))?.includes(name));
379
+ if (this.deps.signal?.aborted || !holders.some((holder) => due(holder).length))
380
+ return;
381
+ await around(async () => {
382
+ let done = 0;
383
+ // Read again: a request since may have changed or deleted one.
384
+ for (const holder of await this.deps.holders()) {
385
+ const fields = due(holder);
386
+ if (!fields.length)
387
+ continue;
388
+ const config = holder.source.config;
389
+ const values = fields.map((name) => String(config[name]));
390
+ const unseal = async () => {
391
+ for (const name of fields)
392
+ await this.deps.sealed.remove(configScope(holder.id, name)).catch(() => undefined);
393
+ };
394
+ let written;
395
+ try {
396
+ for (const [i, name] of fields.entries())
397
+ await this.deps.sealed.set(configScope(holder.id, name), configFieldFor(values[i]), values[i]);
398
+ // These fields alone masked: any other value is as the row keeps it (sealKept's). Written only while the row is
399
+ // the one read here (its updatedAt and its source: one millisecond's writes share an updatedAt): a PATCH since (an
400
+ // accept) is not undone, a delete since leaves no sealed row.
401
+ written = await rewrite(holder.id, { ...holder.source, config: { ...config, ...Object.fromEntries(fields.map((name) => [name, SEALED_MASK])) }, [SEALED_FIELD]: [...new Set([...sealedOf(holder.source), ...fields])] }, holder.updatedAt, holder.source);
402
+ }
403
+ catch (error) {
404
+ await unseal();
405
+ this.deps.say({ condition: "composio_config_not_sealed", trigger: holder.id, fields: fields.join(","), error: told(error, values) });
406
+ continue;
407
+ }
408
+ if (!written) {
409
+ await unseal();
410
+ this.deps.say({ condition: "composio_config_not_sealed", trigger: holder.id, fields: fields.join(","), error: "changed_meanwhile" });
411
+ continue;
412
+ }
413
+ // Written: the row is masked, so its sealed values are now the one copy and nothing after this undoes them.
414
+ this.deps.say({ condition: "composio_config_sealed", trigger: holder.id, fields: fields.join(",") });
415
+ done++;
416
+ }
417
+ return done;
418
+ });
419
+ }
259
420
  // ---- its steps ---------------------------------------------------------------------------------------------------------
260
421
  /** `step` run once the steps queued before it for the project of key `key` are done (failed or not), and before any
261
422
  * queued after it. The key is digested, never kept as it is. */
@@ -301,9 +462,14 @@ export class ComposioTriggers {
301
462
  throw error;
302
463
  });
303
464
  }
304
- /** Composio asked with the server's key; a failure's words end with what it left (`outcome`). */
305
- ask(credential, outcome = "nothing was changed") {
306
- return asking(this.deps.control, credential.key, this.deps.signal, outcome);
465
+ /** The sealed config values `holders` keep here: what Composio may quote back about their instance. */
466
+ sealedValues(holders) {
467
+ return holders.flatMap((h) => sealedOf(h.source).map((name) => this.deps.sealed.get(configScope(h.id, name), CONFIG_SECRET) ?? this.deps.sealed.get(configScope(h.id, name), CONFIG_UNLISTED) ?? "")).filter(Boolean);
468
+ }
469
+ /** Composio asked with the server's key; a failure's words end with what it left (`outcome`), and pass on none of
470
+ * Composio's own with a value of `sealed` (a trigger's sealed config) in play. */
471
+ ask(credential, outcome = "nothing was changed", sealed = []) {
472
+ return asking(this.deps.control, credential.key, this.deps.signal, outcome, sealed);
307
473
  }
308
474
  addressOf(hook) {
309
475
  return `${this.deps.publicUrl}/v2/hooks/composio/${hook}`;
@@ -0,0 +1,11 @@
1
+ /** How many new sandboxes a claim starts in place of ones its provider lost, by default. */
2
+ export declare const LOST_RECREATES = 2;
3
+ /** The code a run past its new sandboxes fails with: the one a computer that cannot be had at the claim is refused with. */
4
+ export declare const COMPUTER_UNAVAILABLE_CODE = "computer_unavailable";
5
+ /** The Timeline's row once a new sandbox replaced a lost one: its name. */
6
+ export declare const lostRecreatedWords: (name: string) => string;
7
+ /** The run's end once its sandbox was lost again after `recreates` new ones (the claim's bound): the provider's words,
8
+ * `why`, last. */
9
+ export declare const lostEnd: (recreates: number, why: string) => string;
10
+ /** The message of a run's end in lostEnd's words: what follows its code; undefined for any other summary. */
11
+ export declare const lostEndMessage: (summary: string | null | undefined) => string | undefined;
@@ -0,0 +1,19 @@
1
+ // A run's sandbox that its provider lost mid-run (deleted by the vendor's own API or console, or gone with no why): the
2
+ // claim starts a new one in its place at the next tool call (workspace/computer-for-claim.ts lostAware), up to
3
+ // LOST_RECREATES times a claim. These are the words of both: the Timeline's row for a new one, and the run's end once the
4
+ // claim has started as many as it may. That end's words begin with its code, so a reader of the run's summary serves it
5
+ // as the error computer_unavailable, its message the words after the code (store-view.ts errorOfRow), as a cap's end is
6
+ // served as spend_cap_reached.
7
+ /** How many new sandboxes a claim starts in place of ones its provider lost, by default. */
8
+ export const LOST_RECREATES = 2;
9
+ /** The code a run past its new sandboxes fails with: the one a computer that cannot be had at the claim is refused with. */
10
+ export const COMPUTER_UNAVAILABLE_CODE = "computer_unavailable";
11
+ /** How lostEnd's words begin, and only theirs. */
12
+ const LOST_END = `${COMPUTER_UNAVAILABLE_CODE}: `;
13
+ /** The Timeline's row once a new sandbox replaced a lost one: its name. */
14
+ export const lostRecreatedWords = (name) => `Its computer was lost; started a new one (${name}).`;
15
+ /** The run's end once its sandbox was lost again after `recreates` new ones (the claim's bound): the provider's words,
16
+ * `why`, last. */
17
+ export const lostEnd = (recreates, why) => `${LOST_END}the run's sandbox was lost ${recreates + 1} ${recreates === 0 ? "time" : "times"}, and a run starts at most ${recreates} new ${recreates === 1 ? "one" : "ones"} in place of a lost one: ${why.replace(/[.!?]+$/, "")}.`;
18
+ /** The message of a run's end in lostEnd's words: what follows its code; undefined for any other summary. */
19
+ export const lostEndMessage = (summary) => typeof summary === "string" && summary.startsWith(LOST_END) ? summary.slice(LOST_END.length) : undefined;
@@ -1,4 +1,5 @@
1
1
  import type { Result, ScreenWatch, ScreenWatchHandlers, WatchOptions } from "@parcha/agentrun-computer";
2
+ import type { LiveViewHost } from "@parcha/pi-browser/live-view";
2
3
  /** The program that encodes the video. */
3
4
  export declare const FFMPEG = "ffmpeg";
4
5
  /** The recorder's bounds: frames a second at most; the long side in pixels at most; the caps, in bytes across the run's
@@ -35,14 +36,21 @@ export interface Recording {
35
36
  facts(): RecordingFacts;
36
37
  }
37
38
  /** The computer's watch, bound to its ref (provider.watch): the recorder gives the handlers and the signal. */
38
- export type RecordWatch = (handlers: ScreenWatchHandlers, options: WatchOptions) => Promise<Result<ScreenWatch>>;
39
+ export type RecordWatch = (handlers: ScreenWatchHandlers, options: WatchOptions) => Promise<Result<Pick<ScreenWatch, "close">>>;
40
+ /** Browser session `tag`'s screen as the recorder watches it: the run's live view's screencast of it (pi-browser's
41
+ * LiveViewHost.watch), which the live view acks; JPEG frames of the page's size. */
42
+ export declare const browserWatch: (view: Pick<LiveViewHost, "watch">, tag: string) => RecordWatch;
43
+ /** A run's browser sessions' recordings, each by its tag, where its claim records (ClaimBrowser.record): the answer is
44
+ * told session `id` under `tag` at its launch or its reopening, which starts its own (named by its computer, `id`) and
45
+ * ends the one before it under that tag, and null at its release, which ends it. With no `record`, nothing. */
46
+ export declare function sessionRecordings(view: Pick<LiveViewHost, "watch">, record: ((id: string, watch: RecordWatch) => Recording) | undefined): (tag: string, id: string | null) => Promise<void>;
39
47
  export type RecordInput = {
40
48
  readonly watch: RecordWatch;
41
49
  /** The run's recordings folder on this machine (recordingsFolder): made when the first frame comes. */
42
50
  readonly folder: string;
43
51
  /** The computer's ref id: its file's name. */
44
52
  readonly tag: string;
45
- readonly kind: "desktop" | "phone";
53
+ readonly kind: "desktop" | "phone" | "browser";
46
54
  /** A line on the run's timeline. */
47
55
  readonly say: (words: string) => void;
48
56
  /** For tests: the program run in ffmpeg's place, the bounds, and where a line for the operator goes (default stderr). */