@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.47

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 (247) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/NOTICE +4 -0
  3. package/README.md +267 -40
  4. package/dist/acp-package.d.ts +35 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +5 -2
  7. package/dist/adapter-facts.js +6 -3
  8. package/dist/adapters.d.ts +7 -0
  9. package/dist/adapters.js +39 -0
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/api-only.d.ts +7 -10
  13. package/dist/api-only.js +7 -10
  14. package/dist/archil-routes.js +2 -1
  15. package/dist/cap.js +12 -2
  16. package/dist/chatgpt-plan.js +2 -1
  17. package/dist/cli.js +109 -41
  18. package/dist/composio-made.d.ts +19 -2
  19. package/dist/composio-made.js +17 -5
  20. package/dist/composio-preset.d.ts +42 -7
  21. package/dist/composio-preset.js +106 -70
  22. package/dist/composio-triggers.d.ts +9 -4
  23. package/dist/composio-triggers.js +20 -13
  24. package/dist/computer-attach.d.ts +11 -10
  25. package/dist/computer-attach.js +13 -14
  26. package/dist/computer-commands.d.ts +3 -0
  27. package/dist/computer-commands.js +3 -2
  28. package/dist/computer-lost.d.ts +4 -0
  29. package/dist/computer-lost.js +8 -3
  30. package/dist/computer-setting.d.ts +2 -0
  31. package/dist/computer-setting.js +2 -0
  32. package/dist/computers.d.ts +9 -75
  33. package/dist/computers.js +20 -66
  34. package/dist/console/assets/index-BBFzAxLB.js +715 -0
  35. package/dist/console/assets/index-BRi-Rgq6.css +1 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/cost-heal.d.ts +13 -0
  38. package/dist/cost-heal.js +27 -0
  39. package/dist/dial-relay.d.ts +6 -2
  40. package/dist/dial-relay.js +9 -12
  41. package/dist/email/routes.js +2 -1
  42. package/dist/errors.d.ts +2 -0
  43. package/dist/errors.js +5 -0
  44. package/dist/exa-keyless.d.ts +1 -1
  45. package/dist/exa-keyless.js +1 -1
  46. package/dist/faux-computers.d.ts +2 -3
  47. package/dist/faux-computers.js +9 -31
  48. package/dist/github-connection.js +2 -1
  49. package/dist/harness-archive.d.ts +19 -2
  50. package/dist/harness-archive.js +49 -15
  51. package/dist/harness-check.d.ts +73 -0
  52. package/dist/harness-check.js +489 -0
  53. package/dist/harness-cursor.d.ts +45 -0
  54. package/dist/harness-cursor.js +121 -0
  55. package/dist/harness-recipe.d.ts +127 -0
  56. package/dist/harness-recipe.js +357 -0
  57. package/dist/harness-table.d.ts +12 -0
  58. package/dist/harness-table.js +62 -2
  59. package/dist/harness.d.ts +2 -0
  60. package/dist/harness.js +3 -2
  61. package/dist/host-check.d.ts +6 -0
  62. package/dist/host-check.js +14 -0
  63. package/dist/host.d.ts +10 -3
  64. package/dist/host.js +17 -3
  65. package/dist/import-sources.d.ts +2 -0
  66. package/dist/import-sources.js +2 -0
  67. package/dist/import-summary.d.ts +15 -5
  68. package/dist/import-summary.js +24 -8
  69. package/dist/import.d.ts +24 -4
  70. package/dist/import.js +108 -26
  71. package/dist/key-refusal.d.ts +1 -0
  72. package/dist/key-refusal.js +8 -3
  73. package/dist/key-words.d.ts +1 -1
  74. package/dist/key-words.js +4 -4
  75. package/dist/learn/check.d.ts +3 -0
  76. package/dist/learn/check.js +31 -20
  77. package/dist/learn/compile.js +12 -5
  78. package/dist/learn/promote.d.ts +69 -2
  79. package/dist/learn/promote.js +95 -3
  80. package/dist/learned-nodes.d.ts +4 -3
  81. package/dist/learned-workflow.js +4 -1
  82. package/dist/learning-cost.d.ts +6 -16
  83. package/dist/learning-cost.js +6 -12
  84. package/dist/learning-words.d.ts +2 -0
  85. package/dist/learning-words.js +1 -1
  86. package/dist/listen-first.d.ts +10 -0
  87. package/dist/listen-first.js +25 -1
  88. package/dist/llms.txt +1 -1
  89. package/dist/mcp-gateway.d.ts +2 -1
  90. package/dist/mcp-gateway.js +31 -15
  91. package/dist/mcp-probe.d.ts +18 -6
  92. package/dist/mcp-probe.js +41 -8
  93. package/dist/mcp-secret-writes.d.ts +8 -0
  94. package/dist/mcp-secret-writes.js +104 -4
  95. package/dist/mcp-servers-store.d.ts +11 -5
  96. package/dist/mcp-servers-store.js +46 -20
  97. package/dist/model-form.d.ts +2 -1
  98. package/dist/model-form.js +22 -8
  99. package/dist/model-gateway.d.ts +113 -0
  100. package/dist/model-gateway.js +433 -0
  101. package/dist/model.d.ts +2 -1
  102. package/dist/model.js +9 -7
  103. package/dist/monid.js +1 -1
  104. package/dist/native/binding.d.ts +4 -0
  105. package/dist/native/binding.js +9 -0
  106. package/dist/native/cli.d.ts +3 -2
  107. package/dist/native/cli.js +6 -5
  108. package/dist/openapi.d.ts +2 -0
  109. package/dist/openapi.js +322 -39
  110. package/dist/owner.d.ts +4 -2
  111. package/dist/owner.js +10 -4
  112. package/dist/page.d.ts +8 -0
  113. package/dist/page.js +9 -1
  114. package/dist/port-models.js +17 -10
  115. package/dist/provider.d.ts +3 -3
  116. package/dist/provider.js +12 -3
  117. package/dist/public-address.d.ts +28 -0
  118. package/dist/public-address.js +62 -0
  119. package/dist/run-launch.d.ts +1 -1
  120. package/dist/run-launch.js +1 -1
  121. package/dist/run-secrets.d.ts +3 -2
  122. package/dist/run-secrets.js +6 -4
  123. package/dist/runner/adapter-loop.d.ts +10 -7
  124. package/dist/runner/adapter-loop.js +57 -22
  125. package/dist/runner/adapter-run-spec.d.ts +12 -0
  126. package/dist/runner/adapter-run-spec.js +40 -6
  127. package/dist/runner/adapters/index.js +16 -0
  128. package/dist/runner/adapters/pi.d.ts +5 -2
  129. package/dist/runner/adapters/pi.js +7 -4
  130. package/dist/runner/audit.d.ts +7 -0
  131. package/dist/runner/audit.js +15 -6
  132. package/dist/runner/claim-secrets.js +5 -1
  133. package/dist/runner/cli-run-spec.js +15 -7
  134. package/dist/runner/compare-end.d.ts +43 -0
  135. package/dist/runner/compare-end.js +95 -0
  136. package/dist/runner/computer-journal.d.ts +3 -0
  137. package/dist/runner/computer-journal.js +22 -2
  138. package/dist/runner/harness-loops.d.ts +6 -1
  139. package/dist/runner/harness-loops.js +94 -54
  140. package/dist/runner/held.d.ts +5 -4
  141. package/dist/runner/journal-kinds.d.ts +4 -1
  142. package/dist/runner/journal-kinds.js +3 -0
  143. package/dist/runner/loop-contract.d.ts +10 -0
  144. package/dist/runner/main.d.ts +5 -5
  145. package/dist/runner/main.js +62 -11
  146. package/dist/runner/mcp-claim.js +40 -12
  147. package/dist/runner/metrics.d.ts +26 -0
  148. package/dist/runner/metrics.js +44 -1
  149. package/dist/runner/presence.d.ts +41 -0
  150. package/dist/runner/presence.js +89 -0
  151. package/dist/runner/promotion.d.ts +9 -4
  152. package/dist/runner/promotion.js +33 -14
  153. package/dist/runner/run-child-host.js +40 -10
  154. package/dist/runner/runner.d.ts +5 -0
  155. package/dist/runner/runner.js +8 -0
  156. package/dist/runner/store-port.d.ts +3 -0
  157. package/dist/runner/store-secrets.js +19 -7
  158. package/dist/runner/workflow-first.d.ts +5 -2
  159. package/dist/runner/workflow-first.js +6 -3
  160. package/dist/runs-over-store.d.ts +6 -2
  161. package/dist/runs-over-store.js +14 -4
  162. package/dist/sdk/runs.d.ts +1 -1
  163. package/dist/sdk/runs.js +6 -1
  164. package/dist/sdk/schema.js +1 -1
  165. package/dist/secret-writes.d.ts +16 -3
  166. package/dist/secret-writes.js +28 -3
  167. package/dist/server-secrets-store.js +5 -0
  168. package/dist/server.d.ts +31 -2
  169. package/dist/server.js +322 -51
  170. package/dist/sign-ins-secrets.js +4 -1
  171. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  172. package/dist/slack-url.d.ts +5 -0
  173. package/dist/slack-url.js +11 -0
  174. package/dist/slack.d.ts +107 -0
  175. package/dist/slack.js +292 -0
  176. package/dist/start-switches.d.ts +28 -0
  177. package/dist/start-switches.js +37 -0
  178. package/dist/stats.d.ts +1 -1
  179. package/dist/stats.js +2 -1
  180. package/dist/stop-signals.d.ts +11 -0
  181. package/dist/stop-signals.js +22 -0
  182. package/dist/store/agent-body.d.ts +1 -1
  183. package/dist/store/agent-body.js +2 -2
  184. package/dist/store/index.d.ts +3 -3
  185. package/dist/store/index.js +1 -1
  186. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  187. package/dist/store/postgres/store.d.ts +1 -1
  188. package/dist/store/postgres/store.js +4 -2
  189. package/dist/store/schema.d.ts +13 -5
  190. package/dist/store/schema.js +20 -11
  191. package/dist/store/seal.d.ts +16 -4
  192. package/dist/store/sqlite/store.d.ts +1 -1
  193. package/dist/store/sqlite/store.js +106 -27
  194. package/dist/store/store.d.ts +75 -23
  195. package/dist/store/store.js +11 -0
  196. package/dist/store-reads/analytics.js +3 -2
  197. package/dist/store-reads/cap.d.ts +7 -0
  198. package/dist/store-reads/cap.js +11 -1
  199. package/dist/store-reads/journal.js +27 -1
  200. package/dist/store-reads/learning.d.ts +23 -2
  201. package/dist/store-reads/learning.js +29 -8
  202. package/dist/store-reads/runs.d.ts +9 -0
  203. package/dist/store-reads/runs.js +19 -6
  204. package/dist/store-reads/stats.d.ts +4 -1
  205. package/dist/store-reads/stats.js +15 -6
  206. package/dist/store-view.d.ts +123 -14
  207. package/dist/store-view.js +154 -21
  208. package/dist/telemetry.d.ts +7 -7
  209. package/dist/telemetry.js +38 -15
  210. package/dist/timeline/timeline.js +18 -0
  211. package/dist/tool-keys-store.js +2 -2
  212. package/dist/tool-keys.js +2 -1
  213. package/dist/tool-plane.js +2 -2
  214. package/dist/trigger-adapter.d.ts +3 -4
  215. package/dist/trigger-adapter.js +2 -2
  216. package/dist/trigger-composio.js +3 -3
  217. package/dist/trigger-email.js +0 -2
  218. package/dist/trigger-feed.js +0 -2
  219. package/dist/trigger-schedule.js +3 -0
  220. package/dist/trigger-secrets-shown.d.ts +6 -3
  221. package/dist/trigger-secrets-shown.js +22 -13
  222. package/dist/trigger-targets.d.ts +1 -1
  223. package/dist/trigger-targets.js +19 -8
  224. package/dist/triggers.d.ts +2 -2
  225. package/dist/webhooks.d.ts +82 -8
  226. package/dist/webhooks.js +128 -45
  227. package/dist/wires.d.ts +6 -1
  228. package/dist/wires.js +5 -0
  229. package/dist/workspace/attach.d.ts +3 -2
  230. package/dist/workspace/attach.js +2 -1
  231. package/dist/workspace/attached-computers.d.ts +6 -8
  232. package/dist/workspace/attached-computers.js +27 -24
  233. package/dist/workspace/computer-deps.d.ts +2 -3
  234. package/dist/workspace/computer-deps.js +3 -6
  235. package/dist/workspace/computer-for-claim.js +72 -96
  236. package/dist/workspace/computer-kept.d.ts +0 -7
  237. package/dist/workspace/computer-kept.js +0 -17
  238. package/dist/workspace/resolve-computer.d.ts +18 -14
  239. package/dist/workspace/resolve-computer.js +47 -60
  240. package/dist/workspace/synced-folder.d.ts +20 -15
  241. package/dist/workspace/synced-folder.js +33 -43
  242. package/launcher/agentrun-serve +4 -1
  243. package/package.json +10 -10
  244. package/skills/agentrun-serve/SKILL.md +11 -0
  245. package/templates/README.md +1 -1
  246. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  247. package/dist/console/assets/index-CZZeCReB.js +0 -701
package/dist/owner.d.ts CHANGED
@@ -48,14 +48,16 @@ export declare class Owner {
48
48
  readonly signIns: SignInLimit;
49
49
  private setupCode;
50
50
  private base;
51
+ private elsewhere;
51
52
  /** Taken while a first password is being set, so a second at the same moment is refused. */
52
53
  private settingUp;
53
54
  /** `openSetup`: no setup code; the first visit sets the password (no public address). `say` prints a setup code. */
54
55
  constructor(dir: string, openSetup: boolean, say?: (line: string) => void, addresses?: number);
55
56
  private read;
56
57
  hasPassword(): boolean;
57
- /** The address the setup link is printed with, fixed once the server listens. */
58
- attach(baseUrl: string): void;
58
+ /** The address the setup link is printed with, fixed once the server listens; `elsewhere`, the addresses another
59
+ * machine reaches it at (a server listening on every address with no public one), each printed with the code too. */
60
+ attach(baseUrl: string, elsewhere?: readonly string[]): void;
59
61
  /** The setup page's link: with its code when setup needs one, a new code printed (never answered) when none is good. */
60
62
  setupLink(): string;
61
63
  /** A setup code to use, for whoever asks with no credential: the one that stands is kept (never voided here), and a
package/dist/owner.js CHANGED
@@ -122,6 +122,7 @@ export class Owner {
122
122
  signIns;
123
123
  setupCode = null;
124
124
  base = "";
125
+ elsewhere = [];
125
126
  /** Taken while a first password is being set, so a second at the same moment is refused. */
126
127
  settingUp = false;
127
128
  /** `openSetup`: no setup code; the first visit sets the password (no public address). `say` prints a setup code. */
@@ -159,19 +160,24 @@ export class Owner {
159
160
  hasPassword() {
160
161
  return this.read().password !== undefined;
161
162
  }
162
- /** The address the setup link is printed with, fixed once the server listens. */
163
- attach(baseUrl) {
163
+ /** The address the setup link is printed with, fixed once the server listens; `elsewhere`, the addresses another
164
+ * machine reaches it at (a server listening on every address with no public one), each printed with the code too. */
165
+ attach(baseUrl, elsewhere = []) {
164
166
  this.base = baseUrl;
167
+ this.elsewhere = elsewhere;
165
168
  }
166
169
  /** The setup page's link: with its code when setup needs one, a new code printed (never answered) when none is good. */
167
170
  setupLink() {
168
171
  if (this.openSetup)
169
172
  return `${this.base}/setup`;
173
+ const linkAt = (base) => `${base}/setup#code=${this.setupCode.code}`;
170
174
  if (!this.setupCode || Date.now() > this.setupCode.until) {
171
175
  this.setupCode = { code: randomBytes(16).toString("base64url"), until: Date.now() + SETUP_TTL_MS, tries: 0 };
172
- this.say(`Set up this server: ${this.base}/setup#code=${this.setupCode.code} (or paste AGENTRUN_TOKEN)`);
176
+ this.say(`Set up this server: ${linkAt(this.base)} (or paste AGENTRUN_TOKEN)`);
177
+ for (const base of this.elsewhere)
178
+ this.say(`From another machine: ${linkAt(base)}`);
173
179
  }
174
- return `${this.base}/setup#code=${this.setupCode.code}`;
180
+ return linkAt(this.base);
175
181
  }
176
182
  /** A setup code to use, for whoever asks with no credential: the one that stands is kept (never voided here), and a
177
183
  * new one is printed only when none is good (expired, or spent). Answers which, and when the code now good runs
package/dist/page.d.ts CHANGED
@@ -33,6 +33,14 @@ export declare const heldSessions: (req: IncomingMessage) => string[];
33
33
  export declare const signedIn: (req: IncomingMessage, owner: Owner) => boolean;
34
34
  /** A browser's answer for a Host the server refuses (host-check.ts): 403, a fixed page under the console's CSP. */
35
35
  export declare const sendHostRefused: (req: IncomingMessage, res: ServerResponse) => void;
36
+ /** Whether `raw` is the console's own page, or one of the addresses that send a browser to it (MOVED). */
37
+ export declare const consoleEntry: (raw: string) => boolean;
38
+ /** A browser's answer for the console under the server's earlier public address (public-address.ts): 308 to the new one,
39
+ * `to`, whose console takes the link's #fragment along (a browser keeps it across a redirect). no-store, so no browser
40
+ * keeps the redirect: the address may change back. */
41
+ export declare const sendMoved: (res: ServerResponse, to: string) => undefined;
42
+ /** A browser's answer for any other page under the earlier public address: 403, a fixed page that links to `to`. */
43
+ export declare const sendMovedPage: (req: IncomingMessage, res: ServerResponse, to: string) => void;
36
44
  /** `takesBytes`: whether a request of `method` to `path` (under /v2) goes to a route whose body is bytes (server.ts). */
37
45
  /** `publicUrl`: the address people open (AGENTRUN_PUBLIC_URL); an https one adds HSTS to every page answer (hstsHeaders). */
38
46
  /** `sessions`: the console's sessions on a server with no accounts (ConsoleSessions); with `owner`, none. */
package/dist/page.js CHANGED
@@ -9,7 +9,7 @@ import { readFile, realpath, stat } from "node:fs/promises";
9
9
  import { extname, join, sep } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { ApiError } from "./errors.js";
12
- import { hostRefusedPage } from "./host-check.js";
12
+ import { hostRefusedPage, movedPage } from "./host-check.js";
13
13
  // img-src names Google's favicon service and the four hosts it redirects to: the console's Keys page shows a provider's
14
14
  // icon from it (apps/console/src/components/ProviderIcon.tsx), sent with no referrer. Everything else is this origin's.
15
15
  const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https://www.google.com https://t0.gstatic.com https://t1.gstatic.com https://t2.gstatic.com https://t3.gstatic.com; base-uri 'none'; form-action https://github.com; frame-ancestors 'none'";
@@ -86,6 +86,14 @@ function send(req, res, status, type, body, headers = {}) {
86
86
  }
87
87
  /** A browser's answer for a Host the server refuses (host-check.ts): 403, a fixed page under the console's CSP. */
88
88
  export const sendHostRefused = (req, res) => send(req, res, 403, HTML, hostRefusedPage(req.socket.localPort ?? 0));
89
+ /** Whether `raw` is the console's own page, or one of the addresses that send a browser to it (MOVED). */
90
+ export const consoleEntry = (raw) => raw === "/" || MOVED.has(raw);
91
+ /** A browser's answer for the console under the server's earlier public address (public-address.ts): 308 to the new one,
92
+ * `to`, whose console takes the link's #fragment along (a browser keeps it across a redirect). no-store, so no browser
93
+ * keeps the redirect: the address may change back. */
94
+ export const sendMoved = (res, to) => (res.writeHead(308, { ...SECURITY, location: `${to}/`, "content-length": 0 }), void res.end());
95
+ /** A browser's answer for any other page under the earlier public address: 403, a fixed page that links to `to`. */
96
+ export const sendMovedPage = (req, res, to) => send(req, res, 403, HTML, movedPage(to));
89
97
  const refuse = (req, res, error) => send(req, res, error.status, "application/json", JSON.stringify(error.body(String(res.getHeader("x-request-id") ?? ""))), error.headers);
90
98
  const redirect = (res, location, headers = {}) => (res.writeHead(303, { ...SECURITY, location, "content-length": 0, ...headers }), void res.end());
91
99
  /** A file of the console: a known type inside `dir`, read through no link that leaves it. Vite's hashed assets are cached
@@ -1,6 +1,7 @@
1
1
  import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
2
2
  import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
3
3
  import { createProvider } from "@earendil-works/pi-ai/models";
4
+ import { CONVERSATION_HEADER, conversationLabel } from "@parcha/agentrun-kernel/host";
4
5
  import { attachingImages } from "./attach-images.js";
5
6
  /** The provider id the port's one model is listed under. */
6
7
  export const PORT_PROVIDER = "agentrun-session";
@@ -51,18 +52,24 @@ export function sessionProvider(api, proxy, model, options) {
51
52
  api: sessionApi(api, options.like),
52
53
  });
53
54
  }
54
- /** A translated Chat Completions session carries its cache identity in Messages' existing metadata field: the proxy
55
- * preserves it without forwarding extra headers. The translation uses it only for provider cache affinity. */
55
+ /** The session's client of `api`. Each request names its conversation to the proxy (CONVERSATION_HEADER: pi's own id for
56
+ * it, the request's `sessionId`, one per conversation), so the host knows which of several conversations asking at once
57
+ * a booking is; the proxy sends that header no further. A translated Chat Completions session also carries its cache
58
+ * identity in Messages' existing metadata field: the proxy preserves it without forwarding extra headers. The
59
+ * translation uses it only for provider cache affinity. */
56
60
  function sessionApi(api, like) {
57
61
  const own = attachingImages(api === "anthropic-messages" ? anthropicMessagesApi() : openAIResponsesApi());
58
- if (api !== "anthropic-messages" || !like?.translatedChatCompletions)
59
- return own;
60
- const withSession = (options) => ({
61
- ...options,
62
- // The upstream can have accepted a paid request before this hop fails. Never replay it implicitly.
63
- maxRetries: 0,
64
- ...(options?.cacheRetention === "none" ? { metadata: { ...options.metadata, user_id: "" } } : options?.sessionId ? { metadata: { ...options.metadata, user_id: options.sessionId } } : {}),
65
- });
62
+ const translated = api === "anthropic-messages" && like?.translatedChatCompletions === true;
63
+ const withSession = (options) => {
64
+ const conversation = conversationLabel(options?.sessionId);
65
+ return {
66
+ ...options,
67
+ ...(conversation === undefined ? {} : { headers: { ...options?.headers, [CONVERSATION_HEADER]: conversation } }),
68
+ // The upstream can have accepted a paid request before this hop fails. Never replay it implicitly.
69
+ ...(translated ? { maxRetries: 0 } : {}),
70
+ ...(!translated ? {} : options?.cacheRetention === "none" ? { metadata: { ...options.metadata, user_id: "" } } : options?.sessionId ? { metadata: { ...options.metadata, user_id: options.sessionId } } : {}),
71
+ };
72
+ };
66
73
  return {
67
74
  ...own,
68
75
  stream: (model, context, options) => own.stream(model, context, withSession(options)),
@@ -1,8 +1,8 @@
1
- import type { Wire } from "@parcha/agentrun-kernel";
1
+ import type { HarnessWire as Wire } from "@parcha/agentrun-kernel";
2
2
  import type { ClaudeAgentLogin } from "@parcha/agentrun-harness-claude";
3
3
  import { type ModelNeeds, type ModelRef } from "./model.js";
4
- import { WIRES } from "./wires.js";
5
- export { WIRES };
4
+ import { modelWire, WIRES, wireOf } from "./wires.js";
5
+ export { modelWire, WIRES, wireOf };
6
6
  /** What fixes a harness that is not on this machine as its adapter needs it: `install`, its package or binary is missing;
7
7
  * `pins`, what is installed is not the pinned build. */
8
8
  export type InstallFix = "install" | "pins";
package/dist/provider.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { CLAUDE_LOGIN_PROVIDER, onClaudeLogin, claudeLoginOf } from "./claude-login.js";
2
2
  import { chooseModel, FAUX_ENV, hostModel, MODEL_PROVIDER } from "./model.js";
3
- import { WIRES } from "./wires.js";
3
+ import { modelWire, WIRES, wireOf } from "./wires.js";
4
4
  import { modelFormWhy } from "./model-form.js";
5
5
  import { EXPIRED, PLAN_ORIGIN, PLAN_PROVIDER, planOf, SIGNED_OUT } from "./chatgpt-plan.js";
6
6
  // Each wire's own settings live in a leaf module (wires.ts), which the harness table reads as it loads.
7
- export { WIRES };
7
+ export { modelWire, WIRES, wireOf };
8
8
  /** Why this server cannot run a harness here, in words a person can act on; `fix`, when installing is the fix; `keys`,
9
9
  * when a model key is all it lacks: the keys, any one of which, set, lets it run (a key row names it: tool-keys.ts). */
10
10
  export class HarnessUnavailable extends Error {
@@ -89,13 +89,16 @@ function onServeGateway(env, base) {
89
89
  * endpoint the host names never gets the OpenRouter key.
90
90
  */
91
91
  export function openRouterOnly(wire, env) {
92
+ // A harness on its own plan (Cursor's) reaches nothing through OpenRouter, nor through any route of ours.
93
+ if (!modelWire(wire))
94
+ return false;
92
95
  return Boolean(env.OPENROUTER_API_KEY) && !env[WIRES[wire].base] && !env[WIRES[wire].key];
93
96
  }
94
97
  /** Whether a run on `wire` of `model` (as named, `provider/model-id`; none, the host's) sends through OpenRouter: a model
95
98
  * named on it (`openrouter/<vendor>/...`), or the wire's vendor reached only through it (openRouterOnly). Serve's gateway
96
99
  * comes first on the wire it serves. */
97
100
  export function viaOpenRouter(wire, env, model) {
98
- if (WIRES[wire].gateway && env.AGENT_MODEL_BASE_URL)
101
+ if (!modelWire(wire) || (WIRES[wire].gateway && env.AGENT_MODEL_BASE_URL))
99
102
  return false;
100
103
  return Boolean(model?.startsWith(`openrouter/${WIRES[wire].vendor}/`)) || openRouterOnly(wire, env);
101
104
  }
@@ -119,6 +122,9 @@ function openRouterKey(env, who, named) {
119
122
  const gatewayProvider = (env, model) => ({ origin: modelGatewayBase(env.AGENT_MODEL_BASE_URL), credential: () => env.AGENT_MODEL_API_KEY || "none", auth: "bearer", modelId: model.modelId, priceModel: model });
120
123
  export function providerFor(wire, env, model, who) {
121
124
  const named = `${model.provider}/${model.modelId}`;
125
+ // A harness on its own plan (Cursor's) calls its vendor itself, on its owner's key: no route of ours is its.
126
+ if (!modelWire(wire))
127
+ throw new HarnessUnavailable(`${who} runs its model on its own plan, never through a model route of AgentRun's; ${named} is not one to proxy.`);
122
128
  if (wire === "anthropic-messages") {
123
129
  // A model of serve's gateway that the gateway takes on Messages (a Claude model, model.ts gatewayWire): the gateway's
124
130
  // own route, as on Responses. No harness of this wire chooses one (claude-agent's model is never the gateway's).
@@ -187,6 +193,9 @@ export function priceModelFor(wire, env, model, who) {
187
193
  * (it prices the run): OpenRouter's key is the one providerFor sends. A save, a run and capabilities all ask this.
188
194
  */
189
195
  export async function modelOn(wire, env, ref, harness) {
196
+ // A harness on its own plan chooses its model itself (its table entry's model): none of the host's is its.
197
+ if (!modelWire(wire))
198
+ return { why: `${harness} runs a model of its own plan, which its own entry chooses.`, host: false };
190
199
  const { vendor, label } = WIRES[wire];
191
200
  const named = ref ?? hostModel(env, "default", harness);
192
201
  if (wire === "openai-responses") {
@@ -0,0 +1,28 @@
1
+ /** The file, in the data folder: `{ "url": <the address, or null for none>, "earlier": <the one before it, or null> }`. */
2
+ export declare const PUBLIC_ADDRESS_FILE = ".public-url";
3
+ /** What a start finds: `changed` when the folder remembered another address (none counts), and `earlier`, the address the
4
+ * server had before its current one, kept across starts until the next change. `keep` remembers the current address; a
5
+ * start calls it only once it serves, so a start that fails leaves the folder's address, and its earlier one, as they were. */
6
+ export type PublicAddress = {
7
+ changed?: {
8
+ from: string | null;
9
+ to: string | null;
10
+ };
11
+ earlier: string | null;
12
+ keep: (warn: (said: string) => void) => void;
13
+ };
14
+ /** Reads the address `data` remembers and compares it with `publicUrl`. A folder that remembers none (a first start, or a
15
+ * file that is not one) has no change to report. `keep` writes it as the folder's other files are written (whole and
16
+ * synced, mode 600), and only when it differs; a write that fails is told to `warn` and stops nothing: the next start
17
+ * compares again. */
18
+ export declare function readPublicAddress(data: string, publicUrl: string | undefined): PublicAddress;
19
+ /** The log line's words for a change. */
20
+ export declare const publicAddressChanged = "the public address (AGENTRUN_PUBLIC_URL) changed: the owner signs in again at the new address, and links in earlier webhook messages point to the old one";
21
+ /** Where a request under the earlier address is sent on to: `from`, the earlier address's name, and `to`, the address
22
+ * people open now (`publicUrl`, parsed, so a name in any script is written as a header carries it, without a trailing
23
+ * slash). Set only when the server has a public address now and the earlier one's name is none it answers to (`served`:
24
+ * its own names, its --allow-host names and the new address's). */
25
+ export declare function movedAddress(earlier: string | null, publicUrl: string | undefined, served: ReadonlySet<string>): {
26
+ from: string;
27
+ to: string;
28
+ } | undefined;
@@ -0,0 +1,62 @@
1
+ // The public address this server last served at (AGENTRUN_PUBLIC_URL), kept in its data folder. A change of it signs the
2
+ // owner out (the session cookie is kept per host) and leaves the links in earlier webhook messages on the old address, so a
3
+ // start that finds it changed says so in its log, and the server sends a browser that still opens the old address on to
4
+ // the new one (server.ts, host-check.ts).
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { hostName } from "./host-check.js";
8
+ import { writeDurableSync } from "./server-fs.js";
9
+ /** The file, in the data folder: `{ "url": <the address, or null for none>, "earlier": <the one before it, or null> }`. */
10
+ export const PUBLIC_ADDRESS_FILE = ".public-url";
11
+ /** An address as the CLI takes it: parsed, without a trailing slash. None, null. */
12
+ const normal = (url) => (url === undefined ? null : URL.canParse(url) ? new URL(url).href.replace(/\/+$/, "") : url);
13
+ const keptOf = (text) => {
14
+ try {
15
+ const kept = JSON.parse(text);
16
+ const field = (value) => (typeof value === "string" ? value : null);
17
+ return kept && typeof kept === "object" && "url" in kept ? { url: field(kept.url), earlier: field(kept.earlier) } : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ };
23
+ /** Reads the address `data` remembers and compares it with `publicUrl`. A folder that remembers none (a first start, or a
24
+ * file that is not one) has no change to report. `keep` writes it as the folder's other files are written (whole and
25
+ * synced, mode 600), and only when it differs; a write that fails is told to `warn` and stops nothing: the next start
26
+ * compares again. */
27
+ export function readPublicAddress(data, publicUrl) {
28
+ const path = join(data, PUBLIC_ADDRESS_FILE);
29
+ const url = normal(publicUrl);
30
+ let text;
31
+ try {
32
+ text = readFileSync(path, "utf8");
33
+ }
34
+ catch { }
35
+ const before = text === undefined ? undefined : keptOf(text);
36
+ const changed = before !== undefined && before.url !== url;
37
+ const now = { url, earlier: changed ? (before.url ?? before.earlier) : (before?.earlier ?? null) };
38
+ const written = JSON.stringify(now);
39
+ const keep = (warn) => {
40
+ if (written === text)
41
+ return;
42
+ try {
43
+ writeDurableSync(path, written);
44
+ }
45
+ catch (error) {
46
+ warn(`the public address could not be remembered in ${PUBLIC_ADDRESS_FILE}: ${error.message}`);
47
+ }
48
+ };
49
+ return { ...(changed ? { changed: { from: before.url, to: url } } : {}), earlier: now.earlier, keep };
50
+ }
51
+ /** The log line's words for a change. */
52
+ export const publicAddressChanged = "the public address (AGENTRUN_PUBLIC_URL) changed: the owner signs in again at the new address, and links in earlier webhook messages point to the old one";
53
+ /** Where a request under the earlier address is sent on to: `from`, the earlier address's name, and `to`, the address
54
+ * people open now (`publicUrl`, parsed, so a name in any script is written as a header carries it, without a trailing
55
+ * slash). Set only when the server has a public address now and the earlier one's name is none it answers to (`served`:
56
+ * its own names, its --allow-host names and the new address's). */
57
+ export function movedAddress(earlier, publicUrl, served) {
58
+ if (earlier === null || publicUrl === undefined || !URL.canParse(earlier) || !URL.canParse(publicUrl))
59
+ return undefined;
60
+ const from = hostName(new URL(earlier).host);
61
+ return from !== undefined && !served.has(from) ? { from, to: normal(publicUrl) } : undefined;
62
+ }
@@ -13,7 +13,7 @@ import type { Place } from "./workspace/place.js";
13
13
  * the old path recomputed; here they are pinned at start, and optional (a built-in run may name none). */
14
14
  export interface RunLaunch {
15
15
  readonly sdk?: {
16
- runtime: "claude-agent-sdk" | "codex-sdk";
16
+ runtime: "claude-agent-sdk" | "codex-sdk" | "eve";
17
17
  instructions: string;
18
18
  model?: string;
19
19
  workflow_tools?: SdkWorkflowTool[];
@@ -104,7 +104,7 @@ export function readLaunchBody(stored) {
104
104
  const archilDisk = readDisk(stored.archil_disk);
105
105
  return {
106
106
  input: stored.input,
107
- ...(isObject(stored.sdk) && (stored.sdk.runtime === "claude-agent-sdk" || stored.sdk.runtime === "codex-sdk") && typeof stored.sdk.instructions === "string" ? { sdk: stored.sdk } : {}),
107
+ ...(isObject(stored.sdk) && (stored.sdk.runtime === "claude-agent-sdk" || stored.sdk.runtime === "codex-sdk" || stored.sdk.runtime === "eve") && typeof stored.sdk.instructions === "string" ? { sdk: stored.sdk } : {}),
108
108
  ...(nativeOf(stored) ? { native: nativeOf(stored) } : {}),
109
109
  title: typeof stored.title === "string" ? stored.title : "",
110
110
  ...(typeof stored.repo === "string" ? { repo: stored.repo } : {}),
@@ -25,8 +25,9 @@ export declare function needsOf(revision: Revision): Promise<RunNeeds>;
25
25
  * `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does not need, from
26
26
  * the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the gateway's (model.ts'
27
27
  * modelKeys: its own model, or the host's of each tier it runs); a run on an adapter's, the one key its wire's route
28
- * sends for the revision's model (adapters.ts' harnessModelKeys). Read at each claim, so a key saved with no restart
29
- * counts at the next. */
28
+ * sends for the revision's model (adapters.ts' harnessModelKeys); and but each harness's own key (HarnessEntry.ownKeys:
29
+ * Cursor's CURSOR_API_KEY) on a run of any other harness. Read at each claim, so a key saved with no restart counts at
30
+ * the next. */
30
31
  export declare function keysFor(needs: RunNeeds, env: NodeJS.ProcessEnv, rows?: readonly KeyRow[]): string[];
31
32
  /** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
32
33
  export declare function secretsFor(revision: Revision, rows?: readonly KeyRow[], env?: NodeJS.ProcessEnv): Promise<string[]>;
@@ -3,7 +3,7 @@ import { COMPUTER_KEY_NAMES } from "./computer-keys.js";
3
3
  import { BOX_KEYS } from "./place-offers.js";
4
4
  import { providersNamed } from "./decisions.js";
5
5
  import { harnessOfBody } from "./harness.js";
6
- import { harnessOf } from "./harness-table.js";
6
+ import { BUILTIN_OWN_KEYS, harnessOf, harnessTable } from "./harness-table.js";
7
7
  import { GATEWAY_KEY_ENV, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, workflowNodes } from "./model.js";
8
8
  import { DECISION_KEYS, SECRET_NAMES } from "./secrets.js";
9
9
  import { TOOL_FIELDS, TOOL_KEYS, unlocksTool } from "./tool-keys.js";
@@ -45,14 +45,16 @@ export async function needsOf(revision) {
45
45
  * `rows` (TOOL_KEYS) that unlocks none of the tools the run binds; and but each model key its model does not need, from
46
46
  * the host's model settings and the keys in `env`: a pi run's, its models' providers' keys or the gateway's (model.ts'
47
47
  * modelKeys: its own model, or the host's of each tier it runs); a run on an adapter's, the one key its wire's route
48
- * sends for the revision's model (adapters.ts' harnessModelKeys). Read at each claim, so a key saved with no restart
49
- * counts at the next. */
48
+ * sends for the revision's model (adapters.ts' harnessModelKeys); and but each harness's own key (HarnessEntry.ownKeys:
49
+ * Cursor's CURSOR_API_KEY) on a run of any other harness. Read at each claim, so a key saved with no restart counts at
50
+ * the next. */
50
51
  export function keysFor(needs, env, rows = TOOL_KEYS) {
51
52
  const unlocked = new Set(rows.filter((row) => row.unlocks.some((unlock) => needs.tools.some((name) => unlocksTool(unlock, name)))).flatMap((row) => row.fields));
52
53
  const scoped = scopedOf(rows);
53
54
  const entry = harnessOf(env, needs.harness);
54
55
  const model = new Set(!entry || entry.facts ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
55
- return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)));
56
+ const owned = [...BUILTIN_OWN_KEYS, ...Object.values(harnessTable(env)).flatMap((each) => each.ownKeys ?? [])];
57
+ return RUN_SECRETS.filter((name) => (!scoped.includes(name) || unlocked.has(name)) && (!MODEL_KEYS.includes(name) || model.has(name)) && (!owned.includes(name) || entry?.ownKeys?.includes(name) === true));
56
58
  }
57
59
  /** The secrets a run of `revision` is handed with the keys `env` holds (needsOf, then keysFor). */
58
60
  export async function secretsFor(revision, rows = TOOL_KEYS, env = process.env) {
@@ -351,13 +351,16 @@ export declare function pendingPauseOf(entries: readonly {
351
351
  }[]): Refusal | undefined;
352
352
  /** The turns a session's records booked (its runner.turn records), in order. */
353
353
  export declare function turnsOf(records: readonly SessionRecord[]): number[];
354
- /** What the request that just answered cost, from the session's records, and the bookings that answer gives (`turns`):
355
- * every runner.turn record no answer was given yet (`given`). A side request's booking (sideTurnsOf) is given and never
356
- * read: it is no answer's, and it stays on the run's ledger and cap. The answer reads the session's own requests
357
- * booked since the answer before it, their booked figures summed (pi asks one at a time, so that is its own; were a
358
- * retry ever booked without an answer of its own, it would be summed in), null when any is unknown; undefined when none
359
- * is booked. Each booking is given once, so one unknown figure stays that answer's, never every later answer's. */
360
- export declare function bookingOfAnswer(records: readonly SessionRecord[], given: ReadonlySet<number>): {
354
+ /** What the request that just answered cost, from the session's records, and the bookings that answer gives (`turns`),
355
+ * among the runner.turn records no answer was given yet (`given`). The answer reads its own conversation's (`own`: the
356
+ * turns its conversation asked; absent, every turn): a booking of a conversation asking beside it (a subagent's child,
357
+ * answering at about the same time) is left for that conversation's answer, neither read nor given. A side request's
358
+ * booking (sideTurnsOf) is given and never read: it is no answer's, and it stays on the run's ledger and cap. The answer
359
+ * reads its conversation's requests booked since the answer before it, their booked figures summed (a conversation asks
360
+ * one at a time, so that is its own; were a retry ever booked without an answer of its own, it would be summed in), null
361
+ * when any is unknown; undefined when none is booked. Each booking is given once, so one unknown figure stays that
362
+ * answer's, never every later answer's. */
363
+ export declare function bookingOfAnswer(records: readonly SessionRecord[], given: ReadonlySet<number>, own?: (turn: number) => boolean): {
361
364
  turns: number[];
362
365
  usd: number | null | undefined;
363
366
  };
@@ -211,13 +211,16 @@ function sideTurnsOf(records) {
211
211
  }
212
212
  return side;
213
213
  }
214
- /** What the request that just answered cost, from the session's records, and the bookings that answer gives (`turns`):
215
- * every runner.turn record no answer was given yet (`given`). A side request's booking (sideTurnsOf) is given and never
216
- * read: it is no answer's, and it stays on the run's ledger and cap. The answer reads the session's own requests
217
- * booked since the answer before it, their booked figures summed (pi asks one at a time, so that is its own; were a
218
- * retry ever booked without an answer of its own, it would be summed in), null when any is unknown; undefined when none
219
- * is booked. Each booking is given once, so one unknown figure stays that answer's, never every later answer's. */
220
- export function bookingOfAnswer(records, given) {
214
+ /** What the request that just answered cost, from the session's records, and the bookings that answer gives (`turns`),
215
+ * among the runner.turn records no answer was given yet (`given`). The answer reads its own conversation's (`own`: the
216
+ * turns its conversation asked; absent, every turn): a booking of a conversation asking beside it (a subagent's child,
217
+ * answering at about the same time) is left for that conversation's answer, neither read nor given. A side request's
218
+ * booking (sideTurnsOf) is given and never read: it is no answer's, and it stays on the run's ledger and cap. The answer
219
+ * reads its conversation's requests booked since the answer before it, their booked figures summed (a conversation asks
220
+ * one at a time, so that is its own; were a retry ever booked without an answer of its own, it would be summed in), null
221
+ * when any is unknown; undefined when none is booked. Each booking is given once, so one unknown figure stays that
222
+ * answer's, never every later answer's. */
223
+ export function bookingOfAnswer(records, given, own = () => true) {
221
224
  const side = sideTurnsOf(records);
222
225
  const turns = [];
223
226
  let usd;
@@ -227,9 +230,13 @@ export function bookingOfAnswer(records, given) {
227
230
  const turn = record.data;
228
231
  if (typeof turn.turn !== "number" || given.has(turn.turn))
229
232
  continue;
230
- turns.push(turn.turn);
231
- if (side.has(turn.turn))
233
+ if (side.has(turn.turn)) {
234
+ turns.push(turn.turn);
235
+ continue;
236
+ }
237
+ if (!own(turn.turn))
232
238
  continue;
239
+ turns.push(turn.turn);
233
240
  // By the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it was booked at
234
241
  // for the cap; one billed to a person's plan is $0 to the run.
235
242
  const figure = turn.usd === undefined && turn.bookedUsd === undefined ? undefined : turnCostOf(turn).usd;
@@ -268,8 +275,11 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
268
275
  // is never ended interrupted; it waits for its answer, which ends it (run once, refused, or withdrawn).
269
276
  const parked = new Set();
270
277
  const sent = new Set();
271
- // A call of a tool that only nests calls (its start marked `nests`): never ended interrupted, as it runs again whole.
278
+ // A call of a tool that only nests calls (its start marked `nests`): never ended interrupted at a record's open, as it
279
+ // runs again whole; only the run's end ends it (openCalls).
272
280
  const nesting = new Set();
281
+ // The calls still open: no end, and not parked unsent. None for a harness that says each call's end (endsItsCalls).
282
+ const openNow = () => (endsItsCalls ? [] : [...started].filter(([callId, ended]) => !ended && !(parked.has(callId) && !sent.has(callId))).map(([callId]) => callId));
273
283
  // The call of the harness's own each call runs inside (nestedIn), named on the call's start.
274
284
  const parents = new Map();
275
285
  const parentOf = (callId) => {
@@ -322,8 +332,8 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
322
332
  if ((entry.kind === KINDS.message || entry.kind === KINDS.input) && typeof data.requestId === "string")
323
333
  followUps.add(data.requestId);
324
334
  }
325
- for (const [callId, ended] of started) {
326
- if (endsItsCalls || ended || (parked.has(callId) && !sent.has(callId)) || nesting.has(callId))
335
+ for (const callId of openNow()) {
336
+ if (nesting.has(callId))
327
337
  continue;
328
338
  await append(KINDS.callEnd, { callId, status: "interrupted" });
329
339
  started.set(callId, true);
@@ -486,7 +496,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
486
496
  },
487
497
  nestedIn: (callId, parent) => void parents.set(callId, parent),
488
498
  unsentParked: () => [...parked].filter((callId) => !sent.has(callId) && started.get(callId) === false),
489
- openNests: () => [...nesting].filter((callId) => started.get(callId) === false),
499
+ openCalls: () => openNow().sort((a, b) => Number(nesting.has(a)) - Number(nesting.has(b))),
490
500
  noteEnd(callId, status, output) {
491
501
  started.set(callId, true);
492
502
  ends.set(callId, { status, ...(output === undefined ? {} : { output }) });
@@ -2087,6 +2097,8 @@ function adapterLoop(specOf, options, deps) {
2087
2097
  const port = booking.models;
2088
2098
  unbooked = 0;
2089
2099
  bookingsWriting = 0;
2100
+ // The conversation each request of this claim was asked in, by its turn, where its client named one.
2101
+ const askedIn = new Map();
2090
2102
  const counted = {
2091
2103
  beforeRequest: async (request) => {
2092
2104
  // The CLI's next request of its main model after its question to the person: never admitted, it asks for the
@@ -2118,6 +2130,11 @@ function adapterLoop(specOf, options, deps) {
2118
2130
  carried = undefined;
2119
2131
  }
2120
2132
  unbooked += 1;
2133
+ // The conversation that asked, as its client named it (pi's, one of several asking at once): whose answer reads
2134
+ // this request's booking (bookedCost).
2135
+ const conversation = request.conversation;
2136
+ if (ticket && conversation !== undefined)
2137
+ askedIn.set(ticket.turn, conversation);
2121
2138
  // The harness's own side call (a title request on its smaller model): never a typical cost of its main requests.
2122
2139
  if (ticket && request.side)
2123
2140
  notOwn.add(ticket.turn);
@@ -2172,14 +2189,20 @@ function adapterLoop(specOf, options, deps) {
2172
2189
  };
2173
2190
  // What the request that just answered cost, once the session's requests are booked (bookingOfAnswer): its own
2174
2191
  // booking's figure, null when unknown; a side request's is given and never read. A refused request's record is its $0.
2192
+ // Its own is its conversation's (`conversation`, as the answer's harness names it and as its requests named it:
2193
+ // askedIn): with several conversations asking at once (pi's subagents), each answer reads the bookings of its
2194
+ // own conversation's requests, never one a conversation beside it is still to read. An answer that names no
2195
+ // conversation reads those of the requests that named none.
2175
2196
  // The bookings already given to an answer: every one the session holds when it opens (an earlier claim's), then each
2176
2197
  // this claim gives.
2177
2198
  const given = new Set(turnsOf(await writer.read().catch(() => [])));
2178
- const bookedCost = async () => {
2199
+ const bookedCost = async (conversation) => {
2179
2200
  await bookingsSettled();
2180
- const booking = bookingOfAnswer(await writer.read().catch(() => []), given);
2181
- for (const turn of booking.turns)
2201
+ const booking = bookingOfAnswer(await writer.read().catch(() => []), given, (turn) => askedIn.get(turn) === conversation);
2202
+ for (const turn of booking.turns) {
2182
2203
  given.add(turn);
2204
+ askedIn.delete(turn);
2205
+ }
2183
2206
  return booking.usd;
2184
2207
  };
2185
2208
  // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
@@ -2264,7 +2287,7 @@ function adapterLoop(specOf, options, deps) {
2264
2287
  // each call it makes named under it, so its rows read as a codemode script's do on every other harness. Its start is
2265
2288
  // marked `nests`, so a crash leaves it open: its harness ends it (ownCalls.ended) from its CLI's own answer to it after
2266
2289
  // the resume, which comes after the rows of the calls it made, never as an interrupted end ahead of them. One no answer
2267
- // of its CLI ends (a stop while it waits, a crash no resume follows) the run's end closes, interrupted (openNests).
2290
+ // of its CLI ends (a stop while it waits, a crash no resume follows) the run's end closes, interrupted (openCalls).
2268
2291
  const ownCalls = record
2269
2292
  ? {
2270
2293
  opened: (callId, name, input) => ownWrite(record.start(callId, name, input, false, true).catch(unlessSealed)),
@@ -3530,8 +3553,19 @@ function adapterLoop(specOf, options, deps) {
3530
3553
  throw new Error("the run's spec names no agent, so its end-of-run step cannot be asked");
3531
3554
  // Every request from here is learning's, between the step's asks too, until the claim ends (reflecting).
3532
3555
  reflecting = true;
3556
+ // The step's signal, as its contract says (loop-contract.ts EndOfRunTurn): aborted by what cuts askEndOfRun's turn, a
3557
+ // person's stop or cancel (stopAbort), a lost claim or a shutdown (deps.signal) and the session closing, so a request
3558
+ // the step sends of its own (a replay's grader, compare-end.ts) is cut with the run, never waited on.
3559
+ const closed = new AbortController();
3560
+ void harness?.closed.then(() => closed.abort(new Error("the Session closed")), () => closed.abort(new Error("the Session closed")));
3561
+ const signal = AbortSignal.any([deps.signal, stopAbort.signal, closed.signal]);
3533
3562
  try {
3534
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal: deps.signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3563
+ const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3564
+ // A replay's or a shadow's grader verdict (runner/compare-end.ts), on its root before its end: its metrics carry it
3565
+ // (workflow-first.ts pathMetrics), where the check and the audit read it.
3566
+ const on = harness;
3567
+ if (rows?.compared && !cut() && on)
3568
+ await on.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: KINDS.compared, data: rows.compared }), context);
3535
3569
  return cut() ?? { kind: "rows", also: rows?.also ?? [] };
3536
3570
  }
3537
3571
  catch (error) {
@@ -3906,13 +3940,14 @@ function adapterLoop(specOf, options, deps) {
3906
3940
  const ends = cliRecord ?? (await openCliRecord(on, theGate.journal, context, now, undefined, true));
3907
3941
  const recordEnds = ends.unsentParked();
3908
3942
  const notRun = data.state === "stopped" ? STOPPED_WHILE_WAITING : ENDED_WHILE_WAITING;
3909
- // A call that only nests calls (a harness's own: Codex's `exec`) still open when the run ends: nothing will end it now
3910
- // (a stop while its call waited, a crash whose next drive never resumed its CLI's thread), so it ends with the run,
3911
- // interrupted, after the rows of its calls (their withdrawals above it in this commit). Its own end on its way is
3943
+ // A CLI's call still open when the run ends: nothing will end it now (a stop that cut it while it ran, a stop while its
3944
+ // call waited, a crash whose next drive never resumed its CLI's thread), so it ends with the run, interrupted, in the
3945
+ // end's commit: nothing of the stopped turn lands after the end. One that only nests calls (a harness's own: Codex's
3946
+ // `exec`) ends after the rows of its calls (their withdrawals above it in this commit); its own end on its way is
3912
3947
  // written first. Marked `withRun`: a park or a stop failed nothing, so its row reads interrupted, never failed.
3913
3948
  while (ownWrites.size > 0)
3914
3949
  await Promise.allSettled([...ownWrites]);
3915
- const cutOpen = ends.openNests();
3950
+ const cutOpen = ends.openCalls();
3916
3951
  const ended = theGate.expect(writesEntry(KINDS.end), { run, ...(also.length ? { also } : {}), ...(take.length ? { take } : {}) });
3917
3952
  // A seal while the end is committed fails it before it is awaited: handled here, read by the await below.
3918
3953
  ended.catch(() => undefined);
@@ -15,9 +15,11 @@ import type { WebFake } from "../web-fake.js";
15
15
  import { type HostToolCtx } from "../host-tools.js";
16
16
  import { type LearnedWorkflow } from "../learning.js";
17
17
  import { type ToolResults } from "../workspace/run-tools.js";
18
+ import { type ClaimModelKey } from "./claim-secrets.js";
18
19
  import { type ClaimMcp } from "./mcp-run.js";
19
20
  import { type AdapterLoopOptions, type AdapterRun, type AdapterRunSpec, hostLifecycle } from "./adapter-loop.js";
20
21
  import { type RunnerHarness } from "./adapters/index.js";
22
+ import { type SubagentTier } from "./subagent.js";
21
23
  import { type Claim, type Journal } from "./loop-contract.js";
22
24
  import type { ReplayCalls } from "../learn/replay-calls.js";
23
25
  import type { ModelRoute } from "./model-route.js";
@@ -172,6 +174,16 @@ export declare function capModelOf(route: ModelRoute): CapModel;
172
174
  /** Particle requests are never automatically replayed after an uncertain failure. Retry is a harness-wide setting,
173
175
  * so a claim with any Particle route disables it for all its conversations, including subagents on other tiers. */
174
176
  export declare function modelRetryOf(routes: Iterable<Pick<ModelRoute, "like">>): Pick<AdapterRunSpec, "retry">;
177
+ /** A replay run's or an audit shadow's grader route (runner/compare-end.ts): its fast model (the revision's
178
+ * modelTiers.fast, else AGENT_MODEL_FAST) when its revision names no agree_on, on pi's wires. A fast model may be another
179
+ * provider's than the run's own, whose key claimSecrets never opened: so its route reads every model key the server
180
+ * holds (savedModelKeys) as a subagent's tier does, held by the run's redactor, on the route's env alone. A run with its
181
+ * own model key carries that key, and no saved key is read. Undefined when there is no fast model, the revision names
182
+ * agree_on, or no route can be made (logged: the pair is then compared whole). */
183
+ export declare function graderRouteOf(body: {
184
+ readonly modelTiers?: Readonly<Partial<Record<SubagentTier, string>>>;
185
+ readonly learning?: unknown;
186
+ }, keyed: boolean, runKey: ClaimModelKey | undefined, claimed: NodeJS.ProcessEnv, cut: HeldRedact, log: (line: string) => void, deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "env" | "routeOf">, holds?: readonly HeldRedact[]): Promise<ModelRoute | undefined>;
175
187
  /** What the runner routes a claimed run on: the launch's model as its start pinned it, sent as pinned, with the
176
188
  * revision's own ref beside it (main prices a gateway's id by the provider that ref names); the revision's ref alone
177
189
  * when the start pinned none. Never the pin's provider and id joined into a ref: a gateway refuses the joined id, and