@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.58

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 (108) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +64 -33
  3. package/dist/api-only.d.ts +2 -4
  4. package/dist/api-only.js +2 -4
  5. package/dist/box-paths.d.ts +4 -3
  6. package/dist/box-paths.js +7 -4
  7. package/dist/claude-login-token.d.ts +117 -0
  8. package/dist/claude-login-token.js +737 -0
  9. package/dist/claude-login.d.ts +52 -12
  10. package/dist/claude-login.js +164 -39
  11. package/dist/cli.js +7 -41
  12. package/dist/computer-attach.d.ts +35 -17
  13. package/dist/computer-attach.js +301 -49
  14. package/dist/computers.d.ts +10 -10
  15. package/dist/computers.js +5 -5
  16. package/dist/console/assets/{backend-DVhHzJX2.js → backend-CSAWUqtZ.js} +1 -1
  17. package/dist/console/assets/index-DPh29cyz.js +747 -0
  18. package/dist/console/index.html +1 -1
  19. package/dist/dial-relay.d.ts +25 -4
  20. package/dist/dial-relay.js +129 -1
  21. package/dist/env-switch.d.ts +1 -3
  22. package/dist/env-switch.js +1 -3
  23. package/dist/fal-price.d.ts +1 -3
  24. package/dist/fal-price.js +77 -26
  25. package/dist/learn/ledger.d.ts +170 -0
  26. package/dist/learn/ledger.js +218 -0
  27. package/dist/learn/promote.d.ts +3 -3
  28. package/dist/learn/promote.js +1 -1
  29. package/dist/learning-cost.d.ts +22 -20
  30. package/dist/learning-cost.js +15 -21
  31. package/dist/live-reach.d.ts +2 -0
  32. package/dist/live-reach.js +2 -0
  33. package/dist/mcp-api-only-origins.d.ts +8 -3
  34. package/dist/mcp-api-only-origins.js +17 -17
  35. package/dist/micro.d.ts +2 -0
  36. package/dist/micro.js +2 -0
  37. package/dist/model.d.ts +5 -4
  38. package/dist/model.js +7 -6
  39. package/dist/monid.d.ts +14 -1
  40. package/dist/monid.js +103 -26
  41. package/dist/openapi.js +34 -12
  42. package/dist/place-offers.d.ts +4 -0
  43. package/dist/place-offers.js +7 -4
  44. package/dist/provider.d.ts +2 -2
  45. package/dist/provider.js +9 -5
  46. package/dist/run-learning-served.d.ts +2 -2
  47. package/dist/run-view.d.ts +1 -2
  48. package/dist/run-view.js +2 -1
  49. package/dist/runner/adapter-loop.js +3 -16
  50. package/dist/runner/adapter-run-spec.d.ts +20 -13
  51. package/dist/runner/adapter-run-spec.js +57 -48
  52. package/dist/runner/beside.d.ts +9 -2
  53. package/dist/runner/beside.js +24 -7
  54. package/dist/runner/claim-secrets.d.ts +17 -15
  55. package/dist/runner/claim-secrets.js +32 -34
  56. package/dist/runner/cli-run-spec.js +21 -9
  57. package/dist/runner/held.d.ts +16 -4
  58. package/dist/runner/main.d.ts +11 -6
  59. package/dist/runner/main.js +12 -7
  60. package/dist/runner/mcp-claim.js +3 -2
  61. package/dist/runner/mcp-run.d.ts +3 -6
  62. package/dist/runner/mcp-run.js +3 -4
  63. package/dist/runner/presence.d.ts +11 -1
  64. package/dist/runner/presence.js +7 -0
  65. package/dist/runner/reflect-hook.js +1 -1
  66. package/dist/runner/run-child-host.d.ts +19 -8
  67. package/dist/runner/run-child-host.js +80 -34
  68. package/dist/runner/runner.d.ts +3 -0
  69. package/dist/runner/runner.js +1 -1
  70. package/dist/runner/save-slots.js +2 -1
  71. package/dist/runner/subagent.d.ts +11 -0
  72. package/dist/runner/subagent.js +17 -3
  73. package/dist/runner/workflow-first.d.ts +27 -14
  74. package/dist/runner/workflow-first.js +29 -22
  75. package/dist/runner/workflow-spec.js +1 -1
  76. package/dist/server.d.ts +18 -7
  77. package/dist/server.js +150 -64
  78. package/dist/slots.d.ts +9 -0
  79. package/dist/slots.js +45 -0
  80. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  81. package/dist/store/schema.d.ts +17 -0
  82. package/dist/store/schema.js +47 -1
  83. package/dist/store/sqlite/run-patch.d.ts +11 -1
  84. package/dist/store/sqlite/run-patch.js +29 -1
  85. package/dist/store/sqlite/store.js +72 -9
  86. package/dist/store/store.d.ts +14 -0
  87. package/dist/store-reads/learning.d.ts +81 -124
  88. package/dist/store-reads/learning.js +207 -286
  89. package/dist/template-eval.d.ts +19 -0
  90. package/dist/template-eval.js +92 -43
  91. package/dist/template-import.d.ts +0 -10
  92. package/dist/template-import.js +5 -10
  93. package/dist/timeline/web-calls.d.ts +12 -14
  94. package/dist/timeline/web-calls.js +14 -30
  95. package/dist/web-save.d.ts +4 -9
  96. package/dist/web-save.js +4 -43
  97. package/dist/workspace/attached-computers.d.ts +32 -9
  98. package/dist/workspace/attached-computers.js +77 -13
  99. package/dist/workspace/computer-deps.d.ts +6 -1
  100. package/dist/workspace/computer-deps.js +1 -1
  101. package/dist/workspace/computer-for-claim.js +6 -3
  102. package/dist/workspace/paired-route.d.ts +91 -0
  103. package/dist/workspace/paired-route.js +153 -0
  104. package/dist/wrapped.d.ts +8 -2
  105. package/dist/wrapped.js +21 -6
  106. package/package.json +12 -12
  107. package/templates/README.md +3 -3
  108. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -1,12 +1,4 @@
1
- // The API-only profile's MCP origins (AGENTRUN_API_ONLY_MCP_ORIGINS, env-switch.ts) held to past the save. The server
2
- // writes the list it started with into the store (`mcp.api_only_origins`), and removes it when it starts without the
3
- // profile, so every reader on that store holds a per_run server the token saved to the list as it is now. The readers
4
- // are the server's pin at an agent's save, a runner's first pin, a run's claim and each of its calls. Drop an origin and restart, and a
5
- // server the token saved there sends nothing more: no listing, no run's mcp_auth. A server saved from the owner's
6
- // signed-in session (which an API-only server doesn't serve) is the owner's, whenever it was saved, and the list does not
7
- // govern it. An API-only start with the setting
8
- // unset holds an empty list, so a per_run server the token saved with the profile off is refused until its origin is
9
- // listed; that start says so once in its log, naming each such server (offApiOnlyMcpServers).
1
+ // The API-only MCP origin list (API_ONLY_MCP_ORIGINS_ENV), held in the store past the save: the serve README's API-only section.
10
2
  import { mcpSourceKey, savedByToken } from "./mcp-sources.js";
11
3
  import { listMcpServers } from "./mcp-store.js";
12
4
  import { isObject } from "./validate.js";
@@ -26,12 +18,14 @@ export async function heldApiOnlyMcpOrigins(store) {
26
18
  return isObject(held) && Array.isArray(held.origins) ? held.origins : undefined;
27
19
  }
28
20
  /** Why the saved server `name` (`row`) can't be used, or undefined when it can. It can't be used when it is a per_run
29
- * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. */
30
- export async function offApiOnlyMcpOrigins(store, name, row) {
21
+ * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. `held`:
22
+ * the list a caller already read (heldApiOnlyMcpOrigins); without it, the list is read here, for a per_run row alone.
23
+ * Undefined means "not read", never "none held": a caller passes the list only when the store holds one. */
24
+ export async function offApiOnlyMcpOrigins(store, name, row, held) {
31
25
  if (row.auth !== "per_run")
32
26
  return undefined;
33
- const held = await heldApiOnlyMcpOrigins(store);
34
- if (!held)
27
+ const origins = held ?? (await heldApiOnlyMcpOrigins(store));
28
+ if (!origins)
35
29
  return undefined;
36
30
  if (!savedByToken(await store.settings.get(mcpSourceKey(name)), row.createdAt))
37
31
  return undefined;
@@ -42,16 +36,22 @@ export async function offApiOnlyMcpOrigins(store, name, row) {
42
36
  catch {
43
37
  origin = "";
44
38
  }
45
- if (held.includes(origin))
39
+ if (origins.includes(origin))
46
40
  return undefined;
47
- return `The MCP server ${name} can't be used: the API token saved it at an origin that is no longer on this server's AGENTRUN_API_ONLY_MCP_ORIGINS. Nothing was sent.`;
41
+ return offApiOnlyMcpOriginsWords(name);
48
42
  }
43
+ /** The words a per_run server the token saved at an origin off the list is refused with (offApiOnlyMcpOrigins). */
44
+ export const offApiOnlyMcpOriginsWords = (name) => `The MCP server ${name} can't be used: the API token saved it at an origin that is no longer on this server's AGENTRUN_API_ONLY_MCP_ORIGINS. Nothing was sent.`;
49
45
  /** The names of the saved servers offApiOnlyMcpOrigins refuses now, sorted: none when the store holds no list. What an
50
- * API-only start says once in its log (server.ts), by name alone, never an address. */
46
+ * API-only start says once in its log (server.ts), by name alone, never an address: on an upgrade with the setting
47
+ * unset, the only notice before a run that grants one fails. */
51
48
  export async function offApiOnlyMcpServers(store) {
49
+ const held = await heldApiOnlyMcpOrigins(store);
50
+ if (!held)
51
+ return [];
52
52
  const off = [];
53
53
  for (const row of await listMcpServers(store))
54
- if (await offApiOnlyMcpOrigins(store, row.name, row))
54
+ if (await offApiOnlyMcpOrigins(store, row.name, row, held))
55
55
  off.push(row.name);
56
56
  return off.sort();
57
57
  }
@@ -0,0 +1,2 @@
1
+ /** A dollar figure rounded to the micro-dollar (6 places), as the server books and shows money. A leaf module. */
2
+ export declare const micro: (usd: number) => number;
package/dist/micro.js ADDED
@@ -0,0 +1,2 @@
1
+ /** A dollar figure rounded to the micro-dollar (6 places), as the server books and shows money. A leaf module. */
2
+ export const micro = (usd) => Math.round(usd * 1e6) / 1e6;
package/dist/model.d.ts CHANGED
@@ -162,10 +162,11 @@ export declare const PROVIDER_KEYS: Readonly<Record<string, readonly string[]>>;
162
162
  /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
163
163
  export declare const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
164
164
  /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
165
- * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
166
- * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
167
- * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
168
- export declare function modelKeys(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[]): string[];
165
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's from `tierRefs`
166
+ * (a revision's model_tiers, as runModels takes them) else the host's model of that tier; through a gateway
167
+ * (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as chooseModel is, faux or not, so a
168
+ * run on the faux model is handed what a run on its model would be. */
169
+ export declare function modelKeys(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[], tierRefs?: Readonly<Partial<Record<Tier, string>>>): string[];
169
170
  /** `value` as a thinking level (THINKING_LEVELS, exactly), else undefined: a revision's `thinking` or the host's
170
171
  * `AGENT_THINKING` that names none is no level. A run's effort is its own, else these (runs-over-store.ts prepareLaunch). */
171
172
  export declare function thinkingLevel(value: unknown): ThinkingLevel | undefined;
package/dist/model.js CHANGED
@@ -188,7 +188,7 @@ export const MODEL_SOURCES = ["faux", "gateway", "providers", "chatgpt"];
188
188
  export function modelSource(env) {
189
189
  const each = (name) => Object.fromEntries(TIERS.map((tier) => [tier, name(tier)]));
190
190
  if (env[FAUX_ENV])
191
- return { source: "faux", route_prefix: null, ...each((tier) => `faux/${fauxModel(env, tier)}`) };
191
+ return { source: "faux", route_prefix: null, ...each((tier) => `${FAUX_PROVIDER}/${fauxModel(env, tier)}`) };
192
192
  if (env.AGENT_MODEL_BASE_URL)
193
193
  return { source: "gateway", route_prefix: MODEL_PROVIDER, ...each((tier) => (hostModel(env, tier) ? `${MODEL_PROVIDER}/${hostModel(env, tier)}` : null)) };
194
194
  if (signedIn(env) && !Object.values(PROVIDER_KEYS).flat().some((name) => env[name]))
@@ -397,13 +397,14 @@ const REQUEST_KEYS = PROVIDER_KEYS["amazon-bedrock"];
397
397
  /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
398
398
  export const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
399
399
  /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
400
- * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
401
- * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
402
- * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
403
- export function modelKeys(env, ref, tiers = ["default"]) {
400
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's from `tierRefs`
401
+ * (a revision's model_tiers, as runModels takes them) else the host's model of that tier; through a gateway
402
+ * (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as chooseModel is, faux or not, so a
403
+ * run on the faux model is handed what a run on its model would be. */
404
+ export function modelKeys(env, ref, tiers = ["default"], tierRefs = {}) {
404
405
  if (env.AGENT_MODEL_BASE_URL)
405
406
  return [GATEWAY_KEY_ENV];
406
- const named = tiers.map((tier) => (tier === "default" ? ref : undefined) ?? hostModel(env, tier));
407
+ const named = tiers.map((tier) => (tier === "default" ? ref : tierRefs[tier]) ?? hostModel(env, tier));
407
408
  const providers = named.flatMap((name) => (name && name.indexOf("/") > 0 ? [name.slice(0, name.indexOf("/"))] : []));
408
409
  return [...new Set(providers.flatMap((provider) => PROVIDER_KEYS[provider] ?? []))];
409
410
  }
package/dist/monid.d.ts CHANGED
@@ -25,6 +25,8 @@ export type MonidOptions = {
25
25
  /** The most a run is waited for, its first request and every read together (150 s: monid's runs take 1 to 120 s). */
26
26
  waitMs?: number;
27
27
  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
28
+ /** When a save's reads (the listing, an inspect) stop being sent (epoch ms); READ_BUDGET_MS after the first, unset. */
29
+ readsEnd?: number;
28
30
  };
29
31
  /** What a run's answer says monid charged, in USD: its cost; else undefined when monid charged nothing (UNCHARGED), and
30
32
  * null for every other answer, which may have been charged (one with no cost, FAILED, TIMED_OUT, a run stopped by its
@@ -77,16 +79,27 @@ type MonidPinOutcome = {
77
79
  message: string;
78
80
  }[];
79
81
  };
82
+ /** One server's reads of monid's listing and inspects, shared by its saves (monidReads). */
83
+ export type MonidReads = Map<string, {
84
+ answer: Promise<unknown>;
85
+ at?: number;
86
+ }>;
87
+ /** The reads one server's saves share, by key and what is read: a read out now is joined, not sent again, and one that
88
+ * answered is reused for SHARED_READ_MS. One that failed is dropped once it ends: the next save reads anew. */
89
+ export declare const monidReads: () => MonidReads;
80
90
  /** The monid grants among `grants` pinned against monid's listing on `key` (pinned at a save, never at a run): each
81
91
  * provider's wildcard read as the endpoints monid lists for it now (at most MONID_WILDCARD_MAX), each endpoint inspected
82
92
  * for its description, input and price; a grant `previous` made too carries its pin, unread (as server.ts mcpListingOf).
83
93
  * A grant monid lists nothing for is refused, as is every grant to read with no key or monid unreadable. An endpoint
84
- * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's. */
94
+ * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's.
95
+ * With `shared` (monidReads), the listing and each inspect are read once for the saves that ask at once. */
85
96
  export declare function pinMonid(grants: readonly string[], options: {
86
97
  key: string | undefined;
87
98
  fetch?: typeof fetch;
88
99
  signal?: AbortSignal;
89
100
  sleep?: MonidOptions["sleep"];
101
+ shared?: MonidReads;
102
+ budgetMs?: number;
90
103
  previous?: {
91
104
  grants: readonly string[];
92
105
  pin: MonidPinBody | null;
package/dist/monid.js CHANGED
@@ -5,7 +5,10 @@
5
5
  // At the save (server.ts saveable, the one check of a create, an edit and an inline run): each grant is read against
6
6
  // monid's listing (a provider's wildcard: every endpoint it lists, GET /v1/endpoints; one endpoint: POST /v1/inspect),
7
7
  // and the pin is stamped on the revision, a grant its current revision made too carried unread. A grant monid does not
8
- // list is refused in words, so is one that cannot be read now (no key, monid unreachable). A run reads only its pin.
8
+ // list is refused in words, so is one that cannot be read now (no key, monid unreachable). A read monid refuses for its
9
+ // rate, fails (5xx) or leaves unanswered past its limit is sent again inside the save's time (READ_BUDGET_MS, from the
10
+ // save's start), and one server's saves share each read (monidReads): saves that arrive together read the listing once,
11
+ // each waiting on it no longer than its own time. A run reads only its pin.
9
12
  //
10
13
  // An endpoint priced by usage (per result, per unit, metered, a matrix or tier with a usage part) is pinned too, with no
11
14
  // fixed price, and the save's warnings name it (usageWords): monid can't cap what such a call charges. Its maxCost
@@ -25,7 +28,7 @@
25
28
  // provider answers 202 with a run id, read again every POLL_MS until it ends, for at most WAIT_MS in all; a run the
26
29
  // caller stops, or one that outlasts the wait, is asked to stop. Every answer reaches the model as JSON, cut at CLIP
27
30
  // characters, the whole of it then filed under the run's work/evidence/monid/.
28
- import { randomUUID } from "node:crypto";
31
+ import { createHash, randomUUID } from "node:crypto";
29
32
  import { workspaceErrorWords } from "./workspace/index.js";
30
33
  import { wireName } from "./catalog.js";
31
34
  import { formatToolName, monidNameOf, parseToolName, sameWireWords } from "./tool-names.js";
@@ -45,10 +48,20 @@ const TERMINAL = ["COMPLETED", "FAILED", "BLOCKED", "STOPPED", "TIMED_OUT"];
45
48
  const MIN_READ_MS = 100;
46
49
  /** How many inspects a save has out at once. */
47
50
  const INSPECTS_AT_ONCE = 8;
48
- /** A save's read of the listing or an inspect, refused for the rate (429) or failed by monid (5xx), is read again after
49
- * what monid says to wait (Retry-After, 2 s when it says nothing, at most READ_WAIT_MS), READ_TRIES times in all. */
50
- const READ_TRIES = 4;
51
+ /** A save's read of the listing or an inspect, refused for the rate (429), failed by monid (5xx) or not answered in
52
+ * time, is sent again after what monid says to wait (Retry-After, 2 s when it says nothing, at least READ_WAIT_MIN_MS
53
+ * and at most READ_WAIT_MS), at most READ_RESENDS times, while that read's waits add up to at most READ_WAITS_MS and
54
+ * the save is inside READ_BUDGET_MS of its start: a burst of saves on one key waits out monid's rate inside the save's
55
+ * own time, and only then is refused. */
56
+ const READ_WAIT_MIN_MS = 250;
51
57
  const READ_WAIT_MS = 10_000;
58
+ const READ_WAITS_MS = 20_000;
59
+ const READ_RESENDS = 20;
60
+ const READ_BUDGET_MS = 45_000;
61
+ /** Why a save's read is not sent, or not waited on, past its time (READ_BUDGET_MS). */
62
+ const OUT_OF_TIME = "no answer within the save's time";
63
+ /** How long one server's saves share a read of monid's listing or an inspect that answered (monidReads). */
64
+ const SHARED_READ_MS = 60_000;
52
65
  /** On an answer monid charged nothing for: the run never ran (refused as sent), was blocked or stopped, or the provider
53
66
  * failed. A symbol, so the model never reads it. */
54
67
  const UNCHARGED = Symbol("monid.uncharged");
@@ -137,17 +150,27 @@ export function monidClient(options) {
137
150
  return { status: res.status, body: isObject(json) ? json : { message: text.slice(0, 500) }, ...(retryAfter >= 0 ? { retryAfter } : {}) };
138
151
  }
139
152
  catch (error) {
140
- return { status: 0, body: { message: signal?.aborted ? "stopped by the caller" : limit.aborted ? `no answer in ${ms / 1000} s` : String(error?.message ?? error) } };
153
+ const timedOut = !signal?.aborted && limit.aborted;
154
+ return { status: 0, body: { message: signal?.aborted ? "stopped by the caller" : timedOut ? `no answer in ${ms / 1000} s` : String(error?.message ?? error) }, ...(timedOut ? { timedOut: true } : {}) };
141
155
  }
142
156
  };
143
157
  const answer = (res) => (res.status >= 200 && res.status < 300 ? res.body : failure(res.status, res.body));
144
- /** A save's read, safe to repeat (READ_TRIES). */
158
+ /** When this client's reads stop being sent (READ_BUDGET_MS after its first, unless given). */
159
+ let readsEnd = options.readsEnd;
160
+ /** A save's read, safe to repeat (READ_WAITS_MS, READ_BUDGET_MS); any other refusal (401, 403, 404), or monid out of
161
+ * reach (a request that failed before its limit), is its answer. */
145
162
  const read = async (method, path, body, signal) => {
146
- for (let tries = 1;; tries++) {
147
- const res = await call(method, path, body, signal);
148
- if ((res.status !== 429 && res.status < 500) || tries >= READ_TRIES || signal?.aborted)
163
+ const end = (readsEnd ??= Date.now() + READ_BUDGET_MS);
164
+ if (Date.now() >= end)
165
+ return { status: 0, body: { message: OUT_OF_TIME } };
166
+ for (let waited = 0, resends = 0;; resends++) {
167
+ const res = await call(method, path, body, signal, Math.min(requestMs, Math.max(MIN_READ_MS, end - Date.now())));
168
+ const wait = Math.min(READ_WAIT_MS, Math.max(READ_WAIT_MIN_MS, (res.retryAfter ?? 2) * 1000));
169
+ const again = res.status === 429 || res.status >= 500 || res.timedOut === true;
170
+ if (!again || signal?.aborted || resends >= READ_RESENDS || waited + wait > READ_WAITS_MS || Date.now() + wait >= end)
149
171
  return res;
150
- await sleep(Math.min(READ_WAIT_MS, (res.retryAfter ?? 2) * 1000), signal);
172
+ waited += wait;
173
+ await sleep(wait, signal);
151
174
  }
152
175
  };
153
176
  const stop = async (runId, why) => {
@@ -280,12 +303,54 @@ function inputSchema(input) {
280
303
  }
281
304
  return { type: "object", additionalProperties: false, properties, ...(required.length ? { required } : {}) };
282
305
  }
306
+ /** The reads one server's saves share, by key and what is read: a read out now is joined, not sent again, and one that
307
+ * answered is reused for SHARED_READ_MS. One that failed is dropped once it ends: the next save reads anew. */
308
+ export const monidReads = () => new Map();
309
+ /** `read`'s answer, shared through `reads` under `id` (monidReads): joined while it is out, kept while `kept` says it
310
+ * answered. A save that joins a read another started waits on it until its own `end` at most, then has `late()`.
311
+ * Without `reads`, read alone. */
312
+ function sharedRead(reads, id, read, kept, end, late) {
313
+ if (!reads)
314
+ return read();
315
+ const now = Date.now();
316
+ for (const [one, entry] of reads)
317
+ if (entry.at !== undefined && now - entry.at >= SHARED_READ_MS)
318
+ reads.delete(one);
319
+ const had = reads.get(id);
320
+ if (had) {
321
+ if (had.at !== undefined)
322
+ return had.answer;
323
+ let timer;
324
+ const lateness = new Promise((resolve) => (timer = setTimeout(() => resolve(late()), Math.max(0, end - now))));
325
+ return Promise.race([had.answer, lateness]).finally(() => clearTimeout(timer));
326
+ }
327
+ const entry = {
328
+ answer: read().then((answer) => {
329
+ if (reads.get(id) !== entry)
330
+ return answer;
331
+ if (kept(answer))
332
+ entry.at = Date.now();
333
+ else
334
+ reads.delete(id);
335
+ return answer;
336
+ }, (error) => {
337
+ if (reads.get(id) === entry)
338
+ reads.delete(id);
339
+ throw error;
340
+ }),
341
+ };
342
+ reads.set(id, entry);
343
+ return entry.answer;
344
+ }
283
345
  /** The monid grants among `grants` pinned against monid's listing on `key` (pinned at a save, never at a run): each
284
346
  * provider's wildcard read as the endpoints monid lists for it now (at most MONID_WILDCARD_MAX), each endpoint inspected
285
347
  * for its description, input and price; a grant `previous` made too carries its pin, unread (as server.ts mcpListingOf).
286
348
  * A grant monid lists nothing for is refused, as is every grant to read with no key or monid unreadable. An endpoint
287
- * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's. */
349
+ * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's.
350
+ * With `shared` (monidReads), the listing and each inspect are read once for the saves that ask at once. */
288
351
  export async function pinMonid(grants, options) {
352
+ // The save's reads stop READ_BUDGET_MS (or `budgetMs`) after it starts, a wait on another save's read included.
353
+ const readsEnd = Date.now() + (options.budgetMs ?? READ_BUDGET_MS);
289
354
  const pin = {};
290
355
  const before = options.previous;
291
356
  const named = grants.flatMap((tool) => {
@@ -304,7 +369,7 @@ export async function pinMonid(grants, options) {
304
369
  const reads = named.filter((grant) => grant.read && !(grant.parsed.kind === "monid" && pin[grant.tool]));
305
370
  if (reads.length && !options.key)
306
371
  return { refused: reads.map(({ tool }) => ({ tool, message: `${tool} is pinned to what monid lists when the agent is saved, and there is no monid key here to read it with: save the monid key in Settings → API Keys first.` })) };
307
- const refused = reads.length ? await readPins(reads, pin, { ...options, key: options.key }) : [];
372
+ const refused = reads.length ? await readPins(reads, pin, { ...options, key: options.key, readsEnd }) : [];
308
373
  // Two endpoints the harnesses would call by one name (wireName folds `.` and `/`): neither could be told apart.
309
374
  const wires = new Map();
310
375
  for (const tool of Object.keys(pin).sort()) {
@@ -322,28 +387,40 @@ export async function pinMonid(grants, options) {
322
387
  }
323
388
  /** The grants `reads` read against monid's listing into `pin`; why each that could not be is refused. */
324
389
  async function readPins(named, pin, options) {
325
- const client = monidClient({ key: options.key, ...(options.fetch ? { fetch: options.fetch } : {}), ...(options.sleep ? { sleep: options.sleep } : {}) });
390
+ const { readsEnd } = options;
391
+ const client = monidClient({ key: options.key, readsEnd, ...(options.fetch ? { fetch: options.fetch } : {}), ...(options.sleep ? { sleep: options.sleep } : {}) });
326
392
  // monid's own words, which a save's refusal returns to its caller: the key they were read with cut from them, in
327
393
  // every form a run's error is redacted of (key-refusal.ts redacted).
328
394
  const key = options.key;
329
395
  const said = (error) => redacted(String(error), [key]);
396
+ // The shared reads are told apart by a digest of the key they were read with, never the key.
397
+ const keyId = createHash("sha256").update(key).digest("hex");
330
398
  const refused = [];
331
399
  // Each endpoint to pin, by catalog name: each wildcard's provider's as monid lists them, then the grants' own.
332
400
  const wanted = new Map();
333
401
  const providers = new Set(named.flatMap(({ parsed }) => (parsed.kind === "monid-provider" ? [parsed.provider] : [])));
334
402
  if (providers.size) {
335
- const listed = new Map();
336
- // Every page, a bounded number of them: monid's listing is not filtered by provider.
337
- for (let cursor, page = 0; (page === 0 || cursor) && page < 500; page++) {
338
- const res = await client.endpoints(cursor, options.signal);
339
- if (res.error !== undefined)
340
- return named.map(({ tool }) => ({ tool, message: `${tool} could not be pinned: monid's listing could not be read (${said(res.error)}).` }));
341
- for (const item of Array.isArray(res.items) ? res.items : []) {
342
- if (isObject(item) && typeof item.provider === "string" && typeof item.endpoint === "string" && providers.has(item.provider))
343
- listed.set(item.provider, [...(listed.get(item.provider) ?? []), item.endpoint]);
403
+ // Every provider's endpoints, every page, a bounded number of them: monid's listing is not filtered by provider.
404
+ const listing = await sharedRead(options.shared, `${keyId} listing`, async () => {
405
+ const listed = new Map();
406
+ for (let cursor, page = 0; (page === 0 || cursor) && page < 500; page++) {
407
+ const res = await client.endpoints(cursor, options.signal);
408
+ if (res.error !== undefined)
409
+ return { error: res.error };
410
+ for (const item of Array.isArray(res.items) ? res.items : []) {
411
+ if (isObject(item) && typeof item.provider === "string" && typeof item.endpoint === "string") {
412
+ const endpoints = listed.get(item.provider) ?? [];
413
+ listed.set(item.provider, endpoints);
414
+ endpoints.push(item.endpoint);
415
+ }
416
+ }
417
+ cursor = typeof res.cursor === "string" && res.cursor ? res.cursor : undefined;
344
418
  }
345
- cursor = typeof res.cursor === "string" && res.cursor ? res.cursor : undefined;
346
- }
419
+ return { listed };
420
+ }, (answer) => "listed" in answer, readsEnd, () => ({ error: OUT_OF_TIME }));
421
+ if ("error" in listing)
422
+ return named.map(({ tool }) => ({ tool, message: `${tool} could not be pinned: monid's listing could not be read (${said(listing.error)}).` }));
423
+ const { listed } = listing;
347
424
  for (const { tool, parsed } of named) {
348
425
  if (parsed.kind !== "monid-provider")
349
426
  continue;
@@ -365,7 +442,7 @@ async function readPins(named, pin, options) {
365
442
  const inspectOne = async () => {
366
443
  for (let next = queue.shift(); next; next = queue.shift()) {
367
444
  const [tool, at] = next;
368
- const res = await client.inspect(at, options.signal);
445
+ const res = await sharedRead(options.shared, `${keyId} inspect ${JSON.stringify([at.provider, at.endpoint])}`, () => client.inspect(at, options.signal), (answer) => answer.error === undefined, readsEnd, () => ({ error: OUT_OF_TIME }));
369
446
  if (res.status === 404)
370
447
  refused.push({ tool, message: `monid lists no endpoint ${at.endpoint} of a provider ${at.provider}.` });
371
448
  else if (res.error !== undefined)
package/dist/openapi.js CHANGED
@@ -72,6 +72,7 @@ import { tableTools } from "./tool-list.js";
72
72
  import { SECRET_META_SCHEMA } from "./secret-writes.js";
73
73
  import { LABEL_KEY, MAX_LABEL_VALUE, MAX_LABELS } from "./run-labels.js";
74
74
  import { COST_BASES } from "./runner/metrics.js";
75
+ import { PAST_RUNS } from "./runner/workflow-first.js";
75
76
  import { BASH_POLICIES } from "./bash-read-only.js";
76
77
  // The modules that own the computer and Archil key writes: loading the document loads their secret-write predicates
77
78
  // (secret-writes.ts registerSecretWrite), so every operation the document marks has its predicate wherever it is read.
@@ -95,6 +96,13 @@ const LABEL_PARAMETER = {
95
96
  schema: { type: "string" },
96
97
  "x-agentrun-serve": "runlabels/1",
97
98
  };
99
+ /** runsource/1: GET /runs' filter on where a run came from. */
100
+ const SOURCE_PARAMETER = {
101
+ name: "source", in: "query", required: false,
102
+ description: "Only runs imported from this source, a source's name as the run's `imported_from.source` holds it (`claude-code`, `codex`, ...), or `live` for the runs made here, not imported. A name no run holds lists none. Once per request; a second `source`, or one that does not read as a name, is 400.",
103
+ schema: { type: "string" },
104
+ "x-agentrun-serve": "runsource/1",
105
+ };
98
106
  /** Why each capability this server turns off answers 501, by the route's capability. */
99
107
  export const UNSUPPORTED = {
100
108
  quotes: "This server has no billing, so it gives no quotes.",
@@ -153,8 +161,8 @@ const WRAPPED = closed({
153
161
  hours: { type: "array", minItems: 24, maxItems: 24, items: COUNT, description: "Requests by local hour of the day." },
154
162
  weekdays: { type: "array", minItems: 7, maxItems: 7, items: COUNT, description: "Requests by local weekday, Sunday first." },
155
163
  active_ms: { ...COUNT, description: "Time at work: the gaps between a session's requests, each counted when under 15 minutes." },
156
- harnesses: { type: "array", items: closed({ harness: { type: "string" }, sessions: COUNT, requests: COUNT, tokens: COUNT }), description: "By the harness that runs what each source ran, most tokens first." },
157
- models: { type: "array", items: closed({ model: { type: "string", description: "`provider/model`, or `unknown` for a request that names none." }, requests: COUNT, tokens: COUNT, cost_usd: { type: "number", minimum: 0 } }), description: "By the request's model, most tokens first." },
164
+ harnesses: { type: "array", items: closed({ harness: { type: "string" }, sessions: COUNT, requests: COUNT, tokens: COUNT, sources: { type: "array", items: { type: "string" }, description: "The sources read for this harness, in the order of `sources`: several can share one. Each is a `source` of `sources` and of `imported`." } }), description: "By the harness that runs what each source ran, most tokens first." },
165
+ models: { type: "array", items: closed({ model: { type: "string", description: "`provider/model`, or `unknown` for a request that names none." }, requests: COUNT, tokens: COUNT, cost_usd: { type: "number", minimum: 0, description: "The list price of the model's requests that could be priced." }, unpriced_requests: { ...COUNT, description: "Of the model's requests, those `cost_usd` leaves out: all of them when no price was known for it." } }), description: "By the request's model, most tokens first." },
158
166
  sources: { type: "array", items: closed({ source: { type: "string" }, sessions: COUNT, requests: COUNT }), description: "By the tool the sessions were read from." },
159
167
  imported: { type: "array", items: closed({ source: { type: "string" }, runs: COUNT }), description: "The runs imported here in the year, by source (never `live`)." },
160
168
  unread_files: { ...COUNT, description: "Session files that could not be read (gone since listed, or not openable by this user), so the numbers are short by them. A count only: no path." },
@@ -1098,7 +1106,7 @@ const COMPUTER_PROVIDER_GPU = closedWith({
1098
1106
  why: { type: "string", description: "Why a run on this server cannot have its GPUs: its GPU computers take no mount of this server's folder mode." },
1099
1107
  });
1100
1108
  /** `runs_refused` of a provider in Settings → Computers (computers.ts ProviderView; attached-computers.ts dialApartWords). */
1101
- const PROVIDER_RUNS_REFUSED = { type: ["string", "null"], description: "On a server whose runner runs in a process of its own (`--no-runner`; the image's default `server-and-runner`), why no run here can use this provider's computers, and the one-line fix: start the image with the server options alone, without `server-and-runner`. Said for a provider whose machines dial this server (Fly Machines and Cloudflare), whose sockets the server's process takes and its runner never reaches, unless a runner of its relays their dials now (it knows the server's public address, AGENTRUN_PUBLIC_URL, and the server relays each machine's socket to it); and for a paired computer, always. Its test (POST /computers/{provider}/test) fails in the same words. Null where this server's runs can use it." };
1109
+ const PROVIDER_RUNS_REFUSED = { type: ["string", "null"], description: "On a server whose runner runs in a process of its own (`--no-runner`; the image's default `server-and-runner`), why no run here can use this provider's computers, and the one-line fix: start the image with the server options alone, without `server-and-runner`. Said for a provider whose machines dial this server (Fly Machines and Cloudflare), whose sockets the server's process takes and its runner never reaches, unless a runner of its relays their dials now (it knows the server's public address, AGENTRUN_PUBLIC_URL, and the server relays each machine's socket to it). Its test (POST /computers/{provider}/test) fails in the same words. Null where this server's runs can use it." };
1102
1110
  /** A provider in Settings → Computers (computers.ts ProviderView). */
1103
1111
  const COMPUTER_PROVIDER = closedWith({
1104
1112
  id: { type: "string", description: "The provider's id, as an agent's `computer.provider` names it (PUT /computers/{provider}/keys)." },
@@ -1124,7 +1132,7 @@ const COMPUTER_PROVIDER = closedWith({
1124
1132
  },
1125
1133
  });
1126
1134
  /** `runs_refused` of a pairing code, the pair answer and a paired computer (attached-computers.ts RUNNER_APART_WORDS). */
1127
- const RUNS_REFUSED = { type: ["string", "null"], description: "On a server whose runner runs in a process of its own (`--no-runner`; the image's default `server-and-runner`), why no run here can use a paired computer, and the one-line fix: start the image with the server options alone, without `server-and-runner`. A computer still pairs and attaches. Null where this server's runs can use it." };
1135
+ const RUNS_REFUSED = { type: ["string", "null"], description: "On a server whose runner runs in a process of its own (`--no-runner`; the image's default `server-and-runner`), why no run here can use a paired computer, and the fix: give the runner AGENTRUN_PUBLIC_URL (this server's public address), so the server relays a paired computer's socket to the runner whose run holds it, or start the image with the server options alone, without `server-and-runner`. Said only while no runner relays; null once one does. A computer still pairs and attaches. Null where this server's runs can use it." };
1128
1136
  /** A paired computer in GET /computers' `paired` (computer-attach.ts PairedView). */
1129
1137
  const PAIRED_COMPUTER = closed({
1130
1138
  id: { type: "string", description: "Its id: an agent's `computer.provider` names it (`{kind: \"desktop\", provider: <id>}`), and DELETE /computers/{computer_id} removes it." },
@@ -1141,9 +1149,11 @@ const PAIRED_COMPUTER = closed({
1141
1149
  groups: { type: "array", items: { type: "string" }, description: "The capability groups its driver offers: its live hello's while it is attached, else its last hello's. A run uses only these." },
1142
1150
  features: { type: "object", additionalProperties: { oneOf: [{ const: true }, closed({ off: { type: "string", description: "Why it is off here, in words a person can act on." } })] }, description: "What its groups can and cannot do on it, by feature name (true, or off with why), as its driver says it: live while attached, else as paired." },
1143
1151
  driver: { type: "string", description: "Its driver's build: its live hello's while it is attached, else the one it last said." },
1144
- online: { type: "boolean", description: "Whether its driver is attached to this server now." },
1145
- held_by_run: { type: ["string", "null"], description: "The run that holds it now; null when none does." },
1152
+ online: { type: "boolean", description: "Whether its driver is attached now: to this server, or to a runner the server relays its socket to." },
1153
+ held_by_run: { type: ["string", "null"], description: "The run that holds it now, on this server or on a runner the server relays it to; null when none does." },
1146
1154
  held_until: { type: ["string", "null"], format: "date-time", description: "When the holding run's hold ends, released or not: the run's lifetime. Past it the run's connections close and the next run may claim it, and the computer stays attached. Null when no run holds it." },
1155
+ held_on: { type: ["string", "null"], description: "The runner whose run holds it, where the server relays its socket to a runner: the computer's dials go there while the run holds it, and come back to this server when the hold ends. Null when it is attached to this server." },
1156
+ hold_note: { type: ["string", "null"], description: "The server's note of why its last relay to a runner was refused or dropped (the runner restarted, or the run's runner is gone, and it comes back to this server at its next dial), or that it is attached nowhere and its driver must be opened, in words naming what to do. Null when nothing is wrong." },
1147
1157
  pairing: { type: "string", description: "The pairing (POST /computers/pairings' `id`) whose code paired it." },
1148
1158
  created_at: { type: "string", format: "date-time", description: "When it was paired." },
1149
1159
  seen_at: { type: ["string", "null"], format: "date-time", description: "When it last attached; null before its first." },
@@ -1713,7 +1723,7 @@ const WRITE_DESCRIPTION = "As a person: one host commit on main in the agent's q
1713
1723
  /** GET /agents/{agent_id}/learning/cost (learning-cost.ts, store-reads/learning.ts agentCostOverStore). */
1714
1724
  const COST_USD = (description) => ({ type: ["number", "null"], minimum: 0, description: `${description} As booked (its float noise rounded off at 1e-12, the precision of a run's own cost): a decision's sub-micro-dollar cost is in it; null when unknown, never 0 for unknown.` });
1715
1725
  const COST_MEAN = (description) => ({ oneOf: [closed({ runs: { ...COUNT, minimum: 1, description: "How many runs the mean is over." }, mean_usd: { type: "number", minimum: 0, description: "Their mean, rounded to 1e-6." } }), { type: "null" }], description });
1716
- const COST_RUN = closed({
1726
+ const COST_RUN = closedWith({
1717
1727
  n: { type: ["integer", "null"], minimum: 1, description: "The run's place among the agent's runs that do a job (`agent`, `workflow` and `handed_back`), oldest first, as `bill.points` number them: 1 is its first. Null for a `replay`: it checks a revision and does no job." },
1718
1728
  run_id: { type: "string" },
1719
1729
  started_at: DATE_TIME,
@@ -1726,6 +1736,12 @@ const COST_RUN = closed({
1726
1736
  cost_upper_bound: { type: "boolean", description: "The run's stored cost is only a bound (its row's `costAtMostUsd`: a model request cut at its cap hold): `cost_usd` and `total_usd` are null, never a known cost. `summary` counts such a run as `at_most`, not `unknown`." },
1727
1737
  learning_usd: COST_USD("What learning cost for the run: its compile turn. 0 for a run that does not learn or was not asked one. An audit's shadow run of it is its learning too: null while that shadow is queued or running, never $0."),
1728
1738
  total_usd: COST_USD("The run's all-in cost, `cost_usd` and `learning_usd` together; null when either is."),
1739
+ }, {
1740
+ compile_usd: COST_USD("The compile turns the run's own session asked: its revision's spend, never its own (`bill.revisions`), or no run's when it kept no draft (`bill.unattributed_usd`). GET /runs/{id} `cost.compile_usd` is the same figure. 0 for a run asked none."),
1741
+ followup_usd: COST_USD("What the run's learning spent after its job answered besides its compile turns (a follow-up round's turns): a part of its GET /runs/{id} `cost.learning_usd`, the same figure there."),
1742
+ shadow_usd: COST_USD("Its audit shadow's cost (0 when none ran): a part of its GET /runs/{id} `cost.learning_usd`, the same figure there. Null while the shadow is queued or running."),
1743
+ share_usd: COST_USD("Its share of the learning spend of the revision that served it (`bill.revisions`): a part of its GET /runs/{id} `cost.learning_usd`, the same figure there. 0 for a run no revision served."),
1744
+ not_served: { enum: ["cost_stop", "cut", null], description: "Why a learned workflow did not serve the run alone, when one was there to: `cost_stop`, the money rule stopped it (its served runs cost as much as the agent by hand); `cut`, a restart cut the workflow's call and the run was handed back (`handed_back` at agent cost, counted in the summary's `hand_backs.cut`, never `back`). Null otherwise." },
1729
1745
  });
1730
1746
  const LEARNING_COST = closed({
1731
1747
  agent: { type: "string" },
@@ -1738,12 +1754,12 @@ const LEARNING_COST = closed({
1738
1754
  digest: { type: "string", description: "The version of it its newest run served first ran: the first 16 hex characters of its workflow.json's sha256. A new version starts its count from zero." },
1739
1755
  state: { enum: ["serving", "needs_revision"], description: `\`serving\`: it runs first on every run it fits. \`needs_revision\`: over its newest ${COST_WINDOW} priced runs served at this version, its mean all-in cost (\`served\`) is at or over the agent's cost by hand (\`by_hand\`), so it no longer runs first: the agent takes each run it would have served, and the stop asks for no new version. A new version (a new digest) runs first again.` },
1740
1756
  served: COST_MEAN(`The mean all-in cost (\`total_usd\`: the run's own cost, the workflow's nodes and, after a handback, the agent's work, with every learning round booked for it) of its newest ${COST_WINDOW} runs served first at this version whose all-in cost is known (a window, never how many runs it served: \`runs\` stops at ${COST_WINDOW}); null when none is.`),
1741
- by_hand: COST_MEAN("The agent's cost by hand: the mean all-in cost (`total_usd`) of its runs on the `agent` path whose all-in cost is known or, with none, of its runs before the workflow first ran; null when there are none: the workflow then keeps serving."),
1742
- unknown_cost_runs: { ...COUNT, description: "How many runs `served` and `by_hand` would have read have no known all-in cost: left out of their means, never read as 0." },
1757
+ by_hand: COST_MEAN(`The agent's cost by hand, as the money rule reads it at a run's launch: the mean of the job's own cost (\`cost_usd\`, learning left out) of its runs on the \`agent\` path (a run that does not learn among them) in a window, the agent's newest ${PAST_RUNS} runs on no named disk since its learning's reset, whose cost is known exactly; null when there are none: the workflow then keeps serving. The window, never every run: \`summary.before\` reads every run before the takeover, so the two differ.`),
1758
+ unknown_cost_runs: { ...COUNT, description: "How many runs `served` would have read have no known all-in cost, and `by_hand` no exact own cost: left out of their means, never read as 0." },
1743
1759
  }), description: "Each learned workflow that has run first on one of these runs, at its newest version, and where it stands against the money rule: it runs first while its cost a run stays under the agent's by hand. It does not catch a workflow that answers wrong with confidence." },
1744
1760
  summary: closed({
1745
1761
  takeover: { oneOf: [closed({ n: { type: "integer", minimum: 1 }, run_id: { type: "string" } }), { type: "null" }], description: "The first run a learned workflow served (`path` `workflow` or `handed_back`), numbered as `runs` number it. Null before one." },
1746
- before: COST_MEAN("The mean of the job's own cost (`cost_usd`, learning left out) over the `agent` runs before the takeover (all of them when there is none yet) whose cost is known exactly (never `cost_upper_bound`); null when there is none."),
1762
+ before: COST_MEAN("The mean of the job's own cost (`cost_usd`, learning left out) over the `agent` runs before the takeover (all of them when there is none yet) whose cost is known exactly (never `cost_upper_bound`); null when there is none. Over every run the series counts (`total_runs`), on any disk: the money rule's by-hand side (`workflows[].by_hand`) reads a window of them instead, so the two differ."),
1747
1763
  after: COST_MEAN("The mean all-in cost (`total_usd`, learning included) of the runs a learned workflow served from the takeover on (`path` `workflow` or `handed_back`; never a `replay`, which checks a revision and serves no one, nor an `agent` run) whose total is known exactly (never `cost_upper_bound`); null when there is none, and `after_state` says why."),
1748
1764
  after_state: { enum: [...AFTER_STATES], description: "Why `after` is what it is: `priced`, it is the mean of the served runs whose cost is known; `no_served_runs`, no learned workflow has taken over yet (replays are not served runs), so there is no after side; `cost_unknown`, runs were served but no served run's all-in cost is known exactly. A reader says these in words, never as a figure." },
1749
1765
  times_cheaper: { type: ["number", "null"], minimum: 0, description: `\`before\` over \`after\`, to a tenth, once \`after\` counts ${CHEAPER_AFTER_RUNS} runs or more and \`withheld\` is null; else null. Learning is left out of the before side and kept in the after side, so it never flatters learning.` },
@@ -2243,6 +2259,7 @@ const EXTENSIONS = {
2243
2259
  { name: "status", in: "query", required: false, description: "Only runs with this status.", schema: ref("schemas/RunStatus") },
2244
2260
  { name: "archived", in: "query", required: false, description: "true lists only archived runs; false, the default, the others.", schema: { type: "boolean" } },
2245
2261
  LABEL_PARAMETER,
2262
+ SOURCE_PARAMETER,
2246
2263
  ],
2247
2264
  responses: { "200": json(ref("schemas/RunList"), "One page of runs, newest first."), ...errors(400, 401, 429, 500) },
2248
2265
  },
@@ -2337,7 +2354,7 @@ const EXTENSIONS = {
2337
2354
  "/wrapped": {
2338
2355
  get: {
2339
2356
  operationId: "getWrapped", tags: ["runs"], summary: "A year of the work under this machine's session files",
2340
- description: "Reads the Claude Code, Codex, pi and other session files under the home of the machine this server runs on, and answers numbers and names only (no prompt, title, path or project). Everything is bucketed by each request's time in the server's local zone, so a session that spans New Year splits; a session counts for the year of its first request. Answered only by one owner's server on their own machine, reached at a loopback name: one bound past loopback, with a public URL, the API-only profile, more than one API token or a Postgres store is 403. The home is read on a worker thread; a read not done within 15 seconds is 503 `unavailable` with `retry_after_ms` while it goes on. The current year's answer is kept for a minute, an earlier year's until the server stops. A year after the current one is 400.",
2357
+ description: "Reads the Claude Code, Codex, pi and other session files under the home of the machine this server runs on, and answers numbers and names only (no prompt, title, path or project). Everything is bucketed by each request's time in the server's local zone, so a session that spans New Year splits; a session counts for the year of its first request. Answered only by one owner's server on their own machine, reached at a loopback name: one bound past loopback, with a public URL, the API-only profile, more than one API token, an API key made in the console for an app, or a Postgres store is 403. The home is read on a worker thread; a read not done within 15 seconds is 503 `unavailable` with `retry_after_ms` while it goes on. The current year's answer is kept for a minute, an earlier year's until the server stops. A read that fails is kept for a minute too: each ask in it is 500 `internal`, the reason in the server's log, and the next ask after it reads again. A year after the current one is 400.",
2341
2358
  parameters: [
2342
2359
  { name: "year", in: "query", required: false, description: "A four-digit year, in the server's local zone. Default the current year.", schema: { type: "integer", minimum: 1000, maximum: 9999 } },
2343
2360
  ],
@@ -2988,7 +3005,7 @@ const EXTENSIONS = {
2988
3005
  },
2989
3006
  put: {
2990
3007
  operationId: "saveMcpServer", tags: ["local"], summary: "Preview a remote MCP server, then save it with the tools listed and its credential sealed",
2991
- description: `The credential is sealed under the server's seal key, bound to the server's name and its URL's origin, and kept in the data directory as ciphertext alone. On an API-only server (AGENTRUN_API_ONLY=1) it is 404 not_found unless its operator names MCP origins (AGENTRUN_API_ONLY_MCP_ORIGINS): then the token saves a per_run server (auth.type per_run, no credential kept) at one of those origins alone, under a name no Composio server has, and any other body is 404, before anything is sent to the address. 403 forbidden to the API token for a save that sends a credential's value, or over a saved server the token did not save or that holds a credential (one the owner saved stays the owner's, sealing a credential or not: its address, its credential and what the Composio preset made for it): the owner's signed-in session alone, and the refusal's \`details.console_url\` opens the console's form for it filled with the rest (no credential). 412 precondition_failed when a save that sends a new credential, or none, finds the server's credential changed while it listed its tools (another save, a sign-in or a removal landed), or the token's save finds the owner saved over its server meanwhile, or a save that keeps it finds the server at another address or holding another kind of credential by then (a Composio save over it moved it): nothing is written over it. A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. A body with no \`prices\` keeps the saved ones for the tools still listed at the same URL, so a save from any client never leaves a paid tool unmetered; \`prices: {}\` clears them. 422 too for a bad name, URL or auth, or a price that is not a finite number 0 or more or names a tool the server does not list. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds. A save that moves a server the Composio preset made to another address makes it another service's server, and removes in the owner's Composio account what the preset made for it, as its delete does (the MCP server, then the connected account its connect link started and the auth config it made, unless another saved server uses them), with the key it was saved with, and answers \`composio\` saying so; 409 composio_in_use, naming them in \`details.triggers\`, while Composio triggers use it: delete them first. A save of a server the preset made lists its tools at once, then writes and cleans up one at a time with the preset's saves and the MCP servers' deletes, in its Composio project's turn.`,
3008
+ description: `The credential is sealed under the server's seal key, bound to the server's name and its URL's origin, and kept in the data directory as ciphertext alone. On an API-only server (AGENTRUN_API_ONLY=1) the token saves only a per_run server at an origin AGENTRUN_API_ONLY_MCP_ORIGINS lists, and any other body is 404 not_found (the serve README's API-only section). 403 forbidden to the API token for a save that sends a credential's value, or over a saved server the token did not save or that holds a credential (one the owner saved stays the owner's, sealing a credential or not: its address, its credential and what the Composio preset made for it): the owner's signed-in session alone, and the refusal's \`details.console_url\` opens the console's form for it filled with the rest (no credential). 412 precondition_failed when a save that sends a new credential, or none, finds the server's credential changed while it listed its tools (another save, a sign-in or a removal landed), or the token's save finds the owner saved over its server meanwhile, or a save that keeps it finds the server at another address or holding another kind of credential by then (a Composio save over it moved it): nothing is written over it. A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. A body with no \`prices\` keeps the saved ones for the tools still listed at the same URL, so a save from any client never leaves a paid tool unmetered; \`prices: {}\` clears them. 422 too for a bad name, URL or auth, or a price that is not a finite number 0 or more or names a tool the server does not list. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds. A save that moves a server the Composio preset made to another address makes it another service's server, and removes in the owner's Composio account what the preset made for it, as its delete does (the MCP server, then the connected account its connect link started and the auth config it made, unless another saved server uses them), with the key it was saved with, and answers \`composio\` saying so; 409 composio_in_use, naming them in \`details.triggers\`, while Composio triggers use it: delete them first. A save of a server the preset made lists its tools at once, then writes and cleans up one at a time with the preset's saves and the MCP servers' deletes, in its Composio project's turn.`,
2992
3009
  parameters: [MCP_NAME],
2993
3010
  requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["url"], properties: { url: MCP_URL, auth: MCP_AUTH, prices: MCP_PRICES, ...MCP_TOOLKIT_BODY } } } } },
2994
3011
  responses: { "200": json({ ...MCP_SERVER_VIEW, properties: { ...MCP_SERVER_VIEW.properties, composio: closed({ removed: { type: "boolean", description: "Nothing the save was to remove at Composio is left there." }, note: { type: "string", description: "What it removed at Composio, what it kept and why, and what is left, with the dashboard's address to remove that by hand." } }, "Present when the save moved a server the Composio preset made off Composio: what became of what the preset made there.") } }, "The server, as saved."), ...errors(400, 401, 403, 404, 409, 412, 415, 422, 429, 500), ...MCP_FAILED },
@@ -3852,6 +3869,10 @@ const FIELD_EXTENSIONS = {
3852
3869
  learning_usd: { type: ["number", "null"], minimum: 0, description: "On the run read (GET /v2/runs/{run_id}) alone, where `usd` is the run's own spend, the job's: what learning spent for it, on the agent's own model route. Its audit shadow's cost (the agent on its input with learning off) and its share of its workflow revision's learning spend: the compile turn that drafted that revision and its check's replay runs, spread over the first `compile_after` runs the revision serves (GET /agents/{agent_id}/learning/cost `bill.revisions`). A compile turn is never in the `usd` or `learning_usd` of the run whose session asked it: it is its revision's (a recompile's, its recompiled revision's), or, when it kept no draft (every draft failed its checks, or the cap stopped it), on no run (`bill.unattributed_usd`). 0 for a replay or shadow run, whose spend is on the runs it serves. As booked (float noise rounded off at 1e-12, as `usd` is); null while the run or its shadow is at work, or a part is unknown: never $0 for unknown.", "x-agentrun-serve": "allin/1" },
3853
3870
  tools_usd: { type: ["number", "null"], minimum: 0, description: "On the run read (GET /v2/runs/{run_id}) alone: the part of `usd` that went to the run's paid tool calls (a monid endpoint's charge, an MCP tool's saved price, Parallel's behind `web_search` and `web_fetch`, the browser's session time, and a workflow decision Parallel answered on its own API on this server's PARALLEL_API_KEY, at Parallel's list price), as the run's ledger booked them, joined and rounded as `usd` is, so `usd` less this is its model requests and its other decisions (Jev's, an OpenRouter model's, Parallel's model reached through OpenRouter). Inside `usd`, never added to it. A paid call in the run's end-of-run turn is learning's, in `learning_usd` and never here. 0 when the run made no paid call. An MCP tool with no price is in neither (`not_metered` on its trace span). Null while a paid call's charge is unknown (one charged an unknown amount, cut, or still running), or counted at its hold; while the run is at work (until it ended, stopped or failed); for a run a follow-up opened again (a round past its first), whose job is what it had cost when its first round answered; and for an imported, native or SDK run, whose `usd` is its import's or its harness's own figure and whose tool calls the server never books: never $0 for unknown.", "x-agentrun-serve": "toolsusd/2" },
3854
3871
  all_in_usd: { type: ["number", "null"], minimum: 0, description: "On the run read alone: `usd` and `learning_usd` together, what the run cost its owner all in. 0 for a replay or shadow run. Over every run of an agent, these and the cost route's `bill.unattributed_usd` add up to its `bill.booked_usd`. Null when either is, or `usd` is only a bound (`upper_bound`).", "x-agentrun-serve": "allin/1" },
3872
+ compile_usd: { type: ["number", "null"], minimum: 0, description: "On the run read alone: the compile turns the run's own session asked, as booked. Never in its `usd` or `learning_usd`: each is its revision's (its share is in the `learning_usd` of the runs that revision serves, `share_usd`), or no run's when it kept no draft (the cost route's `bill.unattributed_usd`). 0 for a run asked none; null while the run is at work or the turn's cost is unknown. The cost route's `runs[].compile_usd` is the same figure.", "x-agentrun-serve": "ledger/1" },
3873
+ followup_usd: { type: ["number", "null"], minimum: 0, description: "On the run read alone, a part of `learning_usd`: what the run's learning spent after its job answered besides its compile turns (a follow-up round's turns, feedback the run was given). 0 for none; null while the run is at work or unknown.", "x-agentrun-serve": "ledger/1" },
3874
+ shadow_usd: { type: ["number", "null"], minimum: 0, description: "On the run read alone, a part of `learning_usd`: its audit shadow's cost (0 when none ran). Null while the shadow is queued or running, or its cost is unknown: never $0.", "x-agentrun-serve": "ledger/1" },
3875
+ share_usd: { type: ["number", "null"], minimum: 0, description: "On the run read alone, a part of `learning_usd`: its share of the learning spend of the workflow revision that served it (that revision's compile turns and check replays, spread over the first `compile_after` runs it serves, the cost route's `bill.revisions`). 0 for a run no revision served; null while unknown. `followup_usd`, `shadow_usd` and this add up to `learning_usd`.", "x-agentrun-serve": "ledger/1" },
3855
3876
  degraded: { type: "boolean", const: true, description: "On the run read alone, set only when this read could not ask the purge gate (a store read of a purged run's writer failed): `learning_usd` and `all_in_usd` were then counted over the agent's workflow revisions with no purged one left out, so they may count a revision a purged run wrote as the one serving. Figures only: no text is read. Absent on every read that asked the gate.", "x-agentrun-serve": "purge/1" },
3856
3877
  plan: {
3857
3878
  type: "object", additionalProperties: false, required: ["requests", "tokens", "on"],
@@ -4486,6 +4507,7 @@ const BLOCKED_DETAILS = {
4486
4507
  denied: { type: "array", items: { type: "string" }, description: "A workflow revision: the tools its call nodes call that are set to deny here." },
4487
4508
  asks: { type: "array", items: { type: "string" }, description: "A workflow revision: the tools its call nodes call that are set to ask here (a catalog tool's default among them). A call node cannot wait for an approval: set the tool to allow for the agent." },
4488
4509
  box: { enum: [...BOX_IDS], description: "The box of the revision's place, when this server does not have it (capabilities.places.boxes)." },
4510
+ login_on_runner: { type: "boolean", enum: [true], description: "Present (true) when the run is refused for its model while its harness runs on Claude Code's login on this machine, the login runs its model (Anthropic's own, `anthropic/<id>`, or none named), and its place is a box: the login runs agents on the runner only, so moving the agent to the runner (its definition's `computer` set to none) runs it on the login. Absent for any other model (an OpenRouter one, Anthropic's through OpenRouter included): that model needs its provider's key on the runner too." },
4489
4511
  not_grantable: { type: "array", items: { type: "object", additionalProperties: false, required: ["tool", "reason"], properties: { tool: { type: "string" }, reason: { type: "string" } } }, description: "The MCP tools the revision grants that are never granted here (known meta tools, which run other actions by name), each with why. Not in `unbound`: no server setup makes one grantable; remove the grant and use the server's direct tools." },
4490
4512
  adapters: { type: "array", items: { type: "string" }, description: "A workflow revision: the adapters it needs that this server does not bind." },
4491
4513
  code: { type: "boolean", description: "A workflow revision: whether it needs code this server does not run." },
@@ -99,6 +99,10 @@ export type PlaceOffersOptions = {
99
99
  container?: ContainerFacts;
100
100
  /** Under --faux only: Docker answers, whatever AGENTRUN_BOXES lists, and nothing asks it. */
101
101
  fauxDocker?: boolean;
102
+ /** Told the architecture of the Docker daemon the probe found (amd64, arm64), when Docker answers and names it: the
103
+ * server's check that a Docker computer's daemon is built for it (box-paths.ts dockerComputerRefusal) asks Docker
104
+ * nothing more. */
105
+ dockerArch?: (arch: string) => void;
102
106
  };
103
107
  /** Every box, in BOX_IDS order, as this server has it at its start (`env`: its environment, its secrets readable): a box AGENTRUN_BOXES does not list is not enabled; docker by its probe (or `fauxDocker`); daytona
104
108
  * and modal by their keys. Rejects only for a name in AGENTRUN_BOXES that is no box. No reason holds a key or an answer's body. */