@parcha/agentrun-serve 0.1.0-beta.49 → 0.1.0-beta.51

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 (216) hide show
  1. package/CHANGELOG.md +173 -9
  2. package/README.md +246 -39
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/agents-store.js +7 -3
  6. package/dist/api-only.d.ts +8 -10
  7. package/dist/api-only.js +11 -12
  8. package/dist/capacity.d.ts +50 -0
  9. package/dist/capacity.js +49 -0
  10. package/dist/cli-learning/claude-wire.d.ts +41 -0
  11. package/dist/cli-learning/claude-wire.js +258 -0
  12. package/dist/cli-learning/cli.d.ts +11 -0
  13. package/dist/cli-learning/cli.js +241 -0
  14. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  15. package/dist/cli-learning/codex-worktree.js +119 -0
  16. package/dist/cli-learning/connections.d.ts +62 -0
  17. package/dist/cli-learning/connections.js +87 -0
  18. package/dist/cli-learning/entry.d.ts +1 -0
  19. package/dist/cli-learning/entry.js +4 -0
  20. package/dist/cli-learning/evidence.d.ts +78 -0
  21. package/dist/cli-learning/evidence.js +492 -0
  22. package/dist/cli-learning/hook.d.ts +33 -0
  23. package/dist/cli-learning/hook.js +544 -0
  24. package/dist/cli-learning/install.d.ts +33 -0
  25. package/dist/cli-learning/install.js +335 -0
  26. package/dist/cli-learning/observation-proof.d.ts +14 -0
  27. package/dist/cli-learning/observation-proof.js +10 -0
  28. package/dist/cli-learning/policy.d.ts +48 -0
  29. package/dist/cli-learning/policy.js +363 -0
  30. package/dist/cli-learning/schema.d.ts +16 -0
  31. package/dist/cli-learning/schema.js +27 -0
  32. package/dist/cli-learning/state.d.ts +23 -0
  33. package/dist/cli-learning/state.js +61 -0
  34. package/dist/cli.js +24 -2
  35. package/dist/compute-cost.d.ts +101 -0
  36. package/dist/compute-cost.js +250 -0
  37. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  38. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/email/email-faux.d.ts +3 -1
  41. package/dist/email/email-faux.js +3 -2
  42. package/dist/email/routes.js +22 -12
  43. package/dist/eval-previous.d.ts +52 -0
  44. package/dist/eval-previous.js +164 -0
  45. package/dist/file-types.d.ts +2 -0
  46. package/dist/file-types.js +3 -1
  47. package/dist/harness-install.d.ts +6 -2
  48. package/dist/harness-install.js +40 -8
  49. package/dist/harness.d.ts +1 -1
  50. package/dist/harness.js +3 -2
  51. package/dist/learn/check.d.ts +8 -5
  52. package/dist/learn/check.js +25 -24
  53. package/dist/learn/repick.d.ts +22 -13
  54. package/dist/learn/repick.js +57 -56
  55. package/dist/learn/secrets.js +14 -3
  56. package/dist/learn/workflow-draft.d.ts +4 -0
  57. package/dist/learn/workflow-draft.js +10 -7
  58. package/dist/learned-workflow.js +8 -8
  59. package/dist/learning-setting.js +2 -2
  60. package/dist/learning-words.d.ts +1 -1
  61. package/dist/learning-words.js +1 -1
  62. package/dist/mcp-pin-first.js +2 -1
  63. package/dist/mcp-private-hosts.d.ts +24 -3
  64. package/dist/mcp-private-hosts.js +53 -3
  65. package/dist/model-gateway.d.ts +2 -0
  66. package/dist/model-gateway.js +3 -1
  67. package/dist/native/runtimes.d.ts +2 -0
  68. package/dist/native/runtimes.js +2 -0
  69. package/dist/observation/learning.d.ts +32 -0
  70. package/dist/observation/learning.js +66 -0
  71. package/dist/observation/observer.d.ts +8 -1
  72. package/dist/observation/observer.js +89 -9
  73. package/dist/observation/schema.js +12 -4
  74. package/dist/observation/usage-identity.d.ts +9 -0
  75. package/dist/observation/usage-identity.js +11 -0
  76. package/dist/openapi.js +113 -29
  77. package/dist/paid-calls.d.ts +13 -6
  78. package/dist/paid-calls.js +14 -8
  79. package/dist/run-launch.d.ts +16 -2
  80. package/dist/run-launch.js +6 -1
  81. package/dist/run-timeline-served.js +5 -3
  82. package/dist/run-usage.d.ts +23 -8
  83. package/dist/run-usage.js +100 -18
  84. package/dist/run-view.d.ts +2 -0
  85. package/dist/run-view.js +12 -7
  86. package/dist/runner/adapter-loop.d.ts +4 -0
  87. package/dist/runner/adapter-loop.js +44 -27
  88. package/dist/runner/adapter-run-spec.d.ts +8 -3
  89. package/dist/runner/adapter-run-spec.js +15 -8
  90. package/dist/runner/beside.d.ts +13 -0
  91. package/dist/runner/beside.js +27 -8
  92. package/dist/runner/big-writes.d.ts +33 -0
  93. package/dist/runner/big-writes.js +105 -0
  94. package/dist/runner/cli-run-spec.js +16 -8
  95. package/dist/runner/disk-free.d.ts +44 -0
  96. package/dist/runner/disk-free.js +96 -0
  97. package/dist/runner/feedback-round.d.ts +12 -8
  98. package/dist/runner/feedback-round.js +16 -30
  99. package/dist/runner/harness-loops.js +3 -1
  100. package/dist/runner/held.d.ts +4 -1
  101. package/dist/runner/journal-kinds.d.ts +1 -1
  102. package/dist/runner/learning-end.js +13 -4
  103. package/dist/runner/main.d.ts +17 -6
  104. package/dist/runner/main.js +187 -45
  105. package/dist/runner/metrics.d.ts +4 -0
  106. package/dist/runner/metrics.js +9 -0
  107. package/dist/runner/presence.d.ts +11 -2
  108. package/dist/runner/presence.js +31 -3
  109. package/dist/runner/run-child-host.d.ts +27 -17
  110. package/dist/runner/run-child-host.js +70 -116
  111. package/dist/runner/run-child.js +3 -0
  112. package/dist/runner/run-errors.js +2 -0
  113. package/dist/runner/runner-check.d.ts +51 -0
  114. package/dist/runner/runner-check.js +206 -0
  115. package/dist/runner/runner-metrics.d.ts +19 -0
  116. package/dist/runner/runner-metrics.js +49 -0
  117. package/dist/runner/runner.d.ts +37 -0
  118. package/dist/runner/runner.js +43 -3
  119. package/dist/runner/save-slots.d.ts +9 -0
  120. package/dist/runner/save-slots.js +91 -0
  121. package/dist/runner/sdk-loop.js +34 -22
  122. package/dist/runs-over-store.d.ts +8 -1
  123. package/dist/runs-over-store.js +57 -9
  124. package/dist/sdk/runs.d.ts +25 -6
  125. package/dist/sdk/runs.js +107 -35
  126. package/dist/sdk/runtimes.d.ts +19 -0
  127. package/dist/sdk/runtimes.js +23 -0
  128. package/dist/sdk/schema.d.ts +14 -8
  129. package/dist/sdk/schema.js +18 -6
  130. package/dist/server.d.ts +7 -0
  131. package/dist/server.js +151 -28
  132. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  133. package/dist/start-switches.js +2 -0
  134. package/dist/stats.d.ts +4 -0
  135. package/dist/stats.js +1 -1
  136. package/dist/store/agent-body.d.ts +13 -2
  137. package/dist/store/agent-body.js +19 -4
  138. package/dist/store/dialect.d.ts +2 -0
  139. package/dist/store/dialect.js +1 -0
  140. package/dist/store/index.d.ts +3 -3
  141. package/dist/store/index.js +2 -2
  142. package/dist/store/postgres/connection.d.ts +5 -2
  143. package/dist/store/postgres/connection.js +19 -7
  144. package/dist/store/postgres/dialect.js +1 -0
  145. package/dist/store/postgres/migrate.d.ts +30 -0
  146. package/dist/store/postgres/migrate.js +72 -5
  147. package/dist/store/postgres/migration-lint.d.ts +8 -0
  148. package/dist/store/postgres/migration-lint.js +119 -0
  149. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  150. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  151. package/dist/store/postgres/store.d.ts +8 -3
  152. package/dist/store/postgres/store.js +31 -11
  153. package/dist/store/schema.d.ts +26 -4
  154. package/dist/store/schema.js +45 -4
  155. package/dist/store/sqlite/connection.d.ts +3 -3
  156. package/dist/store/sqlite/connection.js +3 -3
  157. package/dist/store/sqlite/run-launch.d.ts +9 -1
  158. package/dist/store/sqlite/run-launch.js +44 -0
  159. package/dist/store/sqlite/store.d.ts +19 -4
  160. package/dist/store/sqlite/store.js +180 -93
  161. package/dist/store/store-schema.d.ts +34 -0
  162. package/dist/store/store-schema.js +125 -0
  163. package/dist/store/store.d.ts +61 -2
  164. package/dist/store/store.js +13 -0
  165. package/dist/store-reads/analytics.d.ts +3 -2
  166. package/dist/store-reads/analytics.js +20 -8
  167. package/dist/store-reads/cap.d.ts +9 -5
  168. package/dist/store-reads/cap.js +28 -2
  169. package/dist/store-reads/decisions.d.ts +21 -0
  170. package/dist/store-reads/decisions.js +22 -0
  171. package/dist/store-reads/journal.d.ts +8 -2
  172. package/dist/store-reads/journal.js +27 -8
  173. package/dist/store-view.d.ts +9 -4
  174. package/dist/store-view.js +48 -25
  175. package/dist/template-eval.d.ts +15 -1
  176. package/dist/template-eval.js +92 -13
  177. package/dist/templates.d.ts +4 -3
  178. package/dist/templates.js +4 -3
  179. package/dist/timeline/labels.js +17 -0
  180. package/dist/tool-gate.d.ts +4 -2
  181. package/dist/tool-list.js +1 -0
  182. package/dist/tools.d.ts +6 -2
  183. package/dist/tools.js +13 -1
  184. package/dist/trigger-targets.d.ts +21 -5
  185. package/dist/trigger-targets.js +13 -10
  186. package/dist/unified-usage.d.ts +24 -0
  187. package/dist/unified-usage.js +400 -0
  188. package/dist/uploads-archil.d.ts +100 -0
  189. package/dist/uploads-archil.js +430 -0
  190. package/dist/uploads.d.ts +55 -1
  191. package/dist/uploads.js +185 -98
  192. package/dist/validate.js +1 -1
  193. package/dist/web-fake.d.ts +25 -0
  194. package/dist/web-fake.js +38 -1
  195. package/dist/web-save.d.ts +75 -0
  196. package/dist/web-save.js +235 -0
  197. package/dist/workspace/archil-claim.d.ts +5 -2
  198. package/dist/workspace/archil-claim.js +5 -2
  199. package/dist/workspace/archil-disk.d.ts +11 -1
  200. package/dist/workspace/archil-disk.js +43 -10
  201. package/dist/workspace/archil.d.ts +3 -0
  202. package/dist/workspace/archil.js +102 -16
  203. package/dist/workspace/computer-for-claim.d.ts +14 -0
  204. package/dist/workspace/computer-for-claim.js +46 -7
  205. package/dist/workspace/computer-intervals.d.ts +9 -3
  206. package/dist/workspace/computer-intervals.js +17 -8
  207. package/dist/workspace/pieced.d.ts +14 -0
  208. package/dist/workspace/pieced.js +23 -0
  209. package/dist/workspace/run-disk.js +32 -12
  210. package/dist/workspace/run-workspace.d.ts +1 -1
  211. package/dist/workspace/run-workspace.js +11 -6
  212. package/package.json +10 -10
  213. package/skills/agentrun-serve/SKILL.md +52 -7
  214. package/templates/README.md +36 -7
  215. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
  216. package/dist/console/assets/index-CR2ZGei1.css +0 -1
@@ -12,6 +12,7 @@ import { approvalsOf } from "./approvals.js";
12
12
  import { ApiError, invalid } from "./errors.js";
13
13
  import { harnessOfBody } from "./harness.js";
14
14
  import { learningSettingIssue } from "./learning-setting.js";
15
+ import { learningSettingForBody } from "./store/agent-body.js";
15
16
  import { storedHarness } from "./harness-table.js";
16
17
  import { AgentBodyInvalid, RevisionMoved, bodyOf, canonical, isObject, StoreConstraint, } from "./store/index.js";
17
18
  import { canonicalToolSettings, settingsIssues } from "./tool-plane.js";
@@ -109,6 +110,7 @@ function revisionInputOf(definition, files) {
109
110
  return {
110
111
  kind: "agentic",
111
112
  instructions: definition.instructions,
113
+ ...(definition.cli_learning !== undefined ? { cli_learning: definition.cli_learning } : {}),
112
114
  ...(definition.sdk !== undefined ? { sdk: definition.sdk } : {}),
113
115
  ...(isObject(definition.native) ? { native: definition.native } : {}),
114
116
  ...(typeof definition.model === "string" ? { model: definition.model } : {}),
@@ -194,7 +196,7 @@ export async function createAgent(store, { definition, skills = {}, note }, opti
194
196
  if (given !== undefined && (await store.agents.get(given)))
195
197
  throw new ApiError("agent_exists", `an agent ${given} exists here`);
196
198
  // Stamped on the revision now, never resolved at run time: an agent saved with no place keeps running on the runner.
197
- const placed = options.fresh && definition.place === undefined && definition.computer === undefined && !isObject(definition.workflow) && !isObject(definition.sdk)
199
+ const placed = options.fresh && definition.place === undefined && definition.computer === undefined && !isObject(definition.workflow) && !isObject(definition.sdk) && !isObject(definition.cli_learning)
198
200
  ? { place: options.fresh.place, ...(definition.tools === undefined ? { tools: [...options.fresh.tools] } : {}) }
199
201
  : {};
200
202
  // A template's agent keeps the package it was applied from on its first revision (store `revisions.package`).
@@ -323,6 +325,7 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
323
325
  files = (isObject(current?.skills) ? current.skills : {});
324
326
  const carried = current
325
327
  ? {
328
+ ...(currentBody.cli_learning && definition.cli_learning === undefined ? { cli_learning: currentBody.cli_learning } : {}),
326
329
  ...(currentBody.sdk && definition.sdk === undefined ? { sdk: currentBody.sdk } : {}),
327
330
  ...(currentBody.native && definition.native === undefined ? { native: currentBody.native } : {}),
328
331
  ...(definition.harness === undefined && currentBody.harness ? { harness: currentBody.harness } : {}),
@@ -335,7 +338,7 @@ function editOn(entry, definition, skills, note, fromPackage = false) {
335
338
  // What the host owns (the sdk and native references, the harness, the computer and place) carries as an edit's does.
336
339
  const owned = current && !fromPackage
337
340
  ? {
338
- ...(definition.learning === undefined && current.kind === "agentic" && !isObject(definition.workflow) && currentBody.learning !== undefined ? { learning: currentBody.learning } : {}),
341
+ ...(definition.learning === undefined && current.kind === "agentic" && !isObject(definition.workflow) && learningSettingForBody(currentBody) !== undefined ? { learning: learningSettingForBody(currentBody) } : {}),
339
342
  // No approvals here: an edit that leaves them out asks (openapi.ts DefinitionInput.approvals),
340
343
  // so no edit makes an agent unattended by saying nothing. The console's edit sends back the approvals it read.
341
344
  ...(definition.max_cost_usd === undefined && currentBody.maxCostUsd !== undefined ? { max_cost_usd: currentBody.maxCostUsd } : {}),
@@ -385,7 +388,7 @@ export function definitionOf(agent, revision, version) {
385
388
  const body = revision.body;
386
389
  const common = body.maxCostUsd !== undefined ? { max_cost_usd: body.maxCostUsd } : {};
387
390
  const kindBody = revision.kind === "agentic"
388
- ? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(body.learning !== undefined ? { learning: body.learning } : {}), ...(body.inputSchema !== undefined ? { input_schema: body.inputSchema } : {}), ...(body.outputSchema !== undefined ? { output_schema: body.outputSchema } : {}), ...(body.checkout !== undefined ? { checkout: body.checkout } : {}), ...common }
391
+ ? { instructions: body.instructions, ...(body.model ? { model: body.model } : {}), ...(body.modelTiers ? { model_tiers: body.modelTiers } : {}), ...(body.thinking ? { thinking: body.thinking } : {}), ...(learningSettingForBody(body) !== undefined ? { learning: learningSettingForBody(body) } : {}), ...(body.inputSchema !== undefined ? { input_schema: body.inputSchema } : {}), ...(body.outputSchema !== undefined ? { output_schema: body.outputSchema } : {}), ...(body.checkout !== undefined ? { checkout: body.checkout } : {}), ...common }
389
392
  : { workflow: body.workflow, ...common };
390
393
  return {
391
394
  id: agent.id,
@@ -393,6 +396,7 @@ export function definitionOf(agent, revision, version) {
393
396
  name: agent.name,
394
397
  ...(agent.description !== null && agent.description !== undefined ? { description: agent.description } : {}),
395
398
  ...kindBody,
399
+ ...(body.cli_learning ? { cli_learning: body.cli_learning } : {}),
396
400
  ...(body.sdk ? { sdk: body.sdk } : {}),
397
401
  ...(body.native ? { native: body.native } : {}),
398
402
  // Its approvals, of either kind: "ask" where none is set, as the definition read says it (definitionOf).
@@ -1,16 +1,14 @@
1
1
  import type { Route } from "./server.js";
2
2
  /** The variable that turns the profile on. */
3
3
  export declare const API_ONLY_ENV = "AGENTRUN_API_ONLY";
4
- /** The routes (server.ts ROUTES, by name) an API-only server serves. Those past a run's own:
5
- * - getComputerDaemon: a run's hosted machine that dials fetches computerd with its own token, as the attach upgrade
6
- * takes such a machine alone (a paired computer is the console's).
7
- * - listComputers, getWorkspaceArchil: the two reads a backend checks before it launches, naming keys and never a
8
- * value; their writes and tests stay the console's.
9
- * - getAgentArchil, deleteAgentArchil, deleteAgent: an agent's disk and the delete of an agent its inline runs made,
10
- * which the backend that made it sends.
11
- * - getRunComputer, takeOverRunComputer, handBackRunComputer, createRunComputerViewer: a run's computer, its take-over
12
- * and hand-back, and its viewer credential's mint (viewer-credential.ts), by the server's token, the backend's own;
13
- * the live page and socket take that credential. */
4
+ /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
5
+ * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
6
+ * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
7
+ * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
8
+ * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
9
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
10
+ * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
11
+ * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
14
12
  export declare const API_ONLY_ROUTES: ReadonlySet<string>;
15
13
  /** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
16
14
  * words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
package/dist/api-only.js CHANGED
@@ -1,25 +1,24 @@
1
1
  /** The variable that turns the profile on. */
2
2
  export const API_ONLY_ENV = "AGENTRUN_API_ONLY";
3
- /** The routes (server.ts ROUTES, by name) an API-only server serves. Those past a run's own:
4
- * - getComputerDaemon: a run's hosted machine that dials fetches computerd with its own token, as the attach upgrade
5
- * takes such a machine alone (a paired computer is the console's).
6
- * - listComputers, getWorkspaceArchil: the two reads a backend checks before it launches, naming keys and never a
7
- * value; their writes and tests stay the console's.
8
- * - getAgentArchil, deleteAgentArchil, deleteAgent: an agent's disk and the delete of an agent its inline runs made,
9
- * which the backend that made it sends.
10
- * - getRunComputer, takeOverRunComputer, handBackRunComputer, createRunComputerViewer: a run's computer, its take-over
11
- * and hand-back, and its viewer credential's mint (viewer-credential.ts), by the server's token, the backend's own;
12
- * the live page and socket take that credential. */
3
+ /** The routes (server.ts ROUTES, by name) an API-only server serves. Past a run's own, why each group is here:
4
+ * - a run's hosted machine fetches computerd with the token its create minted, not the server's;
5
+ * - the computers list and the Archil settings are read before a launch, naming keys, never a value;
6
+ * - an agent its inline runs made has its disk and its delete sent by the backend that made it;
7
+ * - a run's computer, take-over, hand-back and viewer link go to the backend, which has no owner's session here;
8
+ * - a backend reads what its agents learned (loop, promotions, cost per run, a run's learning), cut as the console's;
9
+ * - a run's usage lines (what its cost.usd joins, by meter) are a read of that run alone, cut as the run's read is;
10
+ * - an operator or a scaler reads the runners' capacity (getCapacity, capacity.ts) from the server whose runners run apart. */
13
11
  export const API_ONLY_ROUTES = new Set([
14
12
  "createRun", "createInlineRun", "getComputerDaemon",
15
13
  "getRunComputer", "takeOverRunComputer", "handBackRunComputer", "createRunComputerViewer",
16
14
  "listComputers", "getWorkspaceArchil",
17
15
  "getAgentArchil", "deleteAgentArchil", "deleteAgent",
18
- "getRun", "listRuns", "listAllRuns", "getTimeline",
16
+ "getLearningLoop", "listLearningPromotions", "getLearningCost", "getRunLearning",
17
+ "getRun", "getRunUsage", "listRuns", "listAllRuns", "getTimeline",
19
18
  "sendMessage", "stopRun", "cancelRun", "raiseRunCap", "gradeRun",
20
19
  "listRunFiles", "readRunFile",
21
20
  "createFile", "listFiles", "getFile", "uploadFile", "deleteFile",
22
- "getCapabilities", "getHealth", "getUsage",
21
+ "getCapabilities", "getHealth", "getUsage", "getCapacity",
23
22
  ]);
24
23
  /** Whether `env` turns the profile on: `1` or `true` on; unset, empty, `0` or `false` off. Any other value is refused in
25
24
  * words (a TypeError), so a typo never leaves the console open on a server meant to be API-only. */
@@ -0,0 +1,50 @@
1
+ import type { Runners } from "./store/store.js";
2
+ /** The hand-back window when none is asked, in minutes. */
3
+ export declare const CAPACITY_WINDOW_MINUTES = 15;
4
+ /** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
5
+ export declare const CAPACITY_WINDOW_MAX_MINUTES: number;
6
+ /** One live runner, as the capacity read shows it. */
7
+ export interface CapacityRunner {
8
+ /** The runner's name (--name, AGENTRUN_RUNNER_NAME, or its host and process). */
9
+ readonly id: string;
10
+ /** Its build's version; null for a runner of a build before this read. */
11
+ readonly version: string | null;
12
+ /** The most runs it holds at once (its loops); null when it did not say (a build before this read, or a runner that
13
+ * refused to claim). */
14
+ readonly slots: number | null;
15
+ /** The runs its live claims hold now. */
16
+ readonly executing: number;
17
+ /** Its slots less what it holds (never below 0), 0 for a runner that refused to claim, null with no slots said. A
18
+ * runner also claims by its host's memory (memory-claim.ts), so a free slot is the most it may take, not a promise. */
19
+ readonly free_slots: number | null;
20
+ /** It refused to claim any run (its run isolation refused): it takes none. Its words are in capabilities' runner_refused. */
21
+ readonly refused: boolean;
22
+ /** When it last said it was there (the deadlines' clock). */
23
+ readonly seen_at: string;
24
+ }
25
+ /** The capacity read's answer. */
26
+ export interface CapacityView {
27
+ /** When it was read (the deadlines' clock: the database's on Postgres). */
28
+ readonly at: string;
29
+ readonly runs: {
30
+ /** Runs waiting for a runner now: queued, handed back or with their claim run out (past any backoff), or parked with
31
+ * something to wake them; the backlog a scaler reads. */
32
+ readonly queued: number;
33
+ /** Runs a live claim holds now, on any runner. */
34
+ readonly executing: number;
35
+ };
36
+ /** The live runners, by name. */
37
+ readonly runners: readonly CapacityRunner[];
38
+ /** The free slots of every live runner that said its slots. */
39
+ readonly free_slots: number;
40
+ /** Runs given back still running (a drain, a loop that closed itself, a claim given back) within the window. */
41
+ readonly hand_backs: {
42
+ readonly window_minutes: number;
43
+ readonly count: number;
44
+ };
45
+ }
46
+ /** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
47
+ * CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
48
+ export declare function capacityWindowOf(url: URL): number;
49
+ /** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
50
+ export declare function capacityOverStore(runners: Pick<Runners, "live" | "capacity">, windowMinutes: number, staleMs?: number): Promise<CapacityView>;
@@ -0,0 +1,49 @@
1
+ // GET /v2/capacity: what an operator, or an autoscaler, reads to size the runners. Read from the store alone, so a server
2
+ // with no runner beside it (--no-runner, the API-only profile) answers for every runner on its store: the runs waiting for
3
+ // a runner and the runs a claim holds, each live runner (its row seen within PRESENCE_STALE_MS) with its version, its
4
+ // slots and how many are free, and the hand-backs within a window. Counts, runner names and versions only: no run id,
5
+ // agent, prompt, address or customer's word. Behind the server's token, as every route but capabilities and health.
6
+ import { ApiError } from "./errors.js";
7
+ import { PRESENCE_STALE_MS } from "./runner/presence.js";
8
+ /** The hand-back window when none is asked, in minutes. */
9
+ export const CAPACITY_WINDOW_MINUTES = 15;
10
+ /** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
11
+ export const CAPACITY_WINDOW_MAX_MINUTES = 24 * 60;
12
+ /** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
13
+ * CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
14
+ export function capacityWindowOf(url) {
15
+ const text = url.searchParams.get("window");
16
+ if (text === null)
17
+ return CAPACITY_WINDOW_MINUTES;
18
+ const minutes = /^\d{1,5}$/.test(text) ? Number(text) : NaN;
19
+ if (!(minutes >= 1 && minutes <= CAPACITY_WINDOW_MAX_MINUTES))
20
+ throw new ApiError("bad_request", `window is a whole number of minutes from 1 to ${CAPACITY_WINDOW_MAX_MINUTES}, not ${JSON.stringify(text)}`);
21
+ return minutes;
22
+ }
23
+ /** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
24
+ export async function capacityOverStore(runners, windowMinutes, staleMs = PRESENCE_STALE_MS) {
25
+ const [counts, live] = await Promise.all([runners.capacity(windowMinutes * 60_000), runners.live(staleMs)]);
26
+ const shown = live.map((row) => {
27
+ const executing = counts.held.get(row.runner) ?? 0;
28
+ const refused = row.refused !== null;
29
+ return {
30
+ id: row.runner,
31
+ version: row.version,
32
+ slots: row.slots,
33
+ executing,
34
+ free_slots: refused ? 0 : row.slots === null ? null : Math.max(0, row.slots - executing),
35
+ refused,
36
+ seen_at: new Date(row.seenAt).toISOString(),
37
+ };
38
+ });
39
+ let executing = 0;
40
+ for (const count of counts.held.values())
41
+ executing += count;
42
+ return {
43
+ at: new Date(counts.at).toISOString(),
44
+ runs: { queued: counts.queued, executing },
45
+ runners: shown,
46
+ free_slots: shown.reduce((sum, runner) => sum + (runner.free_slots ?? 0), 0),
47
+ hand_backs: { window_minutes: windowMinutes, count: counts.handBacks },
48
+ };
49
+ }
@@ -0,0 +1,41 @@
1
+ type Policy = {
2
+ text: string;
3
+ complete: boolean;
4
+ reason?: string;
5
+ };
6
+ type Blob = {
7
+ role: string;
8
+ text?: string;
9
+ complete: boolean;
10
+ reason?: string;
11
+ };
12
+ type Request = {
13
+ shapeHash: string;
14
+ refs: string[];
15
+ complete: boolean;
16
+ reason?: string;
17
+ };
18
+ export type ClaudeWireState = {
19
+ version: 1;
20
+ shapes: Record<string, Policy>;
21
+ blobs: Record<string, Blob>;
22
+ requests: Record<string, Request>;
23
+ current?: {
24
+ prompt: string;
25
+ text: string;
26
+ stableText?: string;
27
+ complete: boolean;
28
+ reason?: string;
29
+ };
30
+ /** Re-read ordinary source rows from this byte offset after restoring the JSON cache. */
31
+ replayFrom?: number;
32
+ reminders?: string[];
33
+ };
34
+ /** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
35
+ * never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
36
+ export declare function updateClaudeWire(state: ClaudeWireState | undefined, row: unknown, options: {
37
+ promptId?: string;
38
+ redact: (text: string) => string;
39
+ recordOffset?: number;
40
+ }): ClaudeWireState;
41
+ export {};
@@ -0,0 +1,258 @@
1
+ import { createHash } from 'node:crypto';
2
+ const POLICY_BYTES = 256 * 1024, CACHE_BYTES = 4 * 1024 * 1024, MAX_REFS = 4096;
3
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
4
+ const hash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
5
+ const requestId = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
6
+ const refused = (reason) => ({ text: '', complete: false, reason });
7
+ // Incremental digests contain no recoverable conversation text and are never serialized.
8
+ // On a cache reload the caller replays typed rows from replayFrom to hydrate this state.
9
+ const sourceRuns = new WeakMap();
10
+ function hashValue(value, write, depth = 0) {
11
+ if (depth > 64)
12
+ throw new Error('Native message nesting exceeds the hashing bound.');
13
+ if (typeof value === 'string') {
14
+ write('"');
15
+ for (let start = 0; start < value.length;) {
16
+ let end = Math.min(start + 65536, value.length);
17
+ if (end < value.length && value.charCodeAt(end - 1) >= 0xd800 && value.charCodeAt(end - 1) <= 0xdbff)
18
+ end--;
19
+ write(JSON.stringify(value.slice(start, end)).slice(1, -1));
20
+ start = end;
21
+ }
22
+ write('"');
23
+ return;
24
+ }
25
+ if (value === null || typeof value !== 'object') {
26
+ write(JSON.stringify(value) ?? 'null');
27
+ return;
28
+ }
29
+ if (Array.isArray(value)) {
30
+ write('[');
31
+ value.forEach((item, index) => { if (index)
32
+ write(','); hashValue(item, write, depth + 1); });
33
+ write(']');
34
+ return;
35
+ }
36
+ write('{');
37
+ let first = true;
38
+ for (const key of Object.keys(value).sort()) {
39
+ const item = value[key];
40
+ if (key === 'cache_control' || item === undefined)
41
+ continue;
42
+ if (!first)
43
+ write(',');
44
+ first = false;
45
+ write(JSON.stringify(key));
46
+ write(':');
47
+ hashValue(item, write, depth + 1);
48
+ }
49
+ write('}');
50
+ }
51
+ function sourceMessage(previous, next, row, offset) {
52
+ const message = row.message;
53
+ if (!object(message) || message.role !== row.type || message.content == null) {
54
+ sourceRuns.delete(next);
55
+ delete next.replayFrom;
56
+ return;
57
+ }
58
+ const role = message.role, messageId = typeof message.id === 'string' ? message.id : undefined;
59
+ const before = sourceRuns.get(previous);
60
+ if (offset !== undefined && before?.lastOffset !== undefined && offset <= before.lastOffset && offset !== previous.replayFrom)
61
+ return;
62
+ const restarting = offset !== undefined && offset === previous.replayFrom;
63
+ const same = !restarting && before?.role === role && (role === 'user' || (messageId !== undefined && messageId === before?.messageId));
64
+ const unprimed = !before && previous.replayFrom !== undefined && offset !== previous.replayFrom;
65
+ const run = same ? { ...before, value: before.value?.copy() } : {
66
+ role, ...(messageId ? { messageId } : {}), blocks: 0, bytes: 0,
67
+ ...(!unprimed ? { value: createHash('sha256').update('{"content":[') } : {}),
68
+ };
69
+ if (!same && !unprimed) {
70
+ if (offset !== undefined)
71
+ next.replayFrom = offset;
72
+ else
73
+ delete next.replayFrom;
74
+ }
75
+ run.lastOffset = offset;
76
+ sourceRuns.set(next, run);
77
+ if (!run.value)
78
+ return;
79
+ const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }]
80
+ : Array.isArray(message.content) ? message.content : [message.content];
81
+ try {
82
+ const write = (part) => {
83
+ run.bytes += Buffer.byteLength(part);
84
+ if (run.bytes > 64 * 1024 * 1024)
85
+ throw new Error('Native message hashing exceeds the byte bound.');
86
+ run.value.update(part);
87
+ };
88
+ for (const block of blocks) {
89
+ if (run.blocks++ > 100_000)
90
+ throw new Error('Native message hashing exceeds the block bound.');
91
+ if (run.blocks > 1)
92
+ write(',');
93
+ hashValue(block, write);
94
+ }
95
+ const digest = run.value.copy().update(`],"role":${JSON.stringify(role)}}`).digest('hex');
96
+ const known = next.blobs[digest];
97
+ put(next.blobs, digest, known && known.role !== role ? { role: 'unknown', complete: false, reason: 'A native transcript hash conflicts with its recorded role.' }
98
+ : { role, complete: true }, 8192);
99
+ }
100
+ catch {
101
+ delete run.value;
102
+ }
103
+ }
104
+ function policy(content, redact) {
105
+ const values = typeof content === 'string' ? [content] : Array.isArray(content)
106
+ && content.every(block => object(block) && block.type === 'text' && typeof block.text === 'string')
107
+ ? content.map(block => block.text) : undefined;
108
+ if (!values)
109
+ return refused('The native request contains unsupported system policy content.');
110
+ if (values.reduce((size, value) => size + Buffer.byteLength(value) + 2, 0) > POLICY_BYTES)
111
+ return refused('The native request policy exceeds the 256 KiB evidence limit.');
112
+ const original = values.join('\n\n');
113
+ let text;
114
+ try {
115
+ text = redact(original);
116
+ }
117
+ catch {
118
+ return refused('The native request policy could not be safely captured.');
119
+ }
120
+ if (typeof text !== 'string' || Buffer.byteLength(text) > POLICY_BYTES)
121
+ return refused('The native request policy exceeds the 256 KiB evidence limit.');
122
+ return { text, complete: text === original, ...(text !== original ? { reason: 'The native request policy contains withheld or redacted text.' } : {}) };
123
+ }
124
+ function put(map, key, value, limit) {
125
+ delete map[key];
126
+ map[key] = value;
127
+ while (Object.keys(map).length > limit)
128
+ delete map[Object.keys(map)[0]];
129
+ }
130
+ function bounded(state) {
131
+ // Eviction only removes reconstruction inputs. A later request referring to an evicted
132
+ // record becomes explicitly incomplete; the independently retained current snapshot stays pinned.
133
+ while (Buffer.byteLength(JSON.stringify(state)) > CACHE_BYTES) {
134
+ const map = Object.keys(state.requests).length ? state.requests : Object.keys(state.blobs).length ? state.blobs : state.shapes;
135
+ const key = Object.keys(map)[0];
136
+ if (!key) {
137
+ state.current = state.current ? { prompt: state.current.prompt, ...refused('The native request cache exceeds its evidence limit.') } : undefined;
138
+ break;
139
+ }
140
+ delete map[key];
141
+ }
142
+ return state;
143
+ }
144
+ /** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
145
+ * never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
146
+ export function updateClaudeWire(state, row, options) {
147
+ const previous = state ?? { version: 1, shapes: {}, blobs: {}, requests: {} };
148
+ if (!object(row) || row.agentId || row.isSidechain || !['user', 'assistant', 'attachment', 'api-request-shape', 'api-request-blob', 'api-request'].includes(row.type))
149
+ return previous;
150
+ const next = { ...previous, shapes: { ...previous.shapes }, blobs: { ...previous.blobs }, requests: { ...previous.requests } };
151
+ const run = sourceRuns.get(previous);
152
+ if (run)
153
+ sourceRuns.set(next, run);
154
+ if (row.type === 'user' || row.type === 'assistant') {
155
+ sourceMessage(previous, next, row, Number.isSafeInteger(options.recordOffset) && options.recordOffset >= 0 ? options.recordOffset : undefined);
156
+ return bounded(next);
157
+ }
158
+ if (row.type === 'attachment') {
159
+ const attachment = row.attachment;
160
+ if (object(attachment) && attachment.type === 'total_tokens_reminder' && row.renderedRole === 'system'
161
+ && typeof attachment.text === 'string' && /^<total_tokens>(?:\d{1,20}|Infinite) tokens left<\/total_tokens>$/.test(attachment.text)
162
+ && Array.isArray(row.rendered) && row.rendered.length === 1
163
+ && row.rendered[0]?.content === `<system-reminder>\n${attachment.text}\n</system-reminder>`) {
164
+ next.reminders = [...(next.reminders ?? []).filter(text => text !== attachment.text), attachment.text].slice(-256);
165
+ }
166
+ return bounded(next);
167
+ }
168
+ if (row.type === 'api-request-shape') {
169
+ if (!hash(row.shapeHash))
170
+ return previous;
171
+ const captured = object(row.shape) ? policy(row.shape.system, options.redact) : refused('The native request shape has no captured system policy.');
172
+ const known = next.shapes[row.shapeHash];
173
+ put(next.shapes, row.shapeHash, known && JSON.stringify(known) !== JSON.stringify(captured)
174
+ ? refused('A native shape hash was reused for different policy.') : captured, 128);
175
+ return bounded(next);
176
+ }
177
+ if (row.type === 'api-request-blob') {
178
+ if (!hash(row.hash))
179
+ return previous;
180
+ const message = row.message;
181
+ const role = object(message) && typeof message.role === 'string' ? message.role : 'unknown';
182
+ const captured = ['system', 'developer'].includes(role)
183
+ ? { role, ...policy(message.content, options.redact) }
184
+ : ['user', 'assistant', 'tool'].includes(role) ? { role, complete: true }
185
+ : { role: 'unknown', complete: false, reason: 'A referenced native message has an unsupported role.' };
186
+ const known = next.blobs[row.hash];
187
+ put(next.blobs, row.hash, known && JSON.stringify(known) !== JSON.stringify(captured)
188
+ ? { role: 'unknown', complete: false, reason: 'A native message hash was reused for different policy.' } : captured, 8192);
189
+ return bounded(next);
190
+ }
191
+ const main = row.querySource === 'sdk' || (typeof row.querySource === 'string' && row.querySource.startsWith('repl_main_thread'));
192
+ const prompt = typeof options.promptId === 'string' && options.promptId.length > 0 && options.promptId.length <= 200 ? options.promptId : undefined;
193
+ const failCurrent = (reason) => { if (main)
194
+ next.current = prompt ? { prompt, ...refused(reason) } : undefined; };
195
+ if (!requestId(row.id) || !hash(row.shapeHash) || !Number.isSafeInteger(row.keep) || row.keep < 0 || row.keep > MAX_REFS
196
+ || !Array.isArray(row.tail) || row.tail.length > MAX_REFS || !row.tail.every(hash)) {
197
+ failCurrent('The native request has malformed or oversized reconstruction metadata.');
198
+ return bounded(next);
199
+ }
200
+ let reason;
201
+ const fail = (value) => { reason ??= value; };
202
+ let refs = [];
203
+ if (row.keep > 0) {
204
+ const base = requestId(row.base) ? next.requests[row.base] : undefined;
205
+ if (!base || !base.complete || base.refs.length < row.keep)
206
+ fail('The native request base is missing, incomplete, or shorter than its retained prefix.');
207
+ else
208
+ refs = base.refs.slice(0, row.keep);
209
+ }
210
+ if (refs.length + row.tail.length > MAX_REFS)
211
+ fail('The native request has too many referenced messages.');
212
+ else
213
+ refs.push(...row.tail);
214
+ if (Object.hasOwn(row, 'cut') || Object.hasOwn(row, 'withheld'))
215
+ fail('The native request declares cut or withheld evidence.');
216
+ const shape = next.shapes[row.shapeHash];
217
+ if (!shape)
218
+ fail('The native request shape is missing from the bounded policy cache.');
219
+ else if (!shape.complete)
220
+ fail(shape.reason ?? 'The native request shape policy is incomplete.');
221
+ const parts = [], stableParts = [];
222
+ let policyBytes = 0, oversized = false;
223
+ const include = (label, content, reminder = false) => {
224
+ if (!content || oversized)
225
+ return;
226
+ const size = Buffer.byteLength(label) + 1 + Buffer.byteLength(content) + (parts.length ? 2 : 0);
227
+ if (policyBytes + size > POLICY_BYTES) {
228
+ oversized = true;
229
+ fail('The reconstructed native policy exceeds the 256 KiB evidence limit.');
230
+ return;
231
+ }
232
+ parts.push(`${label}\n${content}`);
233
+ if (!reminder)
234
+ stableParts.push(`${label}\n${content}`);
235
+ policyBytes += size;
236
+ };
237
+ if (shape)
238
+ include('Native API system policy:', shape.text);
239
+ for (const ref of refs) {
240
+ const entry = next.blobs[ref];
241
+ if (!entry) {
242
+ fail('A native request message is missing from the bounded policy cache.');
243
+ continue;
244
+ }
245
+ if (!entry.complete)
246
+ fail(entry.reason ?? 'A referenced native policy message is incomplete.');
247
+ if (entry.role === 'system' || entry.role === 'developer')
248
+ include(`Native API ${entry.role} message:`, entry.text ?? '', entry.role === 'system' && (next.reminders ?? []).includes(entry.text ?? ''));
249
+ }
250
+ const text = oversized ? '' : parts.join('\n\n');
251
+ const known = next.requests[row.id];
252
+ if (known && (known.shapeHash !== row.shapeHash || JSON.stringify(known.refs) !== JSON.stringify(refs)))
253
+ fail('A native request identity was reused for different reconstruction metadata.');
254
+ put(next.requests, row.id, { shapeHash: row.shapeHash, refs, complete: !reason, ...(reason ? { reason } : {}) }, 32);
255
+ if (main)
256
+ next.current = prompt ? { prompt, text, stableText: oversized ? '' : stableParts.join('\n\n'), complete: !reason, ...(reason ? { reason } : {}) } : undefined;
257
+ return bounded(next);
258
+ }
@@ -0,0 +1,11 @@
1
+ type CliIO = {
2
+ stdout?: (text: string) => void;
3
+ stderr?: (text: string) => void;
4
+ stdin?: AsyncIterable<string | Uint8Array>;
5
+ fetch?: typeof fetch;
6
+ /** Test/packaging boundary: executable plus arguments, never evaluated while installing. */
7
+ command?: string[];
8
+ };
9
+ /** Installer/status command plus the bounded stdin worker invoked by ordinary CLI hooks. */
10
+ export declare function learningMain(argv: string[], io?: CliIO): Promise<number>;
11
+ export {};