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

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 (110) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +84 -14
  3. package/dist/acp-package.d.ts +24 -6
  4. package/dist/adapter-facts.d.ts +0 -4
  5. package/dist/adapter-facts.js +1 -4
  6. package/dist/adapters.d.ts +3 -12
  7. package/dist/adapters.js +1 -70
  8. package/dist/answer-json.d.ts +10 -0
  9. package/dist/answer-json.js +24 -0
  10. package/dist/api-only.d.ts +5 -2
  11. package/dist/api-only.js +10 -2
  12. package/dist/browser-live.d.ts +9 -4
  13. package/dist/browser-live.js +18 -5
  14. package/dist/cap.js +7 -9
  15. package/dist/cli.js +6 -6
  16. package/dist/computer-routes.d.ts +8 -5
  17. package/dist/computer-routes.js +7 -5
  18. package/dist/computers.d.ts +6 -2
  19. package/dist/computers.js +4 -2
  20. package/dist/conformance.d.ts +4 -0
  21. package/dist/conformance.js +6 -0
  22. package/dist/console/assets/index-CTGegcKt.css +1 -0
  23. package/dist/console/assets/{index-BBFzAxLB.js → index-D1Se6mgG.js} +165 -165
  24. package/dist/console/index.html +2 -2
  25. package/dist/harness-check.d.ts +3 -1
  26. package/dist/harness-check.js +99 -70
  27. package/dist/harness-cursor.d.ts +10 -27
  28. package/dist/harness-cursor.js +5 -84
  29. package/dist/harness-goose.d.ts +4 -29
  30. package/dist/harness-goose.js +6 -86
  31. package/dist/harness-module.d.ts +4 -0
  32. package/dist/harness-module.js +1 -0
  33. package/dist/harness-owned.d.ts +52 -0
  34. package/dist/harness-owned.js +92 -0
  35. package/dist/harness-recipe.js +2 -24
  36. package/dist/harness-table.d.ts +109 -6
  37. package/dist/harness-table.js +242 -28
  38. package/dist/harness.js +2 -2
  39. package/dist/key-refusal.d.ts +2 -1
  40. package/dist/key-refusal.js +18 -2
  41. package/dist/learn/promote.d.ts +11 -0
  42. package/dist/learn/secrets.d.ts +4 -0
  43. package/dist/learn/secrets.js +23 -0
  44. package/dist/learning-model.d.ts +18 -0
  45. package/dist/learning-model.js +77 -0
  46. package/dist/llms.txt +1 -0
  47. package/dist/model-form.js +12 -12
  48. package/dist/model.d.ts +5 -4
  49. package/dist/model.js +19 -13
  50. package/dist/openapi.js +35 -5
  51. package/dist/page.d.ts +1 -0
  52. package/dist/page.js +1 -1
  53. package/dist/run-secrets.d.ts +2 -2
  54. package/dist/run-secrets.js +6 -5
  55. package/dist/run-trace.js +6 -3
  56. package/dist/runner/adapter-loop.d.ts +4 -1
  57. package/dist/runner/adapter-loop.js +1 -2
  58. package/dist/runner/adapter-run-spec.d.ts +3 -2
  59. package/dist/runner/adapter-run-spec.js +8 -4
  60. package/dist/runner/adapters/index.d.ts +4 -2
  61. package/dist/runner/adapters/index.js +6 -42
  62. package/dist/runner/cli-run-spec.js +10 -6
  63. package/dist/runner/conformance/host-tools.d.ts +4 -0
  64. package/dist/runner/conformance/host-tools.js +14 -0
  65. package/dist/runner/meta-tools.js +4 -2
  66. package/dist/runner/presence.d.ts +3 -0
  67. package/dist/runner/presence.js +19 -12
  68. package/dist/runner/promotion.d.ts +62 -4
  69. package/dist/runner/promotion.js +146 -15
  70. package/dist/runner/sdk-loop.js +25 -1
  71. package/dist/runner/workflow-spec.js +3 -2
  72. package/dist/runs-over-store.d.ts +2 -1
  73. package/dist/runs-over-store.js +2 -4
  74. package/dist/sdk/check.d.ts +31 -0
  75. package/dist/sdk/check.js +58 -0
  76. package/dist/sdk/runs.d.ts +10 -2
  77. package/dist/sdk/runs.js +87 -17
  78. package/dist/sdk/schema.js +11 -3
  79. package/dist/server.d.ts +3 -0
  80. package/dist/server.js +116 -40
  81. package/dist/store/sqlite/store.js +35 -30
  82. package/dist/store/store.d.ts +20 -18
  83. package/dist/store-view.d.ts +5 -3
  84. package/dist/store-view.js +9 -7
  85. package/dist/template-eval.js +5 -2
  86. package/dist/template-github-permissions.d.ts +5 -1
  87. package/dist/template-github-permissions.js +7 -3
  88. package/dist/timeline/index.d.ts +1 -1
  89. package/dist/timeline/index.js +1 -1
  90. package/dist/timeline/timeline.d.ts +8 -0
  91. package/dist/timeline/timeline.js +18 -6
  92. package/dist/tool-gate.d.ts +8 -4
  93. package/dist/tool-gate.js +6 -7
  94. package/dist/tool-plane.d.ts +4 -0
  95. package/dist/tool-plane.js +10 -10
  96. package/dist/trigger-targets.d.ts +11 -2
  97. package/dist/trigger-targets.js +71 -2
  98. package/dist/validate.js +5 -1
  99. package/dist/viewer-credential.d.ts +25 -0
  100. package/dist/viewer-credential.js +51 -0
  101. package/dist/workspace/resolve-computer.d.ts +5 -0
  102. package/dist/workspace/resolve-computer.js +19 -1
  103. package/package.json +18 -10
  104. package/templates/code-review/agent.md +2 -3
  105. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  106. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  107. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  108. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  109. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  110. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
package/dist/server.js CHANGED
@@ -1,9 +1,7 @@
1
1
  import { maintainObservations, Observations } from './observation/observer.js';
2
2
  import { isObservationRoute, observationHttp } from './observation/http.js';
3
3
  import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
4
- import { askRouteOf } from "./runner/sdk-ask.js";
5
- import { PI_WIRES } from "./runner/adapter-run-spec.js";
6
- import { routeOf as sdkModelRoute } from "./runner/model-route.js";
4
+ import { learningModelOf } from "./learning-model.js";
7
5
  import { answerSkill } from './skill-route.js';
8
6
  import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
9
7
  import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
@@ -18,6 +16,7 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from
18
16
  import { createServer } from "node:http";
19
17
  import proxyaddr from "proxy-addr";
20
18
  import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
19
+ import { carriedFields } from "./answer-json.js";
21
20
  import { dirname, join, relative, resolve, sep } from "node:path";
22
21
  import { pathToFileURL } from "node:url";
23
22
  import { Worker } from "node:worker_threads";
@@ -173,6 +172,8 @@ import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
173
172
  import { recordingsFolder } from "./workspace/paths.js";
174
173
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
175
174
  import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
175
+ import { runOver } from "./computer-commands.js";
176
+ import { mintViewerCredential, VIEWER_PARAM, viewerCookie, viewerCredentialFor, viewerCredentialKey, viewerCredentialOf, viewerExpiry } from "./viewer-credential.js";
176
177
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
177
178
  import { createAttachRoutes, liveRelays, pairedView } from "./computer-attach.js";
178
179
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
@@ -336,6 +337,8 @@ export const ROUTES = [
336
337
  // store-backed take-over lands). The run routes stay together.
337
338
  { method: "GET", pattern: /^\/runs\/([^/]+)\/computer$/, name: "getRunComputer" },
338
339
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/take-over$/, name: "takeOverRunComputer" },
340
+ // An API-only server's viewer credential for a run's live view (viewer-credential.ts), minted for its backend.
341
+ { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/viewer$/, name: "createRunComputerViewer" },
339
342
  { method: "POST", pattern: /^\/runs\/([^/]+)\/computer\/hand-back$/, name: "handBackRunComputer" },
340
343
  // A held computer's (computer-held-routes.ts): a run started with hold: true waits for its start, takes its owner's
341
344
  // protocol calls, and keeps its computer after its agent's end until released.
@@ -560,9 +563,10 @@ async function planStep(step) {
560
563
  }
561
564
  async function needsOf(env) {
562
565
  const chosen = await chooseModel(env, undefined);
566
+ const learning_model = await learningModelOf(env);
563
567
  if ("why" in chosen)
564
- return { needs: chosen.needs, priced: null };
565
- return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0 };
568
+ return { needs: chosen.needs, priced: null, learning_model };
569
+ return { needs: null, priced: (await unpricedModels(env, undefined)).length === 0, learning_model };
566
570
  }
567
571
  /** The server's reading of `base`, whole: its secrets, saved keys among them (`env`), the harnesses' offers, probed from
568
572
  * env without the tool keys (offersEnvOf), and its capabilities made from both under its learning switch (`learning`,
@@ -598,7 +602,7 @@ export function forCaller(caps, ownerSession) {
598
602
  * needsOf says it for a revision that names no model (null when it runs). `runnerShell`: the sandbox-only tools a run
599
603
  * on the runner has a shell for here (tools.ts shellTools; bash in Mode 2), available with no box. `switched`: the two
600
604
  * start-time switches the server takes as options (switchedOnBy reads them from `env`, as the CLI sets them). */
601
- function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
605
+ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, learning_model }, toolSettings, boxes, refused = {}, runnerShell, isolation = "process", switched = switchedOnBy(env)) {
602
606
  const models = { ...modelSource(env), ready: needs === null, needs, priced };
603
607
  // Both limits apply: the cap on the count, and the memory each run reserves (host.ts).
604
608
  const memory = hostMemory();
@@ -621,6 +625,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
621
625
  /** The places a revision may name (`definition.place`), this host's default, and whether this server has each box. */
622
626
  places: placesOf(boxes, boxAllowOf(env)),
623
627
  models,
628
+ learning_model,
624
629
  /** `pending`: a workflow draft with a call no price covers is kept to wait for its owner's OK, served to no run;
625
630
  * `approve`: whether the caller can approve one, which takes the owner's password session (forCaller), and
626
631
  * `approve_needs` when not. */
@@ -1139,6 +1144,12 @@ async function startHolding(options, data, checked, stops) {
1139
1144
  const sealKey = seal.key;
1140
1145
  // SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
1141
1146
  const sdkSecret = sdkRunSecret(sealKey);
1147
+ // An API-only server's viewer credentials (viewer-credential.ts) are signed with another key from it: every server on
1148
+ // this store checks them alike, across restarts.
1149
+ const viewerKey = viewerCredentialKey(sealKey);
1150
+ /** Whether `credential` opens run `runId`'s live view now: minted for that run, not expired, and its run not ended,
1151
+ * read from the store each time (its revocation). */
1152
+ const viewerHolds = async (credential, runId) => credential !== undefined && viewerCredentialFor(viewerKey, runId, credential, Date.now()) && !(await runOver(store, runId));
1142
1153
  // Each run's viewers are asked under that run's key (live-reach.ts reachForRun).
1143
1154
  const answers = (runId) => (handover) => viewerAnswers(handover, reachForRun(reach, runId));
1144
1155
  // Settings → Computers and the owner's Archil settings, over the one store (computers.ts, archil-routes.ts), built once
@@ -1581,7 +1592,10 @@ async function startHolding(options, data, checked, stops) {
1581
1592
  const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
1582
1593
  if (view?.status !== "completed")
1583
1594
  return undefined;
1584
- return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null };
1595
+ // The fields its next run is handed when the whole result is too large: its own revision's output schema's, the one
1596
+ // its result.output was checked against (store-view.ts), never the agent's current one.
1597
+ const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
1598
+ return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
1585
1599
  },
1586
1600
  };
1587
1601
  const targets = triggerTargets(store, triggerDeps);
@@ -3932,14 +3946,15 @@ async function startHolding(options, data, checked, stops) {
3932
3946
  throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
3933
3947
  }
3934
3948
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
3935
- // approving a note is (never a token a run, an MCP client or a script may hold).
3936
- if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3949
+ // approving a note is (never a token a run, an MCP client or a script may hold). An API-only server has no owner: there
3950
+ // the server's token, its backend's own, takes a run's computer, checked below as every route's token is.
3951
+ if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || (found.name === "getRunComputer" && !options.apiOnly)) && !byOwnerSession(req) && req.headers.authorization !== undefined) {
3937
3952
  const what = found.name.endsWith("Browser") ? "browser" : "computer";
3938
3953
  authFailed(`/v2${path}`, `${what}_without_session`);
3939
3954
  throw new ApiError("forbidden", owner ? `A run's live ${what} takes the owner's password sign-in in the console, never a token.` : `A run's live ${what} takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).`);
3940
3955
  }
3941
3956
  // A run's desktop or phone view drives it once taken over: the owner's signed-in page alone (computer-routes.ts decides).
3942
- if (COMPUTER_ROUTES.has(found.name) && !byOwnerSession(req) && req.headers.authorization !== undefined)
3957
+ if (COMPUTER_ROUTES.has(found.name) && !options.apiOnly && !byOwnerSession(req) && req.headers.authorization !== undefined)
3943
3958
  authFailed(`/v2${path}`, "computer_without_session");
3944
3959
  // Answering a tool call that waits for approval (tool-gate.ts) is the same: the owner's signed-in page alone, never a
3945
3960
  // token, which the run's own process, an agent's MCP client or a script may hold.
@@ -4033,22 +4048,16 @@ async function startHolding(options, data, checked, stops) {
4033
4048
  // A learning SDK run's compile turn is asked on its agent's own model: checked reachable before the run starts.
4034
4049
  let compileModel;
4035
4050
  if (sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
4036
- try {
4037
- const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
4038
- if (chosen)
4039
- compileModel = `${chosen.provider}/${chosen.modelId}`;
4040
- }
4041
- catch { }
4051
+ const configured = await learningModelOf(env, (await pinnedOf(entry, {})).revision);
4052
+ compileModel = configured.model ?? undefined;
4042
4053
  }
4043
4054
  const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
4044
- const compile = { ...(compileModel ? { model: compileModel } : {}), check: async (model) => {
4045
- try {
4046
- const route = await askRouteOf(model, env, (one) => sdkModelRoute(one, env, "default", PI_WIRES));
4047
- await route.provider.credential();
4048
- }
4049
- catch {
4050
- throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key to compile workflows. Configure Model keys or turn self-improving off.");
4051
- }
4055
+ const compile = { ...(compileModel ? { model: compileModel } : {}), check: async () => {
4056
+ // SdkRuns checks this only after its durable origin lookup, so a successful admission remains recoverable
4057
+ // when the owner has since changed its model or removed its key.
4058
+ const configured = await learningModelOf(env, entry.revision, { checkCredential: true });
4059
+ if (!configured.ready)
4060
+ throw new ApiError("agent_not_runnable", configured.reason ?? "Configure a server learning model in Settings → API Keys.");
4052
4061
  } };
4053
4062
  const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, startDeps, origin, compile, linkOrigin(req)) }));
4054
4063
  // Re-read the pinned receipt even on an in-memory replay: credentials saved since
@@ -4467,10 +4476,33 @@ async function startHolding(options, data, checked, stops) {
4467
4476
  // hand-back is the browser's own answer row, as POST .../browser/hand-back writes it.
4468
4477
  const run = await needRun(id);
4469
4478
  const answer = await computerRoute(found.name, run.id, {
4470
- ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, accounts: owner !== undefined, body: await bodyOf(req),
4479
+ ownerSession: byOwnerSession(req), token: req.headers.authorization !== undefined, apiOnly: options.apiOnly === true, accounts: owner !== undefined, body: await bodyOf(req),
4471
4480
  }, store, { context: ctx });
4472
4481
  return send(res, 200, answer, { "cache-control": "no-store" });
4473
4482
  }
4483
+ case "createRunComputerViewer": {
4484
+ // A viewer credential for the run's live view (viewer-credential.ts), for an API-only server's backend to hand its
4485
+ // user: a link on the public address to the run's open viewer, the credential in its query, the viewer's own token
4486
+ // in its fragment. A server with no backend in between has an owner who opens the view in the console: not here.
4487
+ if (!options.apiOnly)
4488
+ throw new ApiError("not_found", "A run's viewer link is minted on an API-only server alone (AGENTRUN_API_ONLY=1): here its owner opens the live view in the console.");
4489
+ const run = await needRun(id);
4490
+ const body = await bodyOf(req);
4491
+ const issues = unknownFields(body, []);
4492
+ if (issues.length)
4493
+ throw invalid(issues);
4494
+ if (!options.publicUrl)
4495
+ throw new ApiError("unsupported_here", "A run's viewer link is on this server's public address, and AGENTRUN_PUBLIC_URL is unset: set it to the address your users' browsers open this server at.");
4496
+ if (await runOver(store, run.id))
4497
+ throw new ApiError("computer_not_live", "This run has ended: its computer has no live view.");
4498
+ const link = await computerViewerLink(store, sealKey, run.id, answers(run.id));
4499
+ if (link === undefined)
4500
+ throw new ApiError("computer_not_live", "This run's computer has no live view open now: ask again once GET /v2/runs/{run_id}/computer reads live.");
4501
+ const { credential, expiresAt } = mintViewerCredential(viewerKey, run.id, Date.now());
4502
+ const [path, fragment] = link.viewer.split("#");
4503
+ const minted = `${options.publicUrl.replace(/\/+$/, "")}${path}?${VIEWER_PARAM}=${credential}${fragment === undefined ? "" : `#${fragment}`}`;
4504
+ return send(res, 201, { url: minted, expires_at: new Date(expiresAt).toISOString() }, { "cache-control": "no-store" });
4505
+ }
4474
4506
  case "startRun":
4475
4507
  case "callRunComputer":
4476
4508
  case "releaseRunComputer": {
@@ -4915,7 +4947,7 @@ async function startHolding(options, data, checked, stops) {
4915
4947
  // they are now and of the agent's own sign-in pointers, live and forgotten (agentPointers); a write as the
4916
4948
  // definition's: an archived agent's too.
4917
4949
  case "getAgentLearning": {
4918
- await needAgent(id);
4950
+ const entry = await needAgent(id);
4919
4951
  // The agent's learning view: its corrections, workflows and log from its learning folder; its run-fared counts and
4920
4952
  // its impact over the one store (agentLearningOverStore), from each run's launch, journal and learning end.
4921
4953
  const { counts, impact } = await agentLearningOverStore(store, id);
@@ -4924,7 +4956,9 @@ async function startHolding(options, data, checked, stops) {
4924
4956
  // that does not run first.
4925
4957
  const records = await promotionsOf(store.settings, id);
4926
4958
  const costStop = await costStopOverStore(store, id);
4927
- return send(res, 200, await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)));
4959
+ const body = entry.revision?.body;
4960
+ const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
4961
+ return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)), learning_model: await learningModelOf(modelEnv, entry.revision) });
4928
4962
  }
4929
4963
  case "getLearningCost": {
4930
4964
  await needAgent(id);
@@ -5236,6 +5270,30 @@ async function startHolding(options, data, checked, stops) {
5236
5270
  async function liveRoute(req, res, runId, family, rest) {
5237
5271
  if (req.method !== "GET" && req.method !== "HEAD")
5238
5272
  throw new ApiError("method_not_allowed", `${req.method} is not a method of a run's live view`, {}, { allow: "GET, HEAD" });
5273
+ if (options.apiOnly) {
5274
+ // API-only: no owner here. The viewer credential its backend minted for this run (viewer-credential.ts), on the
5275
+ // public address alone: a navigation sends no Origin, any other request this page's own. The page's answer sets it as
5276
+ // the cookie its files and socket carry.
5277
+ const sent = req.headers.origin;
5278
+ if (sent !== undefined && sent.toLowerCase() !== publicOrigin) {
5279
+ authFailed(`/v2/runs/${runId}/${family}/live`, "live_view_origin");
5280
+ throw new ApiError("forbidden", "a run's live view here is opened on this server's public address (AGENTRUN_PUBLIC_URL) alone");
5281
+ }
5282
+ const credential = viewerCredentialOf(req);
5283
+ if (credential === undefined) {
5284
+ authFailed(`/v2/runs/${runId}/${family}/live`, "no_credential");
5285
+ throw new ApiError("unauthenticated", "a run's live view here takes the viewer link its backend minted (POST /v2/runs/{run_id}/computer/viewer)");
5286
+ }
5287
+ if (!(await viewerHolds(credential, runId))) {
5288
+ authFailed(`/v2/runs/${runId}/${family}/live`, "viewer_credential");
5289
+ throw new ApiError("forbidden", "this viewer link is expired, for another run, or its run has ended: ask for a new one");
5290
+ }
5291
+ const handover = await liveViewerFor(store, sealKey, runId, rest);
5292
+ if (handover === undefined)
5293
+ throw new ApiError("not_found", `this run's ${family} has no live view at that address`);
5294
+ res.setHeader("set-cookie", viewerCookie(req, runId, credential, viewerExpiry(credential), Date.now()));
5295
+ return serveViewerFile(req, res, rest, (handover.kind ?? "browser") === "browser" ? "browser" : "computer");
5296
+ }
5239
5297
  if (!byOwnerSession(req)) {
5240
5298
  authFailed(`/v2/runs/${runId}/${family}/live`, req.headers.authorization === undefined ? "no_credential" : `${family}_without_session`);
5241
5299
  throw req.headers.authorization === undefined ? new ApiError("unauthenticated", `a run's live ${family} view takes the owner's password sign-in in the console`) : new ApiError("forbidden", `a run's live ${family} view takes the owner's password sign-in in the console, never a token`);
@@ -5365,9 +5423,10 @@ async function startHolding(options, data, checked, stops) {
5365
5423
  // away. Its name alone, on any port, as the HTTP routes check it.
5366
5424
  if (names && !names.has(hostName(req.headers.host) ?? ""))
5367
5425
  return deny("403 Forbidden");
5368
- // API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
5369
- // the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
5370
- if (options.apiOnly && raw !== ATTACH_PATH)
5426
+ // API-only: paired computers are the console's (Settings), and refused with it, whose tokens the attach socket takes as
5427
+ // unknown there (machinesOnly). A run's hosted machine that dials still reaches it, and a run's computer live view takes
5428
+ // its viewer credential (below); a browser's live view stays the console's.
5429
+ if (options.apiOnly && raw !== ATTACH_PATH && viewing?.[2] !== "computer")
5371
5430
  return deny("404 Not Found");
5372
5431
  // A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
5373
5432
  // owner's, lets it in.
@@ -5383,15 +5442,27 @@ async function startHolding(options, data, checked, stops) {
5383
5442
  return deny("404 Not Found");
5384
5443
  // A browser always sends its page's origin on a WebSocket, which no other page's script can forge: this server's own
5385
5444
  // (as this request reaches it, or its public address, which a TLS proxy that rewrites Host or drops
5386
- // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing.
5445
+ // X-Forwarded-Proto leaves as the only one the owner's page has), and the owner signed in, or nothing. API-only: the
5446
+ // public address alone, where the minted link opens the page, and the viewer credential for this run (its cookie).
5387
5447
  const sent = String(req.headers.origin ?? "").toLowerCase();
5388
- if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5389
- return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5390
- if (!owner || !signedIn(req, owner))
5391
- return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5448
+ const credential = options.apiOnly ? viewerCredentialOf(req) : undefined;
5449
+ if (options.apiOnly) {
5450
+ if (sent === "" || sent !== publicOrigin)
5451
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5452
+ if (credential === undefined)
5453
+ return (authFailed(raw, "no_credential"), deny("401 Unauthorized"));
5454
+ }
5455
+ else {
5456
+ if (sent === "" || (sent !== ownOrigin(req) && sent !== publicOrigin))
5457
+ return (authFailed(raw, "live_view_origin"), deny("403 Forbidden"));
5458
+ if (!owner || !signedIn(req, owner))
5459
+ return (authFailed(raw, "live_view_without_session"), deny("401 Unauthorized"));
5460
+ }
5392
5461
  // Once the run's WebSocket is piped to this socket, a failure here only ends it: an HTTP line would land mid-stream.
5393
5462
  let piping = false;
5394
5463
  void (async () => {
5464
+ if (options.apiOnly && !(await viewerHolds(credential, viewing[1])))
5465
+ return (authFailed(raw, "viewer_credential"), deny("403 Forbidden"));
5395
5466
  const run = ID.test(viewing[1]) ? await momentOverStore(store, viewing[1], viewDepsFor(ownOriginOf())) : undefined;
5396
5467
  // The run's live viewer from the store (the runner's browser/computer tool wrote it under its claim): none for a run no
5397
5468
  // runner holds. A /computer/live socket reaches a viewer of every kind, a
@@ -5404,11 +5475,16 @@ async function startHolding(options, data, checked, stops) {
5404
5475
  if (socket.destroyed || closing)
5405
5476
  return void socket.destroy();
5406
5477
  // Checked again after the lookup, then for as long as the socket is open: the sessions that let it in, and no other.
5407
- const held = heldSessions(req);
5408
- const admitted = () => held.some((value) => owner.valid(value));
5409
- if (!admitted())
5410
- return deny("401 Unauthorized");
5411
- viewers.watch(socket, admitted);
5478
+ // API-only: the credential's run not ended, read from the store (its revocation); its expiry bounds the opening alone.
5479
+ if (options.apiOnly)
5480
+ viewers.watch(socket, async () => !(await runOver(store, run.id)));
5481
+ else {
5482
+ const held = heldSessions(req);
5483
+ const admitted = () => held.some((value) => owner.valid(value));
5484
+ if (!admitted())
5485
+ return deny("401 Unauthorized");
5486
+ viewers.watch(socket, admitted);
5487
+ }
5412
5488
  proxyLiveUpgrade(req, socket, head, handover, viewing[3], () => { piping = true; }, reachForRun(reach, run.id));
5413
5489
  })().catch(() => (piping ? void socket.destroy() : deny("500 Internal Server Error")));
5414
5490
  };
@@ -11,7 +11,8 @@ import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } fro
11
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { RunStorage } from "../journal/storage.js";
14
- import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
14
+ import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
+ import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
15
16
  import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, } from "../store.js";
16
17
  /** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
17
18
  const seqOf = (cursor) => {
@@ -72,6 +73,9 @@ const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, pac
72
73
  const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
73
74
  const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
74
75
  const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
76
+ /** An ended run, not imported, whose stored cost is unknown: null with no bound beside it (cost_upper_bound 0, never NULL).
77
+ * What Runs.healCost writes over and Runs.costUnknown lists. */
78
+ const COST_UNKNOWN = `cost_usd IS NULL AND cost_upper_bound = 0 AND state IN (${FINAL}) AND imported_from IS NULL AND ended_at IS NOT NULL`;
75
79
  /** Taken (Dialect.lockKey) by every insert of a run's command row, before it: the run's rows commit in id order, as
76
80
  * SQLite's one writer commits them. On Postgres an id is taken at the insert and the row is seen at its commit, so two
77
81
  * inserts at once could commit out of order, and a reader of the rows past the last id it handed on (the runner) would
@@ -1094,19 +1098,34 @@ class SqliteStore {
1094
1098
  const row = await db.get("SELECT list_mark FROM runs WHERE id = ?", runId);
1095
1099
  return row === undefined ? undefined : Number(row.list_mark);
1096
1100
  },
1097
- // A heal of an ended run's unknown cost from its priced booking: one conditional UPDATE, only null to a figure, only
1098
- // at the end it was read at (a reopen or a later end moves ended_at or the epoch), so it never overwrites a figure.
1099
- healCost: async (runId, { epoch, endedAt }, usd) => {
1100
- if (!Number.isFinite(usd) || usd < 0)
1101
- throw new TypeError(`a healed cost is a figure of $0 or more (got ${usd})`);
1101
+ // A heal of an ended run's unknown cost from its priced booking, as its end writes one (the bound beside the figure
1102
+ // with it, applyRunPatch): one conditional UPDATE, only over a null with no bound beside it (cost_upper_bound 0, the
1103
+ // column's no-bound value: it is never NULL), only at the end it was read at (a reopen or a later end moves ended_at
1104
+ // or the epoch), so it never overwrites a figure or a bound, whatever its caller read.
1105
+ healCost: async (runId, { epoch, endedAt }, { costUsd, costUpperBound }) => {
1106
+ if (!Number.isFinite(costUsd) || costUsd < 0)
1107
+ throw new TypeError(`a healed cost is a figure of $0 or more (got ${costUsd})`);
1102
1108
  const [result] = await db.write([{
1103
- sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound = 0 WHERE id = ? AND cost_usd IS NULL AND state IN (${FINAL}) AND imported_from IS NULL AND epoch = ? AND ended_at = ? RETURNING id`,
1104
- params: [usd, runId, epoch, endedAt],
1109
+ sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING id`,
1110
+ params: [costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt],
1105
1111
  }]);
1106
1112
  return (result?.rows.length ?? 0) > 0;
1107
1113
  },
1114
+ // The runs healCost may write that the heal's rule (store-view.ts bookedCostOf, healOf) does not refuse by its
1115
+ // columns alone, so the start sweep never reads one that cannot heal again at each start: left out are a person's
1116
+ // stop of an agentic run (it reads running, stoppedByPerson), an agentic run whose launch names a native connection
1117
+ // (its end reads its own cost; a launch whose `native` is no connection is one no runner could read, so it booked
1118
+ // nothing either), and a run whose journal holds no runner.turn (no request booked with an answer: no figure to heal
1119
+ // to). Kept, and read at each start while their cost stays null: runs with a booked request whose booking still
1120
+ // gives no figure (a charge of no known cost, every request given back). Telling them apart is the booking rule
1121
+ // itself (turnCostOf over each turn's data), which no column holds.
1108
1122
  costUnknown: async ({ limit, after }) => {
1109
- const rows = await db.all(`SELECT id FROM runs WHERE cost_usd IS NULL AND state IN (${FINAL}) AND imported_from IS NULL${after === undefined ? "" : " AND id > ?"} ORDER BY id LIMIT ?`, ...(after === undefined ? [] : [after]), limit);
1123
+ const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
1124
+ const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
1125
+ AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
1126
+ AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${db.dialect.jsonText("run_launch.body", ["native"])} IS NOT NULL))
1127
+ AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${db.dialect.jsonText("entry.record", ["kind"])} = ?)
1128
+ ${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
1110
1129
  return rows.map((row) => row.id);
1111
1130
  },
1112
1131
  relist: async ({ flags, agentId }) => {
@@ -1693,39 +1712,25 @@ class SqliteStore {
1693
1712
  // runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
1694
1713
  const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
1695
1714
  this.runners = {
1696
- put: async ({ runner, incarnation, refused, host = null, port = null }) => {
1715
+ put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
1697
1716
  const n = clock();
1698
- await db.write([
1699
- { sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
1700
- {
1701
- sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at`,
1702
- params: [runner, incarnation, refused, host, port, ...n.params],
1703
- },
1704
- ]);
1705
- },
1706
- putUnlessLive: async ({ runner, incarnation, refused, host = null, port = null }, staleMs) => {
1707
- const n = clock();
1708
- // The upsert's WHERE leaves a row another incarnation renewed within staleMs as it is, in the same statement: no
1709
- // read between, so a later process's put can never land between a look and this write.
1717
+ // With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
1718
+ // statement: no read between, so a later process's put can never land between a look and this write.
1719
+ const unlessLive = unlessLiveMs === undefined ? "" : ` WHERE runners.incarnation = excluded.incarnation OR runners.seen_at < excluded.seen_at - ${d.bigintParam}`;
1710
1720
  const [, result] = await db.write([
1711
1721
  { sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
1712
1722
  {
1713
- sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at WHERE runners.incarnation = excluded.incarnation OR runners.seen_at < excluded.seen_at - ${d.bigintParam}`,
1714
- params: [runner, incarnation, refused, host, port, ...n.params, staleMs],
1723
+ sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at${unlessLive}`,
1724
+ params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
1715
1725
  },
1716
1726
  ]);
1717
1727
  return (result?.changes ?? 0) === 1;
1718
1728
  },
1719
- relayAt: async (runner, incarnation, at) => {
1729
+ renew: async (runner, incarnation, at) => {
1720
1730
  const n = clock();
1721
1731
  const [result] = await db.write([{ sql: `UPDATE runners SET host = ?, port = ?, seen_at = ${n.sql} WHERE runner = ? AND incarnation = ?`, params: [at?.host ?? null, at?.port ?? null, ...n.params, runner, incarnation] }]);
1722
1732
  return (result?.changes ?? 0) === 1;
1723
1733
  },
1724
- seen: async (runner, incarnation) => {
1725
- const n = clock();
1726
- const [result] = await db.write([{ sql: `UPDATE runners SET seen_at = ${n.sql} WHERE runner = ? AND incarnation = ?`, params: [...n.params, runner, incarnation] }]);
1727
- return (result?.changes ?? 0) === 1;
1728
- },
1729
1734
  list: async () => (await db.all(`${RUNNERS_SELECT} ORDER BY runner`)).map(runnerOf),
1730
1735
  live: async (staleMs) => {
1731
1736
  const n = clock();
@@ -952,16 +952,22 @@ export interface Runs {
952
952
  flags: number;
953
953
  agentId?: string;
954
954
  }): Promise<number>;
955
- /** Writes `usd`, an exact figure its booking gives, as ended run `runId`'s stored cost, only while that cost is still
956
- * unknown (null, no bound) and the run is the end it was read at (`epoch`, `endedAt`): one conditional write, so a
955
+ /** Writes `cost`, what its booking gives by the end's own rule (metrics.ts endCostOf: a figure, the most the run can
956
+ * have cost when `costUpperBound`), as ended run `runId`'s stored cost, as its end would have, only while that cost is
957
+ * still unknown (null, no bound) and the run is the end it was read at (`epoch`, `endedAt`): one conditional write, so a
957
958
  * stored figure is never overwritten, a run reopened or ended again since keeps what its end wrote, and a second heal
958
959
  * writes nothing. True when it was written. */
959
960
  healCost(runId: string, at: {
960
961
  readonly epoch: number;
961
962
  readonly endedAt: number;
962
- }, usd: number): Promise<boolean>;
963
+ }, cost: {
964
+ readonly costUsd: number;
965
+ readonly costUpperBound: boolean;
966
+ }): Promise<boolean>;
963
967
  /** Ended runs, not imported, whose stored cost is unknown (null, no bound), by id after `after`, at most `limit`: what
964
- * the server's start sweep reads to heal (cost-heal.ts). */
968
+ * the server's start sweep reads to heal (cost-heal.ts). Left out are those the heal's rule refuses by what the store
969
+ * holds alone: a person's stop of an agentic run, a native run, a run with no booked answer (sqlite/store.ts says
970
+ * which are kept, and why). */
965
971
  costUnknown(options: {
966
972
  limit: number;
967
973
  after?: string;
@@ -1463,26 +1469,22 @@ export declare const RUNNER_ROWS_KEPT_MS: number;
1463
1469
  /** Every runner's word that it is there (runner/presence.ts). */
1464
1470
  export interface Runners {
1465
1471
  /** Keeps `row` for its runner, replacing any earlier incarnation's, seen now; rows no runner renewed for
1466
- * RUNNER_ROWS_KEPT_MS go in the same write. Its host and port go together: both absent (or null) for no relay. */
1472
+ * RUNNER_ROWS_KEPT_MS go in the same write. Its host and port go together: both absent (or null) for no relay. With
1473
+ * `unlessLiveMs`, not over another incarnation's row of the same name seen within that: a process's put again of a row
1474
+ * that went (pruned, a store restored) never takes back a later process's live one. False when such a row is there and
1475
+ * nothing was written. */
1467
1476
  put(row: Omit<RunnerRow, "seenAt" | "host" | "port"> & {
1468
1477
  readonly host?: string | null;
1469
1478
  readonly port?: number | null;
1470
- }): Promise<void>;
1471
- /** Keeps `row` for its runner unless another incarnation's row of the same name was seen within `staleMs`: a process's
1472
- * put again of a row that went (pruned, a store restored) never takes back a later process's live one. False when
1473
- * such a row is there and nothing was written. */
1474
- putUnlessLive(row: Omit<RunnerRow, "seenAt" | "host" | "port"> & {
1475
- readonly host?: string | null;
1476
- readonly port?: number | null;
1477
- }, staleMs: number): Promise<boolean>;
1478
- /** Says on the runner's row where its relay answers (`at`, or null for nowhere), seen now, while the row is still this
1479
- * incarnation's. False when it is not (or there is none), and nothing was written. */
1480
- relayAt(runner: string, incarnation: string, at: {
1479
+ }, options?: {
1480
+ readonly unlessLiveMs?: number;
1481
+ }): Promise<boolean>;
1482
+ /** Marks the runner's row seen now and says on it where its relay answers (`at`, or null for nowhere), while the row is
1483
+ * still this incarnation's. False when it is not (or there is none), and nothing was written. */
1484
+ renew(runner: string, incarnation: string, at: {
1481
1485
  readonly host: string;
1482
1486
  readonly port: number;
1483
1487
  } | null): Promise<boolean>;
1484
- /** Marks the runner's row seen now, while it is still this incarnation's. False when it is not (or there is none). */
1485
- seen(runner: string, incarnation: string): Promise<boolean>;
1486
1488
  /** Every runner's row, by name. */
1487
1489
  list(): Promise<RunnerRow[]>;
1488
1490
  /** The rows seen within `staleMs`, by name. Every row's time (a put's, a seen's) and this "now" are the deadlines'
@@ -115,12 +115,14 @@ interface StoreRun {
115
115
  /** Whether its end stored its cost unknown while this read, which reads its cost from its booking (an ended agentic run
116
116
  * not native, or workflow, not imported), found no booked request: the end could not read the booking, nor can this. */
117
117
  readonly endUnread?: boolean;
118
- /** The figure its store's unknown cost heals to (Runs.healCost), at the end it was read at: set while its stored cost is
119
- * null with no bound and its booking gives an exact figure (no hold counted in it). */
118
+ /** The cost its store's unknown one heals to (Runs.healCost), at the end it was read at: set while its stored cost is
119
+ * null with no bound and its booking gives a figure, written by the end's own rule (endCostOf: a bound when a cut
120
+ * request's hold is counted in it). */
120
121
  readonly heal?: {
121
122
  readonly epoch: number;
122
123
  readonly endedAt: number;
123
- readonly usd: number;
124
+ readonly costUsd: number;
125
+ readonly costUpperBound: boolean;
124
126
  };
125
127
  }
126
128
  /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
@@ -20,7 +20,7 @@ import { learningStartOf, seedFailed } from "./run-launch.js";
20
20
  import { momentOf, pendingOf, stoppedTurn, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costWordsOfView, freeOf, stopAsked, usersOf, withAsks, withApprovalRows, } from "./run-view.js";
21
21
  import { reflects } from "./reflect-range.js";
22
22
  import { freeCeilingMessage, overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kernel/cap";
23
- import { bookedSpend, cliModelWorked, costBasisOf, costWordsOf, planSpend, runCostOf, storedBasisOf } from "./runner/metrics.js";
23
+ import { bookedSpend, cliModelWorked, costBasisOf, costWordsOf, endCostOf, planSpend, runCostOf, storedBasisOf } from "./runner/metrics.js";
24
24
  import { journalRecords, recordOf } from "./runner/journal-reader.js";
25
25
  import { capNowOf, KINDS } from "./runner/journal-kinds.js";
26
26
  import { laidOf, pathViewOf, roundsOf, runLearningEnd, usedOnly } from "./store-reads/learning.js";
@@ -182,7 +182,7 @@ async function storeRunOf(store, runId, deps) {
182
182
  * never fails on its heal, and the next read or start sweep writes it again). */
183
183
  export async function healStoredCost(store, runId, heal) {
184
184
  try {
185
- return await store.runs.healCost(runId, heal, heal.usd);
185
+ return await store.runs.healCost(runId, heal, heal);
186
186
  }
187
187
  catch (error) {
188
188
  console.warn(`[serve] an ended run's cost read from its booking could not be stored: ${error.message}; the next read stores it`);
@@ -487,14 +487,16 @@ function bookedCostOf(row, native, entries) {
487
487
  return undefined;
488
488
  return runCostOf(entries, { unbooked: isCliRecord(entries) && cliModelWorked(entries) });
489
489
  }
490
- /** What an ended run's stored cost heals to (Runs.healCost), at the end it was read at: its booking's figure, when that
491
- * booking has a request and an exact figure (no hold counted in it) while the stored cost is null with no bound. */
490
+ /** What an ended run's stored cost heals to (Runs.healCost), at the end it was read at: what its end would have stored
491
+ * had it read its booking (endCostOf, the one rule every end writes by: its figure, a bound when a cut request's hold is
492
+ * counted in it), when that booking has a request and a figure while the stored cost is null with no bound. */
492
493
  function healOf(endCost, runRow) {
493
- if (!endCost || endCost.usd === null || endCost.atMost !== 0)
494
+ if (!endCost || endCost.usd === null)
494
495
  return undefined;
495
496
  if (runRow.costUsd !== null || runRow.costAtMostUsd !== null || runRow.endedAt === null)
496
497
  return undefined;
497
- return { epoch: runRow.epoch, endedAt: runRow.endedAt, usd: endCost.usd };
498
+ const { costUpperBound } = endCostOf(endCost);
499
+ return { epoch: runRow.epoch, endedAt: runRow.endedAt, costUsd: endCost.usd, costUpperBound };
498
500
  }
499
501
  /** The start sweep's heal of run `runId` (cost-heal.ts): the same rule as its run read's (bookedCostOf, healOf), from its
500
502
  * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning folder. True when
@@ -509,7 +511,7 @@ export async function healedOverStore(store, runId) {
509
511
  const booked = bookedCostOf(row, Boolean(launch?.native), (await journalRecords(snapshot.readJournal(runId), BACKGROUND_CONTEXT)).entries);
510
512
  return healOf(booked?.requests ? booked : undefined, runRow);
511
513
  });
512
- return heal !== undefined && (await store.runs.healCost(runId, heal, heal.usd));
514
+ return heal !== undefined && (await store.runs.healCost(runId, heal, heal));
513
515
  }
514
516
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
515
517
  export async function viewOverStore(store, runId, deps) {
@@ -25,7 +25,8 @@ import { evalClock, LAYOUTS, mailboxAfter, mailboxFixtureOf, mailboxText, mailbo
25
25
  import { caseFeeds, feedFixtureOf } from "./eval-feed.js";
26
26
  import { EMAIL_TOOLS } from "./email/names.js";
27
27
  import { CALENDAR_EVENTS } from "./calendar/names.js";
28
- import { settingsKeyOf, shellToolOf } from "./tool-gate.js";
28
+ import { nameMapOf, settingsKeyOf, shellToolOf } from "./tool-gate.js";
29
+ import { builtinHarness } from "./harness-table.js";
29
30
  import { webShownOf } from "./timeline/index.js";
30
31
  import { ASK_TOOL, BOUND_TOOLS } from "./tools.js";
31
32
  import { webFixtureOf } from "./web-fake.js";
@@ -918,10 +919,12 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
918
919
  * its output's head as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
919
920
  export function callsOf(rows, harness, toolkits = {}) {
920
921
  const results = new Map(rows.filter((row) => row.kind === "tool_result" && row.tool_use_id).map((row) => [String(row.tool_use_id), row]));
922
+ // The rows are a server's, read over its API: the names are the built-in harness's, the only facts known here.
923
+ const names = nameMapOf(harness, builtinHarness(harness)?.facts);
921
924
  return rows.filter((row) => row.kind === "tool_use" && typeof row.tool_name === "string").map((row) => {
922
925
  const name = row.tool_name;
923
926
  const result = results.get(String(row.tool_use_id));
924
- const key = settingsKeyOf(harness, name);
927
+ const key = settingsKeyOf(harness, name, names);
925
928
  const output = typeof result?.tool_result_text === "string" ? result.tool_result_text : (result?.tool_result_preview ?? null);
926
929
  return { tool: shellToolOf(name) ?? (key === undefined ? undefined : onServerName(key, toolkits)) ?? name, name, preview: row.tool_input_preview ?? null, ...(isObject(row.tool_input) ? { arguments: row.tool_input } : {}), status: result?.tool_status ?? null, result: output };
927
930
  });
@@ -16,11 +16,15 @@ export type Held = {
16
16
  readonly unreadable: string;
17
17
  };
18
18
  /** Each GitHub MCP tool a template may grant that needs more than reading what the App's metadata gives: the permission
19
- * and level GitHub's permission table for its request names, and what the template does instead when it can't. */
19
+ * and level GitHub's permission table for its request names, and what the template does instead when it can't.
20
+ * `public`: GitHub's table states a permission for private resources, and this request works on a public repository
21
+ * without it (POST /repos/{owner}/{repo}/issues: "any user with pull access to a repository can create an issue"), so the
22
+ * warning is about private repositories and says what a public one does. */
20
23
  export declare const TOOL_PERMISSIONS: Record<string, {
21
24
  permission: string;
22
25
  level: Level;
23
26
  instead: string;
27
+ public?: string;
24
28
  }>;
25
29
  /** The warnings applying `pkg` adds: one for each GitHub MCP tool it grants that needs a permission an installation of the
26
30
  * App does not hold (naming each installation's account and what it holds), on an MCP server `onApp` says runs on the App's