@parcha/agentrun-serve 0.1.0-beta.61 → 0.1.0-beta.63

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +128 -20
  3. package/dist/adapters.js +4 -2
  4. package/dist/agent-delete.d.ts +3 -3
  5. package/dist/agent-delete.js +50 -4
  6. package/dist/api-only.d.ts +4 -0
  7. package/dist/api-only.js +5 -1
  8. package/dist/archil-settings.d.ts +9 -0
  9. package/dist/archil-settings.js +8 -1
  10. package/dist/bash-read-only.d.ts +3 -0
  11. package/dist/bash-read-only.js +6 -3
  12. package/dist/chatgpt-plan.d.ts +33 -8
  13. package/dist/chatgpt-plan.js +141 -24
  14. package/dist/claude-login.d.ts +12 -5
  15. package/dist/claude-login.js +28 -3
  16. package/dist/cli.js +19 -8
  17. package/dist/composio-triggers.d.ts +9 -3
  18. package/dist/computers.d.ts +3 -0
  19. package/dist/computers.js +2 -1
  20. package/dist/console/assets/{backend-C9ffXUR5.js → backend-BxQ2G1M0.js} +2 -2
  21. package/dist/console/assets/index-C8Y5Zl8x.js +639 -0
  22. package/dist/console/assets/share-CjBJ_rxP.js +6 -0
  23. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/cut-pool.d.ts +14 -0
  27. package/dist/cut-pool.js +98 -0
  28. package/dist/cut-worker.d.ts +14 -0
  29. package/dist/cut-worker.js +16 -0
  30. package/dist/decisions.d.ts +4 -0
  31. package/dist/decisions.js +9 -1
  32. package/dist/env-switch.d.ts +3 -0
  33. package/dist/env-switch.js +3 -0
  34. package/dist/harness-opencode/adapter.d.ts +3 -1
  35. package/dist/harness-opencode/adapter.js +6 -2
  36. package/dist/harness-opencode/harness.d.ts +4 -0
  37. package/dist/harness-opencode/harness.js +6 -1
  38. package/dist/harness-table.d.ts +7 -0
  39. package/dist/harness-table.js +6 -3
  40. package/dist/host-tools.d.ts +18 -3
  41. package/dist/host-tools.js +27 -4
  42. package/dist/import.d.ts +8 -1
  43. package/dist/import.js +36 -5
  44. package/dist/key-check.js +22 -8
  45. package/dist/learn/ledger.d.ts +37 -16
  46. package/dist/learn/ledger.js +56 -24
  47. package/dist/learn/promote.d.ts +4 -1
  48. package/dist/learned-nodes.d.ts +2 -1
  49. package/dist/learned-nodes.js +2 -1
  50. package/dist/learning-cost.d.ts +5 -3
  51. package/dist/learning-model.js +7 -5
  52. package/dist/learning-work.d.ts +69 -0
  53. package/dist/learning-work.js +148 -0
  54. package/dist/mcp-gateway.d.ts +24 -0
  55. package/dist/mcp-gateway.js +97 -8
  56. package/dist/mcp-servers-store.d.ts +7 -10
  57. package/dist/mcp-servers-store.js +15 -9
  58. package/dist/native/cli.js +5 -1
  59. package/dist/ollama-provider.d.ts +10 -3
  60. package/dist/ollama-provider.js +17 -7
  61. package/dist/openapi.js +51 -20
  62. package/dist/otel/tracer.d.ts +6 -3
  63. package/dist/otel/tracer.js +24 -6
  64. package/dist/page.d.ts +7 -0
  65. package/dist/page.js +17 -4
  66. package/dist/place.d.ts +25 -9
  67. package/dist/place.js +37 -11
  68. package/dist/print.d.ts +3 -2
  69. package/dist/print.js +8 -6
  70. package/dist/run-export.js +7 -4
  71. package/dist/run-launch.d.ts +6 -1
  72. package/dist/run-launch.js +26 -6
  73. package/dist/run-model-key.d.ts +2 -1
  74. package/dist/run-model-key.js +2 -1
  75. package/dist/run-reads-over-store.d.ts +7 -0
  76. package/dist/run-reads-over-store.js +32 -4
  77. package/dist/run-view.js +9 -3
  78. package/dist/runnable.d.ts +6 -3
  79. package/dist/runnable.js +21 -11
  80. package/dist/runner/adapter-loop.js +95 -28
  81. package/dist/runner/adapter-run-spec.d.ts +20 -4
  82. package/dist/runner/adapter-run-spec.js +64 -30
  83. package/dist/runner/adapters/index.d.ts +6 -0
  84. package/dist/runner/adapters/index.js +5 -1
  85. package/dist/runner/adapters/pi.d.ts +42 -3
  86. package/dist/runner/adapters/pi.js +114 -13
  87. package/dist/runner/audit.d.ts +8 -2
  88. package/dist/runner/audit.js +34 -18
  89. package/dist/runner/book-cut.d.ts +6 -0
  90. package/dist/runner/book-cut.js +38 -0
  91. package/dist/runner/claim-secrets.d.ts +12 -5
  92. package/dist/runner/claim-secrets.js +28 -12
  93. package/dist/runner/cli-run-spec.d.ts +0 -2
  94. package/dist/runner/cli-run-spec.js +54 -25
  95. package/dist/runner/dispatch.js +2 -0
  96. package/dist/runner/harness-loops.d.ts +5 -0
  97. package/dist/runner/harness-loops.js +4 -1
  98. package/dist/runner/held.d.ts +6 -3
  99. package/dist/runner/learned-first.d.ts +5 -0
  100. package/dist/runner/learned-first.js +1 -1
  101. package/dist/runner/learning-end.d.ts +15 -8
  102. package/dist/runner/learning-end.js +23 -7
  103. package/dist/runner/live-ticker.js +3 -1
  104. package/dist/runner/loop-contract.d.ts +8 -1
  105. package/dist/runner/main.js +2 -0
  106. package/dist/runner/mcp-run.d.ts +5 -0
  107. package/dist/runner/mcp-run.js +18 -0
  108. package/dist/runner/meta-tools.js +4 -4
  109. package/dist/runner/metrics.d.ts +4 -2
  110. package/dist/runner/metrics.js +5 -3
  111. package/dist/runner/model-route.d.ts +4 -0
  112. package/dist/runner/model-route.js +1 -1
  113. package/dist/runner/native-loop.js +2 -2
  114. package/dist/runner/pr-checkout.d.ts +12 -0
  115. package/dist/runner/pr-checkout.js +21 -2
  116. package/dist/runner/promotion.d.ts +9 -2
  117. package/dist/runner/promotion.js +79 -28
  118. package/dist/runner/reflect-hook.d.ts +7 -0
  119. package/dist/runner/reflect-hook.js +2 -1
  120. package/dist/runner/run-child-host.d.ts +10 -6
  121. package/dist/runner/run-child-host.js +65 -41
  122. package/dist/runner/run-child.js +2 -0
  123. package/dist/runner/runner.d.ts +9 -0
  124. package/dist/runner/runner.js +158 -25
  125. package/dist/runner/store-port.d.ts +4 -1
  126. package/dist/runner/workflow-calls.d.ts +4 -3
  127. package/dist/runner/workflow-calls.js +41 -12
  128. package/dist/runner/workflow-first.js +4 -3
  129. package/dist/runner/workflow-loop.js +13 -1
  130. package/dist/runner/workflow-spec.js +1 -1
  131. package/dist/secret-cut.d.ts +4 -0
  132. package/dist/secret-cut.js +1 -1
  133. package/dist/secret-rules.d.ts +2 -1
  134. package/dist/secret-rules.js +88 -24
  135. package/dist/server.d.ts +10 -1
  136. package/dist/server.js +131 -44
  137. package/dist/share-host.d.ts +111 -0
  138. package/dist/share-host.js +669 -0
  139. package/dist/store/schema.d.ts +4 -3
  140. package/dist/store/schema.js +4 -3
  141. package/dist/store/seal.d.ts +8 -2
  142. package/dist/store/seal.js +13 -2
  143. package/dist/store/sqlite/learning-rows.js +2 -1
  144. package/dist/store/sqlite/run-patch.js +4 -4
  145. package/dist/store/sqlite/store.js +28 -4
  146. package/dist/store/store.d.ts +5 -0
  147. package/dist/store-reads/analytics.d.ts +15 -0
  148. package/dist/store-reads/analytics.js +17 -0
  149. package/dist/store-reads/journal.d.ts +2 -0
  150. package/dist/store-reads/journal.js +1 -1
  151. package/dist/store-reads/learning.d.ts +4 -3
  152. package/dist/store-reads/learning.js +62 -18
  153. package/dist/store-view.d.ts +3 -0
  154. package/dist/store-view.js +18 -1
  155. package/dist/suggestions.js +32 -3
  156. package/dist/templates.d.ts +3 -1
  157. package/dist/templates.js +7 -3
  158. package/dist/tool-gate.d.ts +25 -9
  159. package/dist/tool-gate.js +58 -19
  160. package/dist/tool-list.d.ts +4 -0
  161. package/dist/tool-list.js +4 -0
  162. package/dist/tool-plane.d.ts +1 -0
  163. package/dist/tool-plane.js +6 -2
  164. package/dist/tools.js +2 -2
  165. package/dist/trigger-composio.js +1 -1
  166. package/dist/webhooks.d.ts +3 -0
  167. package/dist/webhooks.js +5 -0
  168. package/dist/workspace/archil-claim.d.ts +7 -3
  169. package/dist/workspace/archil-claim.js +13 -5
  170. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  171. package/dist/workspace/archil-mount-credential.js +11 -0
  172. package/dist/workspace/attach.js +22 -5
  173. package/dist/workspace/computer-deps.d.ts +5 -3
  174. package/dist/workspace/computer-deps.js +11 -9
  175. package/dist/workspace/computer-for-claim.d.ts +6 -2
  176. package/dist/workspace/computer-for-claim.js +43 -12
  177. package/dist/workspace/computer-janitor.d.ts +7 -4
  178. package/dist/workspace/computer-janitor.js +7 -4
  179. package/dist/workspace/computer-kept.d.ts +7 -1
  180. package/dist/workspace/computer-kept.js +7 -1
  181. package/dist/workspace/kind-skills/desktop/SKILL.md +17 -4
  182. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  183. package/dist/workspace/mount-revoke-left.js +42 -22
  184. package/dist/workspace/resolve-computer.d.ts +11 -5
  185. package/dist/workspace/resolve-computer.js +22 -13
  186. package/dist/workspace/run-end-computers.js +1 -1
  187. package/dist/workspace/run-tools.d.ts +10 -3
  188. package/dist/workspace/run-tools.js +5 -4
  189. package/dist/wrapped.d.ts +29 -2
  190. package/dist/wrapped.js +20 -3
  191. package/launcher/agentrun-serve +1 -1
  192. package/package.json +12 -12
  193. package/templates/kyb/agent.md +7 -1
  194. package/templates/kyb/evals/list-file-fuzzy-alias/case.yaml +10 -0
  195. package/templates/kyb/evals/list-file-fuzzy-alias/fixtures/web.json +58 -0
  196. package/templates/kyb/evals/list-file-fuzzy-alias/graders/finds-the-transliteration.md +17 -0
  197. package/templates/kyb/evals/list-file-fuzzy-alias/graders/greps-the-files.md +11 -0
  198. package/templates/kyb/evals/list-file-fuzzy-alias/graders/saves-the-uk-file.md +8 -0
  199. package/templates/kyb/evals/list-file-fuzzy-alias/prompt.md +7 -0
  200. package/templates/kyb/evals/list-file-hit/case.yaml +10 -0
  201. package/templates/kyb/evals/list-file-hit/fixtures/web.json +58 -0
  202. package/templates/kyb/evals/list-file-hit/graders/greps-the-files.md +11 -0
  203. package/templates/kyb/evals/list-file-hit/graders/hits-by-company-number.md +18 -0
  204. package/templates/kyb/evals/list-file-hit/graders/saves-the-uk-file.md +8 -0
  205. package/templates/kyb/evals/list-file-hit/prompt.md +7 -0
  206. package/templates/kyb/evals/list-file-no-hit/case.yaml +10 -0
  207. package/templates/kyb/evals/list-file-no-hit/fixtures/web.json +58 -0
  208. package/templates/kyb/evals/list-file-no-hit/graders/greps-the-files.md +11 -0
  209. package/templates/kyb/evals/list-file-no-hit/graders/no-hit-by-whole-file.md +12 -0
  210. package/templates/kyb/evals/list-file-no-hit/graders/saves-the-uk-file.md +8 -0
  211. package/templates/kyb/evals/list-file-no-hit/prompt.md +7 -0
  212. package/templates/kyb/evals/list-file-short-name/case.yaml +9 -0
  213. package/templates/kyb/evals/list-file-short-name/fixtures/web.json +58 -0
  214. package/templates/kyb/evals/list-file-short-name/graders/finds-the-short-name.md +19 -0
  215. package/templates/kyb/evals/list-file-short-name/graders/greps-the-files.md +11 -0
  216. package/templates/kyb/evals/list-file-short-name/graders/saves-the-uk-file.md +8 -0
  217. package/templates/kyb/evals/list-file-short-name/prompt.md +7 -0
  218. package/templates/kyb/evals/list-file-split-name/case.yaml +11 -0
  219. package/templates/kyb/evals/list-file-split-name/fixtures/web.json +58 -0
  220. package/templates/kyb/evals/list-file-split-name/graders/finds-the-director.md +18 -0
  221. package/templates/kyb/evals/list-file-split-name/graders/greps-the-files.md +11 -0
  222. package/templates/kyb/evals/list-file-split-name/graders/saves-the-uk-file.md +8 -0
  223. package/templates/kyb/evals/list-file-split-name/prompt.md +7 -0
  224. package/templates/kyb/kyb.schema.json +2 -2
  225. package/templates/kyb/rules/SANCTIONS.md +82 -13
  226. package/dist/console/assets/index-BnZV3lvW.js +0 -639
  227. package/dist/console/assets/share-B1o5mJ56.js +0 -6
  228. /package/dist/console/assets/{styles-D_znYrHR.js → styles-BGZxYkky.js} +0 -0
@@ -1,8 +1,10 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
+ import type { JsonValue } from "@earendil-works/chord/json";
2
3
  import type { Models } from "@earendil-works/pi-ai";
3
4
  import { type Extension, type Harness, type Registry, type ToolRegistration } from "@earendil-works/pi-durable";
4
- import { type AgentAdapter, type SessionIO, type Wire } from "@parcha/agentrun-kernel";
5
+ import { type AgentAdapter, type HostTool, type SessionIO, type Wire } from "@parcha/agentrun-kernel";
5
6
  import { type ModelProxy, type ProviderPolicy } from "@parcha/agentrun-kernel/host";
7
+ import { TurnBudget } from "@parcha/agentrun-kernel/process";
6
8
  import { type SessionLike, type SessionModelPort } from "../../port-models.js";
7
9
  import { type CallStatus } from "../journal-kinds.js";
8
10
  import { CALL_REFUSED } from "../../timeline/index.js";
@@ -105,8 +107,11 @@ export interface PiAdapterOptions {
105
107
  export declare const PI_BASE_INPUT_TOKENS = 280;
106
108
  /** pi as an AgentAdapter for one claim's run. */
107
109
  export declare function piAdapter(options: PiAdapterOptions): AgentAdapter;
108
- /** A tier's model as its proxy takes it: its route's provider, model, catalog entry, price and fetch (model-route.ts). */
109
- export type TierModel = Pick<PiAdapterOptions, "provider" | "model" | "like" | "price" | "fetch">;
110
+ /** A tier's model as its proxy takes it: its route's provider, model, catalog entry, price and fetch (model-route.ts), and
111
+ * its catalog's context window, which a conversation on the tier holds each tool result to (boundPiResult). */
112
+ export type TierModel = Pick<PiAdapterOptions, "provider" | "model" | "like" | "price" | "fetch"> & {
113
+ readonly contextWindow?: number;
114
+ };
110
115
  /** The tier proxies a session holds (openTierProxies): each tier's port for a side request under `label`, and their close. */
111
116
  export interface TierProxies {
112
117
  port(label: string, tier: string): SessionModelPort | undefined;
@@ -181,3 +186,37 @@ export declare const HOST_TOOL_OUTPUT: Readonly<{
181
186
  maxLines: number;
182
187
  maxBytes: number;
183
188
  }>;
189
+ /**
190
+ * `result` with its text held to the kernel's bound for a model of `contextWindow` (boundResult: the window's share, under
191
+ * HOST_RESULT_MAX_CHARS; none known, that bound alone), as every bridged harness's tool bridge holds a result, and, for a
192
+ * call the model made (`claim`), to the call's share of what its turn has left (the kernel's TurnBudget): within it,
193
+ * undefined (the result stands as it is); past it, its text parts as one text cut at the bound with its note, or refused
194
+ * in words for a window too small for any cut, its images kept after it. Never the oversized text.
195
+ */
196
+ export declare function boundPiResult<R extends {
197
+ readonly output?: readonly {
198
+ readonly type: string;
199
+ readonly text?: string;
200
+ }[];
201
+ }>(result: R, contextWindow: number | undefined, claim?: {
202
+ readonly turn: TurnBudget;
203
+ readonly callId: string;
204
+ }): Promise<R | undefined>;
205
+ /**
206
+ * `forward` passing on at most `max` characters of a tool's live output in all (the kernel's resultMaxChars for the calling
207
+ * agent's model), the line saying where it stopped counted in them; nothing past that, and nothing at all for a bound too
208
+ * small for that line. pi keeps what a tool streams in its slot, and the one result it writes without its afterTool hook
209
+ * (a call cut off its restart limit times: pi-durable's tool task, endCutOff and abort's last attempt, from the slot) is
210
+ * that text, so this is what holds that result to the bound. A chunk is never cut between the halves of a surrogate pair.
211
+ */
212
+ export declare function boundedProgress(forward: (chunk: string) => void, max: number): (chunk: string) => void;
213
+ /** A host tool as a pi tool: replay-safe or at most once, its answer the host's text and any images it shows, its text
214
+ * held to the kernel's bound for the calling agent's model (boundResult, at `windowOf` its model: the window's share,
215
+ * under the host's bound, HOST_TOOL_OUTPUT), as every bridged harness's tool bridge holds it. Each call gets what pi's
216
+ * own tool task gives a tool: the calling agent's model, resolved in the session's models (its input and input limits,
217
+ * which a file read sizes an image by), and pi's output stream (the running tool's live slot); and its attempt
218
+ * (`attemptOf`: above 0 for a call the gate did not pass in this session, pi's rerun after a crash). Exported for the
219
+ * test of what its tool streams to pi (test/pi-tool-progress.test.mjs); the session builds it (sessionOn). */
220
+ export declare function piTool(tool: HostTool, io: PiSessionIO, attemptOf?: (callId: string) => number | undefined, touched?: Set<string>, nestedRefusals?: ReadonlyMap<string, string>, windowOf?: (ref: {
221
+ readonly provider: string;
222
+ } | undefined) => number | undefined, turnOf?: (conversationId: unknown) => TurnBudget): ToolRegistration<never, JsonValue>;
@@ -1,10 +1,11 @@
1
1
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
2
  import { clampThinkingLevel, createModels, getSupportedThinkingLevels } from "@earendil-works/pi-ai/models";
3
- import { defineExtension, defineTool, GenerationTask, hook, ProviderDoc, ToolTask } from "@earendil-works/pi-durable";
3
+ import { AgentDoc, defineExtension, defineTool, GenerationTask, hook, ProviderDoc, ToolTask } from "@earendil-works/pi-durable";
4
4
  import { anthropicPolicy, withWebSearches } from "@parcha/agentrun-harness-claude";
5
5
  import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
6
6
  import { conversationLabel, NATIVE_SEARCH_USD, startModelProxy } from "@parcha/agentrun-kernel/host";
7
7
  import { INTERRUPTED_TEXT } from "@parcha/agentrun-kernel/kernel";
8
+ import { boundTo, resultMaxChars, TurnBudget } from "@parcha/agentrun-kernel/process";
8
9
  import { randomBytes } from "node:crypto";
9
10
  import { DEFAULT_HARNESS } from "../../harness.js";
10
11
  import { durableWait } from "../../workflow/pi-versions.js";
@@ -293,7 +294,22 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
293
294
  const touched = new Set();
294
295
  // A refused nested call's words, by its id (pi's nested result keeps none of a refused call's output).
295
296
  const nestedRefusals = new Map();
296
- const tools = [...spec.tools.filter((tool) => !owned.has(tool.name)).map((tool) => piTool(tool, io, (callId) => (io.gate ? (passed.has(callId) ? 0 : 1) : undefined), touched, nestedRefusals)), ...(options.tools ?? []).map((tool) => announcing(tool, io))];
297
+ // The context window of the model a conversation runs on, when the host knows it: the session's own model's (the
298
+ // session's, from its catalog), or a tier's (its route's). None: the host's bound alone holds each result.
299
+ const tierWindows = new Map(tiers.each.map(([tier, route]) => [tierProvider(tier), route.contextWindow]));
300
+ const windowOf = (ref) => (ref === undefined || ref.provider === PROVIDER ? spec.contextWindow : tierWindows.get(ref.provider));
301
+ // Each conversation's turn budget (the kernel's): what its model's window has left for the results of the calls its
302
+ // last answer made, which those calls share. pi reports each answer's facts (afterResponse); with none yet, the
303
+ // session's system text, counted, is what the context holds.
304
+ const turns = new Map();
305
+ const turnOf = (conversationId) => {
306
+ const key = String(conversationId);
307
+ let turn = turns.get(key);
308
+ if (!turn)
309
+ turns.set(key, (turn = new TurnBudget(spec.system)));
310
+ return turn;
311
+ };
312
+ const tools = [...spec.tools.filter((tool) => !owned.has(tool.name)).map((tool) => piTool(tool, io, (callId) => (io.gate ? (passed.has(callId) ? 0 : 1) : undefined), touched, nestedRefusals, windowOf, turnOf)), ...(options.tools ?? []).map((tool) => announcing(tool, io))];
297
313
  // A refused call's words (the gate's deny, main's), by call: its result is those words alone, as main gives them.
298
314
  const refusals = refusalWords();
299
315
  const extension = defineExtension({
@@ -327,13 +343,29 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
327
343
  });
328
344
  },
329
345
  // A call the gate refused: its result is main's words alone, an error, never pi's framing of a blocked call (its
330
- // diagnostic, which the model reads as "<harness>[error] Tool call blocked: ..."). Every other result is pi's.
331
- afterTool: async (call, result) => refusals.resultOf(call.id, result, call.parent !== undefined),
346
+ // diagnostic, which the model reads as "<harness>[error] Tool call blocked: ..."). Every other result is pi's,
347
+ // held to the kernel's bound for the conversation's model (boundPiResult): every tool's, a host tool's and a
348
+ // pi-native one's (web_fetch, web_search, the browser's, a subagent's) alike, as every bridged harness's tool
349
+ // bridge holds each result. This hook runs on every result pi's tool task writes, so no result reaches the model
350
+ // around it. A call the model made (not one nested in a tool's) is held to its share of its turn as well.
351
+ afterTool: async (call, result, api, hookContext) => {
352
+ const refused = refusals.resultOf(call.id, result, call.parent !== undefined);
353
+ if (refused)
354
+ return refused;
355
+ const agent = (await api.snapshot(AgentDoc, api.conversationId, hookContext).catch(() => undefined));
356
+ return (await boundPiResult(result, windowOf(agent?.model), call.parent === undefined ? { turn: turnOf(api.conversationId), callId: call.id } : undefined));
357
+ },
332
358
  }),
333
359
  // An answer's cost is the runner's booking of its request, never pi's $0 for a model it has no price for: set on
334
360
  // the answer before pi stores it, so the answer, pi.usage and the live timeline carry it; unknown stays unknown.
335
361
  hook(GenerationTask, {
336
362
  afterResponse: async (message, api, hookContext) => {
363
+ // The turn's facts, for its calls' results: the input its request held (cached input included), the answer's
364
+ // output, and the calls it made.
365
+ const usage = message.usage;
366
+ const held = usage ? (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0) : 0;
367
+ const calls = Array.isArray(message.content) ? message.content.filter((part) => part.type === "toolCall").length : undefined;
368
+ turnOf(api.conversationId).open({ ...(held > 0 ? { inputTokens: held, outputTokens: usage?.output ?? 0 } : {}), ...(calls === undefined ? {} : { calls }) });
337
369
  if (!io.bookedCost)
338
370
  return;
339
371
  // The conversation that asked, by the id pi sends with each of its requests (its pi.provider document's), as
@@ -529,12 +561,72 @@ function piNested(api, context, touched, refusals, ended) {
529
561
  },
530
562
  };
531
563
  }
532
- /** A host tool as a pi tool: replay-safe or at most once, its answer the host's text and any images it shows, passed
533
- * whole within the host's bound (HOST_TOOL_OUTPUT). Each call gets what pi's own tool task gives a tool: the calling
534
- * agent's model, resolved in the session's models (its input and input limits, which a file read sizes an image by),
535
- * and pi's output stream (the running tool's live slot); and its attempt (`attemptOf`: above 0 for a call the gate did
536
- * not pass in this session, pi's rerun after a crash). */
537
- function piTool(tool, io, attemptOf = () => undefined, touched = new Set(), nestedRefusals = new Map()) {
564
+ /**
565
+ * `result` with its text held to the kernel's bound for a model of `contextWindow` (boundResult: the window's share, under
566
+ * HOST_RESULT_MAX_CHARS; none known, that bound alone), as every bridged harness's tool bridge holds a result, and, for a
567
+ * call the model made (`claim`), to the call's share of what its turn has left (the kernel's TurnBudget): within it,
568
+ * undefined (the result stands as it is); past it, its text parts as one text cut at the bound with its note, or refused
569
+ * in words for a window too small for any cut, its images kept after it. Never the oversized text.
570
+ */
571
+ export async function boundPiResult(result, contextWindow, claim) {
572
+ const parts = result.output;
573
+ if (!parts)
574
+ return undefined;
575
+ const whole = parts.map((part) => (part.type === "text" ? (part.text ?? "") : "")).join("");
576
+ const { text, truncated } = boundTo(whole, await maxOf(contextWindow, claim));
577
+ claim?.turn.settle(claim.callId, text.length);
578
+ if (!truncated)
579
+ return undefined;
580
+ return { ...result, output: [{ type: "text", text }, ...parts.filter((part) => part.type !== "text")] };
581
+ }
582
+ /** The most characters a result reaches a model of `contextWindow` with: the window's share (resultMaxChars), and, for a
583
+ * call the model made (`claim`), its claim on its turn, the same figure each time it is asked in one turn. */
584
+ async function maxOf(contextWindow, claim) {
585
+ const max = resultMaxChars(contextWindow === undefined ? undefined : { contextWindow });
586
+ if (!claim || contextWindow === undefined)
587
+ return max;
588
+ await claim.turn.ready();
589
+ return Math.min(max, claim.turn.claim(claim.callId, contextWindow));
590
+ }
591
+ /** The line a tool's live output ends with where boundedProgress stopped passing it on. */
592
+ const progressCutNote = (kept) => `\n[live output cut at ${kept} characters: the rest is not kept, past what this model's context window takes]`;
593
+ /**
594
+ * `forward` passing on at most `max` characters of a tool's live output in all (the kernel's resultMaxChars for the calling
595
+ * agent's model), the line saying where it stopped counted in them; nothing past that, and nothing at all for a bound too
596
+ * small for that line. pi keeps what a tool streams in its slot, and the one result it writes without its afterTool hook
597
+ * (a call cut off its restart limit times: pi-durable's tool task, endCutOff and abort's last attempt, from the slot) is
598
+ * that text, so this is what holds that result to the bound. A chunk is never cut between the halves of a surrogate pair.
599
+ */
600
+ export function boundedProgress(forward, max) {
601
+ const room = max - progressCutNote(max).length;
602
+ let sent = 0;
603
+ let stopped = false;
604
+ return (chunk) => {
605
+ if (stopped)
606
+ return;
607
+ // Only within the room.
608
+ if (sent + chunk.length <= room) {
609
+ sent += chunk.length;
610
+ forward(chunk);
611
+ return;
612
+ }
613
+ stopped = true;
614
+ if (room <= 0)
615
+ return;
616
+ let take = room - sent;
617
+ if (take > 0 && (chunk.charCodeAt(take - 1) & 0xfc00) === 0xd800 && (chunk.charCodeAt(take) & 0xfc00) === 0xdc00)
618
+ take -= 1;
619
+ forward(`${chunk.slice(0, take)}${progressCutNote(sent + take)}`);
620
+ };
621
+ }
622
+ /** A host tool as a pi tool: replay-safe or at most once, its answer the host's text and any images it shows, its text
623
+ * held to the kernel's bound for the calling agent's model (boundResult, at `windowOf` its model: the window's share,
624
+ * under the host's bound, HOST_TOOL_OUTPUT), as every bridged harness's tool bridge holds it. Each call gets what pi's
625
+ * own tool task gives a tool: the calling agent's model, resolved in the session's models (its input and input limits,
626
+ * which a file read sizes an image by), and pi's output stream (the running tool's live slot); and its attempt
627
+ * (`attemptOf`: above 0 for a call the gate did not pass in this session, pi's rerun after a crash). Exported for the
628
+ * test of what its tool streams to pi (test/pi-tool-progress.test.mjs); the session builds it (sessionOn). */
629
+ export function piTool(tool, io, attemptOf = () => undefined, touched = new Set(), nestedRefusals = new Map(), windowOf = () => undefined, turnOf) {
538
630
  return defineTool({
539
631
  name: tool.name,
540
632
  description: tool.description,
@@ -551,21 +643,30 @@ function piTool(tool, io, attemptOf = () => undefined, touched = new Set(), nest
551
643
  const attempt = attemptOf(api.callId);
552
644
  const ref = (await api.agent(toolContext)).model;
553
645
  const model = ref === undefined ? undefined : api.models.getModel(ref.provider, ref.modelId);
646
+ const window = windowOf(ref);
647
+ // A call the model made claims its share of its turn (a nested call's result goes to the tool that made it).
648
+ const claim = turnOf && !api.callId.includes("/") ? { turn: turnOf(api.conversationId), callId: api.callId } : undefined;
649
+ const max = await maxOf(window, claim);
554
650
  const answer = await tool.call(args ?? {}, {
555
651
  callId: api.callId, signal: toolContext.abortSignal ?? io.signal,
556
652
  ...(model ? { model } : {}),
557
- output: (chunk) => api.output(chunk),
653
+ // What the tool streams is what pi's slot keeps, and the result pi writes without its hooks (past its restart
654
+ // limit) is that text: held to the same bound as the answer (boundedProgress).
655
+ output: boundedProgress((chunk) => api.output(chunk), max),
558
656
  ...(attempt === undefined ? {} : { attempt }),
559
657
  ...(tool.nests ? { nested: piNested(api, toolContext, touched, nestedRefusals, io.nestedEnded) } : {}),
560
658
  });
561
- io.onEvent({ type: "tool_end", callId: api.callId, name: tool.name, isError: Boolean(answer.isError), result: answer.text });
659
+ // The answer's text within the bound for the calling agent's model (its window, when the host knows it), as the
660
+ // tool bridge holds a bridged harness's; the host's record of the call (its tool_end) carries the same text.
661
+ const { text, truncated } = boundTo(answer.text, max);
662
+ io.onEvent({ type: "tool_end", callId: api.callId, name: tool.name, isError: Boolean(answer.isError), result: text, ...(truncated ? { truncated } : {}) });
562
663
  const images = (answer.images ?? []).map((image) => ({ type: "image", data: image.data, mimeType: image.mimeType }));
563
664
  // A nested call's (its id `<callId>/<key>`) value in the result's details (which the model never reads), recorded
564
665
  // with it: what tools_call or a script reads (piNested). A call the model made itself keeps its result as it was.
565
666
  // A nesting tool that ended at a refused nested call (a script stopped there) carries the refusal mark, as the
566
667
  // nested call's result does (refusalWords): its rows read refused, never as a call that ran and failed.
567
668
  const details = { ...(answer.structured !== undefined && api.callId.includes("/") ? { [HOST_VALUE]: answer.structured } : {}), ...(answer.refused && answer.isError ? { [CALL_REFUSED]: true } : {}) };
568
- return { output: [{ type: "text", text: answer.text }, ...images], ...(answer.isError ? { isError: true } : {}), ...(Object.keys(details).length ? { details } : {}) };
669
+ return { output: [{ type: "text", text }, ...images], ...(answer.isError ? { isError: true } : {}), ...(Object.keys(details).length ? { details } : {}) };
569
670
  },
570
671
  });
571
672
  }
@@ -3,6 +3,7 @@ import type { AuxiliaryAdmitter } from "../source-sync/auxiliary.js";
3
3
  import { type AuditLoop } from "../learning-setting.js";
4
4
  import { type RunLaunch } from "../run-launch.js";
5
5
  import { type RunRow, type Store } from "../store/store.js";
6
+ import { type AtRunEnd } from "../learning-work.js";
6
7
  import type { Shown } from "../learning.js";
7
8
  import type { EndOfRunTurn } from "./loop-contract.js";
8
9
  import { type WorkflowFirst } from "./workflow-first.js";
@@ -20,9 +21,14 @@ export type AuditDeps = {
20
21
  readonly sealKey?: Buffer;
21
22
  readonly admitAuxiliary?: AuxiliaryAdmitter;
22
23
  readonly now?: () => number;
23
- /** Why model spend beside the claimed run is skipped (claim-secrets.ts claimSpendOff): a shadow is a run the runner
24
- * starts with no caller's key. Absent: it runs. */
24
+ /** Why model spend beside the claimed run is skipped (claim-secrets.ts claimSpendOff). Absent: it runs. */
25
25
  readonly spendOff?: (what: string) => string | undefined;
26
+ /** Whether the claim holds its run's own model key now (claim-secrets.ts keyedNow): its shadow then spends on a sealed
27
+ * copy of that key. Absent: never. */
28
+ readonly keyed?: () => boolean;
29
+ /** What the claim queued to start at its run's end (learning-work.ts atRunEnd): run after the end-of-run step, before
30
+ * the audit's start (withAudit). */
31
+ readonly atEnd?: AtRunEnd;
26
32
  };
27
33
  /** The words a second hold within stop_window leaves on its record: what the owner reads. */
28
34
  export declare const STOPPED_TWICE = "stopped: the workflow disagreed with the known answer twice";
@@ -35,7 +35,8 @@ import { launchBody, readLaunchBody } from "../run-launch.js";
35
35
  import { runEntries } from "../store-reads/journal.js";
36
36
  import { runPathOverStore } from "../store-reads/learning.js";
37
37
  import { FINAL_STATES, StoreConstraint } from "../store/store.js";
38
- import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
38
+ import { openRunLaunch, sealHandedLaunch } from "../store/seal.js";
39
+ import { LEARNING_CHILD_MS, noteLearningChild, RUN_CAP_MIN_USD } from "../learning-work.js";
39
40
  import { isObject } from "../validate.js";
40
41
  import { addAuditLines, auditableLaunch, auditEveryOf, auditDrawn, auditsOffWords, auditWriterOf, holdOf, ledgerOf, lineKey, openAudits, rowsOf, shadowRunId } from "../learn/audit.js";
41
42
  import { lastRunsOf, sinceReset } from "../learn/compile.js";
@@ -45,9 +46,6 @@ import { auditRoomOf } from "./learning-end.js";
45
46
  import { answerJudged, answerOf, answerRowOf } from "./promotion.js";
46
47
  import { servedOf } from "./workflow-first.js";
47
48
  import { held, heldEndOfRun } from "./held.js";
48
- /** The least cap a run can take a step under (cap.ts: the next step needs at least a cent): a shadow with less left
49
- * is never started. */
50
- const RUN_CAP_MIN_USD = 0.01;
51
49
  /** The words a second hold within stop_window leaves on its record: what the owner reads. */
52
50
  export const STOPPED_TWICE = "stopped: the workflow disagreed with the known answer twice";
53
51
  const iso = (ms) => new Date(ms).toISOString();
@@ -104,16 +102,24 @@ export const AUDIT_PARKED = "the audit ended where it would wait on a person";
104
102
  * end is counted (auditRoomOf: its job, its follow-ups, its compile turns). A run that
105
103
  * could never be audited (no learning start, or not auditableLaunch) keeps `step` as it is. */
106
104
  export function withAudit(step, deps) {
107
- if (!deps.launch.learning || !auditableLaunch(deps.launch))
105
+ if (!deps.launch.learning)
106
+ return step;
107
+ const audited = auditableLaunch(deps.launch);
108
+ // A run never audited gets no step it had none of: the end of a run with no step queues nothing (its checks wait).
109
+ if (!audited && (!deps.atEnd || !step))
108
110
  return step;
109
111
  // In a run's own process the whole step is its runner's (held.ts endOfRun), the audit's start with it: it reads the
110
112
  // run's journal and writes the ledger and a run, which no run's process may.
111
113
  if (held())
112
114
  return heldEndOfRun();
115
+ // What the claim queued for its run's end (a check on its own key) starts first, so the audit's room counts it.
113
116
  return async (input) => {
114
117
  const rows = step ? await step(input) : undefined;
115
- if (input.cut === undefined)
116
- await auditAtEnd(deps, input.runId);
118
+ if (input.cut === undefined) {
119
+ await deps.atEnd?.run();
120
+ if (audited)
121
+ await auditAtEnd(deps, input.runId);
122
+ }
117
123
  return rows;
118
124
  };
119
125
  }
@@ -148,8 +154,8 @@ export async function startAudit(deps, serve) {
148
154
  const { store, agentId, runId, launch, log } = deps;
149
155
  if (!serve || serve.replay || launch.replay || launch.audit || !launch.learning || !auditableLaunch(launch))
150
156
  return;
151
- // A shadow is a run of its own the runner starts, on no caller's key: skipped where the served run brought its own key
152
- // or the server holds none (claimSpendOff).
157
+ // A shadow is a run of its own the runner starts: on the served run's own key while its claim holds it, else on the
158
+ // server's; skipped where the run's key was erased, or the server holds none (claimSpendOff).
153
159
  const off = deps.spendOff?.("A shadow audit");
154
160
  if (off)
155
161
  return void log(`workflow-first: ${off}`);
@@ -192,9 +198,12 @@ export async function startAudit(deps, serve) {
192
198
  if (allowance === null || (allowance !== undefined && allowance < RUN_CAP_MIN_USD)) {
193
199
  const skipped = { run: runId, shadow_run: null, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, source: "shadow", agreed: null, served_cost: null, shadow_cost: null, ...turn, skipped: "no allowance", at: iso((deps.now ?? Date.now)()) };
194
200
  await addLines(deps, [skipped]);
201
+ await noteLearningChild(store.settings, runId, { run: null, kind: "shadow", at: (deps.now ?? Date.now)(), ...(deps.keyed?.() ? { keyed: true } : {}), dropped: "no_budget" });
195
202
  log(`workflow-first: ${serve.name} at ${serve.digest} served this run, drawn for its audit (1 in ${k}); no shadow: ${allowance === null ? "what it spent under its cap is not known" : `its cap leaves $${allowance}, under a run's smallest cap`} (no allowance)`);
196
203
  return;
197
204
  }
205
+ // Its start, and its deadline from it (learning-work.ts LEARNING_CHILD_MS): its runner cancels it there.
206
+ const at = (deps.now ?? Date.now)();
198
207
  const shadow = {
199
208
  input: launch.input,
200
209
  title: `Audit of ${launch.title}`.slice(0, 200),
@@ -210,7 +219,7 @@ export async function startAudit(deps, serve) {
210
219
  ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
211
220
  ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
212
221
  ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
213
- audit: { of: runId, workflow: serve.name, digest: serve.digest },
222
+ audit: { of: runId, workflow: serve.name, digest: serve.digest, deadlineAt: at + LEARNING_CHILD_MS },
214
223
  };
215
224
  const started = { source: "started", run: runId, shadow_run: id, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, ...turn, at: iso((deps.now ?? Date.now)()) };
216
225
  // The ledger after (`all`, never `added`): a started line already there (a crash between it and its shadow) is in it,
@@ -221,7 +230,11 @@ export async function startAudit(deps, serve) {
221
230
  log(`workflow-first: ${serve.name} at ${serve.digest} served this run, drawn for its audit (1 in ${k}); no shadow: the workflow's version was purged since`);
222
231
  return;
223
232
  }
224
- const sealed = await handedTo(deps, runId, id);
233
+ const keyed = deps.keyed?.() === true;
234
+ const sealed = await handedTo(deps, runId, id, keyed);
235
+ // Named as the run's learning work before it exists (learning-work.ts): its learning_work lists it while it runs, and
236
+ // the same write moves the run's learning deadline to this one's.
237
+ await noteLearningChild(store.settings, runId, { run: id, kind: "shadow", at, ...(keyed ? { keyed: true } : {}) });
225
238
  try {
226
239
  if (sourceSyncOf(revision?.body))
227
240
  await deps.admitAuxiliary({ runId: id, agentId, revisionId: deps.revisionId, launch: shadow, ...(sealed ? { sealed } : {}) });
@@ -239,14 +252,17 @@ export async function startAudit(deps, serve) {
239
252
  log(`workflow-first: the audit of this run did not start (${error?.message ?? error})`);
240
253
  }
241
254
  }
242
- /** The per_run MCP credentials run `from` was handed, sealed for shadow run `id` alone (as a replay run's are). */
243
- async function handedTo(deps, from, id) {
255
+ /** The per_run MCP credentials run `from` was handed, and its own model key when `keyed`, sealed for shadow run `id`
256
+ * alone (store/seal.ts sealHandedLaunch, as a replay run's are). A keyed shadow whose run holds no key now is never
257
+ * started (throws): it would spend on the server's key. */
258
+ async function handedTo(deps, from, id, keyed) {
244
259
  // A run's own process holds no seal key: its runner seals them again, from its own run alone (held.ts handOn).
245
- if (!deps.sealKey)
246
- return held()?.handOn(from, id);
247
- const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
248
- const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
249
- return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
260
+ const sealed = deps.sealKey
261
+ ? await deps.store.runs.launch(from).then((one) => (one.sealed === null ? undefined : sealHandedLaunch(deps.sealKey, from, one.sealed, id, keyed)), () => undefined)
262
+ : await held()?.handOn(from, id, keyed);
263
+ if (keyed && (!deps.sealKey || !sealed || !openRunLaunch(deps.sealKey, id, sealed)?.model))
264
+ throw new Error("the run whose own model key its shadow would spend on holds none now");
265
+ return sealed;
250
266
  }
251
267
  /** Writes the row of each open audit (a started line with no row yet) whose two runs, read by id, ended, the batch
252
268
  * oldest served run first (the ledger's tail is its newest); a run that is gone (its shadow never created, say) ends it
@@ -0,0 +1,6 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import type { Journal } from "./loop-contract.js";
3
+ /** Books, under the claim that holds `journal`, every model request of the run's sessions that an earlier claim left
4
+ * open (bookCut: at its hold, else at an unknown price). The paid-tools and decisions sessions are not model requests'
5
+ * and stay as they are. Idempotent: a booked request is answered. */
6
+ export declare function bookCutRequests(journal: Journal, context: Context, flush: () => Promise<void>): Promise<void>;
@@ -0,0 +1,38 @@
1
+ // What a run's earlier claim left out when its runner went, booked by a claim that ends the run with no loop: each model
2
+ // request it admitted and never saw answered is booked once, cut, at its hold (the kernel's bookCut, the rule every
3
+ // loop's booking takes before it sends anything), so the run's cost reads what it may have spent, never an unknown.
4
+ import { createModels } from "@earendil-works/pi-ai/models";
5
+ import { createRegistry, Harness } from "@earendil-works/pi-durable";
6
+ import { modelPortFor } from "@parcha/agentrun-kernel";
7
+ import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
8
+ import { journalSessions } from "./sessions.js";
9
+ /** `journal` as its Harness sees it: every method its own, but close, which is the claim's to do. */
10
+ function unclosed(journal) {
11
+ return new Proxy(journal, {
12
+ get(target, key) {
13
+ if (key === "close")
14
+ return async () => undefined;
15
+ const value = Reflect.get(target, key, target);
16
+ return typeof value === "function" ? value.bind(target) : value;
17
+ },
18
+ });
19
+ }
20
+ /** Books, under the claim that holds `journal`, every model request of the run's sessions that an earlier claim left
21
+ * open (bookCut: at its hold, else at an unknown price). The paid-tools and decisions sessions are not model requests'
22
+ * and stay as they are. Idempotent: a booked request is answered. */
23
+ export async function bookCutRequests(journal, context, flush) {
24
+ const harness = await Harness.open(unclosed(journal), { models: createModels(), registry: createRegistry(), onReport: () => { } }, context);
25
+ try {
26
+ const sessions = journalSessions(harness, context, { flush });
27
+ for (const key of await sessions.keys()) {
28
+ if (key === TOOL_SESSION || key === DECISION_SESSION)
29
+ continue;
30
+ const writer = await sessions.open(key);
31
+ await (await modelPortFor(writer, { key })).bookCut();
32
+ }
33
+ await flush();
34
+ }
35
+ finally {
36
+ await harness.close(context).catch(() => undefined);
37
+ }
38
+ }
@@ -36,7 +36,9 @@ type RunLaunchReader = {
36
36
  * redactor, which the run's own tool keys are carried into before they are laid, so its journal is cut of them as it is
37
37
  * written (no one holds them after the turn); a plain JS caller that passes none lays no run key, and throws. A run whose
38
38
  * model sends no key (sendsNoModelKey: a held run its model kept from running, any run on a --faux runner, a faux-pinned
39
- * one) is laid no model key and no plan sign-in. Its tools' keys, its decision keys and its own tool keys are laid as any run's. The one tool key row that names
39
+ * one) is laid no model key and no plan sign-in. A held run its model kept from running at its create (hold.refused) is
40
+ * laid no built-in harness's own key either (harness-table.ts BUILTIN_OWN_KEYS: Cursor's): its agent never starts. Its
41
+ * tools' keys, its decision keys and its own tool keys are laid as any run's. The one tool key row that names
40
42
  * a model key's name, TypeSafe's (key-words.ts; model.ts PROVIDER_KEYS typesafe), is a decision key (secrets.ts
41
43
  * DECISION_KEYS): keysFor never names one, so the model key filter below never sees it, and decisionKeysFor lays it
42
44
  * apart, as it lays OpenRouter's for a decision node that runs on it. */
@@ -148,11 +150,16 @@ export declare const keyedAtClaim: (runKey: ClaimModelKey | undefined) => boolea
148
150
  * claimSpendOff's spend with no key to pay it. */
149
151
  export declare function serverKeyless(deps: ClaimSecretsDeps): Promise<boolean>;
150
152
  /** Why the claim's model spend after the run's turn, or beside it on runs the runner starts (a shadow audit, a replay
151
- * check), is skipped: `what` the work, asked when that spend would start. A run that brought
152
- * its own key, at its start or with a message since (everHeld): that key is erased with its turn's end and the server's
153
- * never pays for it (runKeyEndedFor). Else, a server that holds no gateway key (the runner's environment or
154
- * Settings → Model keys) has none to spend (noServerKeyWords). Undefined where it runs. */
153
+ * check), is skipped: `what` the work, asked when that spend would start. A claim that holds the run's own key now runs
154
+ * it on that key (the runs it starts take a sealed copy of it, store/seal.ts sealHandedLaunch), whatever the server
155
+ * holds. A run that brought its own key, at its start or with a message since (everHeld), and holds none now: that key
156
+ * was erased with its turn's end and the server's never pays for it (runKeyEndedFor). Else, a server that holds no
157
+ * gateway key (the runner's environment or Settings → Model keys) has none to spend (noServerKeyWords). Undefined where
158
+ * it runs. */
155
159
  export declare function claimSpendOff(deps: ClaimSecretsDeps, runKey: ClaimModelKey | undefined): Promise<(what: string) => string | undefined>;
160
+ /** Whether the claim holds the run's own model key now: the learning work it starts then spends on that key, out of what
161
+ * the run's cap leaves (learning-work.ts). Read when that work starts, never cached. */
162
+ export declare const keyedNow: (runKey: ClaimModelKey | undefined) => (() => boolean);
156
163
  /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
157
164
  * the runner's environment with the keys `opened` for it, each name from the first source that holds it (withModelKeys),
158
165
  * whose gateway variables read the run's key once a message hands it one (withRunModelKeyLater). */
@@ -6,9 +6,10 @@
6
6
  // providers they name, read once the claim's seed lay chose them (learnedDecisionKeys). So a run that names no monid never gets the monid key, and two runs on
7
7
  // one runner never see each other's keys: each claim reads its own, into its own environment. (MCP credentials are the
8
8
  // other per-claim secret; they come through mcp-claim.ts, which already opens them from the store under the claim.)
9
- import { decisionKeysFor, JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV, providersNamed } from "../decisions.js";
9
+ import { decisionKeysFor, JEV_GATEWAY_KEY_ENV, JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV, providersNamed } from "../decisions.js";
10
10
  import { FAUX_ENV, FAUX_PROVIDER, GATEWAY_KEY_ENV, hostModel, modelKeys, PROVIDER_KEYS, tierModelOf, TIERS, workflowNodes } from "../model.js";
11
11
  import { keysFor, needsOf, RUN_SECRETS } from "../run-secrets.js";
12
+ import { BUILTIN_OWN_KEYS } from "../harness-table.js";
12
13
  import { DECISION_KEYS, withoutSecrets } from "../secrets.js";
13
14
  import { getSealedKey } from "../server-keys.js";
14
15
  import { PLAN_PROVIDER, planOf, planReaderOf, withPlan } from "../chatgpt-plan.js";
@@ -32,23 +33,29 @@ const CANDIDATES = [...new Set([...RUN_SECRETS, ...DECISION_KEYS])];
32
33
  * redactor, which the run's own tool keys are carried into before they are laid, so its journal is cut of them as it is
33
34
  * written (no one holds them after the turn); a plain JS caller that passes none lays no run key, and throws. A run whose
34
35
  * model sends no key (sendsNoModelKey: a held run its model kept from running, any run on a --faux runner, a faux-pinned
35
- * one) is laid no model key and no plan sign-in. Its tools' keys, its decision keys and its own tool keys are laid as any run's. The one tool key row that names
36
+ * one) is laid no model key and no plan sign-in. A held run its model kept from running at its create (hold.refused) is
37
+ * laid no built-in harness's own key either (harness-table.ts BUILTIN_OWN_KEYS: Cursor's): its agent never starts. Its
38
+ * tools' keys, its decision keys and its own tool keys are laid as any run's. The one tool key row that names
36
39
  * a model key's name, TypeSafe's (key-words.ts; model.ts PROVIDER_KEYS typesafe), is a decision key (secrets.ts
37
40
  * DECISION_KEYS): keysFor never names one, so the model key filter below never sees it, and decisionKeysFor lays it
38
41
  * apart, as it lays OpenRouter's for a decision node that runs on it. */
39
42
  export async function claimSecrets(deps, revision, launch, runId) {
40
43
  const base = withoutSecrets(deps.env ?? {});
41
44
  const needs = await needsOf(revision);
45
+ const keyless = sendsNoModelKey(launch, deps.env ?? {});
42
46
  const modelRefused = launch.hold?.refused !== undefined;
43
- // A held run its model kept from running lays no model key, so its claim opens none: a key it never lays is never
44
- // decrypted. OpenRouter's is read still for a run whose decision nodes may run on it (decisionKeysFor), as a decision key.
45
- const unread = modelRefused ? MODEL_KEY_NAMES.filter((name) => !(name === JEV_OPENROUTER_KEY_ENV && needs.decisionProviders.length > 0)) : [];
47
+ // A run that sends no model key (sendsNoModelKey) lays none, so its claim opens none: a key it never lays is never
48
+ // decrypted. A run with decision nodes still reads each name its decision keys come from (DECISION_KEY_SOURCES: Jev's
49
+ // TypeSafe key, OpenRouter's, an OpenRouter gateway's), which decisionKeysFor lays as decision keys alone; the model key
50
+ // filter below lays none of them as a model key. Parallel's is no model key's name, so it is never left unread. A held
51
+ // run its model kept from running (hold.refused) lays no built-in harness's own key either (its agent never starts), so
52
+ // it opens none of those.
53
+ const unread = [...(keyless ? MODEL_KEY_NAMES.filter((name) => !(needs.decisionProviders.length > 0 && DECISION_KEY_SOURCES.has(name))) : []), ...(modelRefused ? BUILTIN_OWN_KEYS : [])];
46
54
  const working = await workingEnv(deps, unread);
47
55
  // An agentic run's model keys are its PINNED model's (the launch's, chosen at its start), the one its route sends, never
48
56
  // the host's default now: a key saved since the run started (another provider's, now first) would otherwise be opened
49
57
  // in its place, and the run would hold a key its model never sends and lack the one it does.
50
58
  const scoped = launch.model && !needs.tiers ? { ...needs, model: `${launch.model.provider}/${launch.model.modelId}` } : needs;
51
- const keyless = sendsNoModelKey(launch, deps.env ?? {});
52
59
  const env = { ...base };
53
60
  // The key of a gateway saved in the console (model-gateway.ts) stays on the run environment its model routes read, never
54
61
  // on the tools': it is read there by name alone (claimModelEnv), as a run's own model key is.
@@ -56,7 +63,7 @@ export async function claimSecrets(deps, revision, launch, runId) {
56
63
  // A model key is never enumerable, as withModelKeys lays a route's, but unlike a route's it stays writable and deletable
57
64
  // (withoutModelKeys drops it); a tool key is a plain value, which its tools read and hand on.
58
65
  for (const name of keysFor(scoped, working))
59
- if (working[name] !== undefined && !(savedGateway && name === GATEWAY_KEY_ENV) && !(keyless && MODEL_KEY_NAMES.includes(name)))
66
+ if (working[name] !== undefined && !(savedGateway && name === GATEWAY_KEY_ENV) && !(keyless && MODEL_KEY_NAMES.includes(name)) && !(modelRefused && BUILTIN_OWN_KEYS.includes(name)))
60
67
  Object.defineProperty(env, name, { value: working[name], enumerable: !MODEL_KEY_NAMES.includes(name), writable: true, configurable: true });
61
68
  // TypeSafe's key is a model key: a run whose model sends none (keyless) is not handed it for Jev's web ranking either,
62
69
  // and its web tools answer unranked.
@@ -356,16 +363,21 @@ export async function serverKeyless(deps) {
356
363
  return runModelOrigin(deps.env ?? {}) !== undefined && !(await savedModelKeys(deps))[GATEWAY_KEY_ENV];
357
364
  }
358
365
  /** Why the claim's model spend after the run's turn, or beside it on runs the runner starts (a shadow audit, a replay
359
- * check), is skipped: `what` the work, asked when that spend would start. A run that brought
360
- * its own key, at its start or with a message since (everHeld): that key is erased with its turn's end and the server's
361
- * never pays for it (runKeyEndedFor). Else, a server that holds no gateway key (the runner's environment or
362
- * Settings → Model keys) has none to spend (noServerKeyWords). Undefined where it runs. */
366
+ * check), is skipped: `what` the work, asked when that spend would start. A claim that holds the run's own key now runs
367
+ * it on that key (the runs it starts take a sealed copy of it, store/seal.ts sealHandedLaunch), whatever the server
368
+ * holds. A run that brought its own key, at its start or with a message since (everHeld), and holds none now: that key
369
+ * was erased with its turn's end and the server's never pays for it (runKeyEndedFor). Else, a server that holds no
370
+ * gateway key (the runner's environment or Settings → Model keys) has none to spend (noServerKeyWords). Undefined where
371
+ * it runs. */
363
372
  export async function claimSpendOff(deps, runKey) {
364
373
  // A run's own process holds no seal key, nor every saved key: its runner says whether the server holds a gateway key.
365
374
  const at = deps.sealKey ? undefined : held();
366
375
  const keyless = at ? await at.serverKeyless() : await serverKeyless(deps);
367
- return (what) => (runKey?.everHeld() ? runKeyEndedFor(what) : keyless ? noServerKeyWords(what) : undefined);
376
+ return (what) => (runKey?.key() !== undefined ? undefined : runKey?.everHeld() ? runKeyEndedFor(what) : keyless ? noServerKeyWords(what) : undefined);
368
377
  }
378
+ /** Whether the claim holds the run's own model key now: the learning work it starts then spends on that key, out of what
379
+ * the run's cap leaves (learning-work.ts). Read when that work starts, never cached. */
380
+ export const keyedNow = (runKey) => () => runKey?.key() !== undefined;
369
381
  /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
370
382
  * the runner's environment with the keys `opened` for it, each name from the first source that holds it (withModelKeys),
371
383
  * whose gateway variables read the run's key once a message hands it one (withRunModelKeyLater). */
@@ -378,6 +390,10 @@ export function claimModelEnv(env, opened, runKey, claim) {
378
390
  /** The decision providers' own keys (decisions.ts: Jev's TypeSafe key, OpenRouter's, Parallel's): some are also pi-ai
379
391
  * provider names, but a run's model key never replaces them, so withoutModelKeys keeps them. */
380
392
  const DECISION_KEY_NAMES = new Set([JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV]);
393
+ /** Every name a decision key is read from (decisions.ts decisionKeysOf): the decision keys' own names, and an OpenRouter
394
+ * gateway's key (JEV_GATEWAY_KEY_ENV), which Jev and OpenRouter's Decisions models run on when no key of their own is
395
+ * set. A claim that opens no model key still opens these for a run with decision nodes (claimSecrets). */
396
+ const DECISION_KEY_SOURCES = new Set([...DECISION_KEY_NAMES, JEV_GATEWAY_KEY_ENV]);
381
397
  /** `toolEnv` with no model key in it, for a run that holds its own: a tool's environment never carries a model key the
382
398
  * run's model routes do not send. The decision providers' keys stay (DECISION_KEY_NAMES): a keyed workflow's judge,
383
399
  * pick, sift, route and ask nodes run on them as any run's do. */
@@ -13,8 +13,6 @@ export type { ClaimComputer, ClaimDeps, ClaimLaunch, ComputerForClaim } from "./
13
13
  /** What the runner hands the CLI spec builder: the same deps the pi spec takes (computerForClaim, computerDeps and
14
14
  * makeArchilDisk are on AdapterSpecDeps, shared by both). One per runner. */
15
15
  export type CliSpecDeps = AdapterSpecDeps;
16
- /** What a CLI harness refuses of an agent's computer, in words: a browser, which only pi's browser tool drives. */
17
- export declare const cliRefusesKind: (kind: string) => string | undefined;
18
16
  /** A harness's facts for a run on `model`: on a model the route translates onto its wire (an Ollama model), its own tool
19
17
  * search is not its (AdapterFacts.ownToolSearch dropped): what it sends (deferred tools, a tool search's references) is
20
18
  * the provider's to read, and the translation's model has none. The host's own tools_search and tools_call are offered