@parcha/agentrun-serve 0.1.0-beta.41 → 0.1.0-beta.43

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 (164) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/NOTICE +2 -0
  3. package/README.md +85 -19
  4. package/dist/agent-rows.d.ts +1 -1
  5. package/dist/agents-store.js +3 -1
  6. package/dist/calendar/address.d.ts +49 -0
  7. package/dist/calendar/address.js +153 -0
  8. package/dist/calendar/fetch.d.ts +24 -0
  9. package/dist/calendar/fetch.js +146 -0
  10. package/dist/calendar/ics-faux.d.ts +39 -0
  11. package/dist/calendar/ics-faux.js +236 -0
  12. package/dist/calendar/labels.d.ts +3 -0
  13. package/dist/calendar/labels.js +61 -0
  14. package/dist/calendar/names.d.ts +52 -0
  15. package/dist/calendar/names.js +54 -0
  16. package/dist/calendar/parse.d.ts +108 -0
  17. package/dist/calendar/parse.js +625 -0
  18. package/dist/calendar/routes.d.ts +17 -0
  19. package/dist/calendar/routes.js +81 -0
  20. package/dist/calendar/tools.d.ts +23 -0
  21. package/dist/calendar/tools.js +124 -0
  22. package/dist/cli.js +3 -1
  23. package/dist/computer-record.d.ts +55 -0
  24. package/dist/computer-record.js +315 -0
  25. package/dist/computer-setting.d.ts +1 -0
  26. package/dist/computer-setting.js +15 -2
  27. package/dist/computers.js +2 -14
  28. package/dist/console/assets/index-BrcDSBD8.css +1 -0
  29. package/dist/console/assets/index-Bz6IWncl.js +711 -0
  30. package/dist/console/index.html +2 -2
  31. package/dist/decisions.js +0 -4
  32. package/dist/eval-feed.d.ts +2 -2
  33. package/dist/eval-feed.js +9 -5
  34. package/dist/feed/parse.d.ts +3 -2
  35. package/dist/feed/parse.js +9 -18
  36. package/dist/feed/pointer.d.ts +2 -0
  37. package/dist/feed/pointer.js +17 -0
  38. package/dist/file-types.js +1 -0
  39. package/dist/host-command.d.ts +3 -0
  40. package/dist/host-command.js +18 -0
  41. package/dist/host.d.ts +3 -0
  42. package/dist/host.js +3 -0
  43. package/dist/import-sources.js +25 -5
  44. package/dist/learn/audit.d.ts +123 -0
  45. package/dist/learn/audit.js +159 -0
  46. package/dist/learn/check.d.ts +14 -0
  47. package/dist/learn/check.js +194 -14
  48. package/dist/learn/compile.d.ts +75 -78
  49. package/dist/learn/compile.js +175 -176
  50. package/dist/learn/folder.d.ts +9 -0
  51. package/dist/learn/folder.js +13 -2
  52. package/dist/learn/promote.d.ts +138 -196
  53. package/dist/learn/promote.js +68 -184
  54. package/dist/learn/replay-calls.d.ts +5 -0
  55. package/dist/learn/replay-calls.js +12 -1
  56. package/dist/learn/secrets.d.ts +8 -0
  57. package/dist/learn/secrets.js +12 -0
  58. package/dist/learn/skills.js +2 -4
  59. package/dist/learn/workflow-nodes.d.ts +1 -2
  60. package/dist/learn/workflow-nodes.js +2 -3
  61. package/dist/learned-nodes.d.ts +9 -34
  62. package/dist/learned-nodes.js +11 -23
  63. package/dist/learned-workflow.d.ts +6 -8
  64. package/dist/learned-workflow.js +18 -57
  65. package/dist/learning-batch.d.ts +13 -5
  66. package/dist/learning-batch.js +34 -8
  67. package/dist/learning-cost.d.ts +11 -4
  68. package/dist/learning-cost.js +4 -2
  69. package/dist/learning-routes.js +1 -1
  70. package/dist/learning-setting.d.ts +38 -0
  71. package/dist/learning-setting.js +83 -0
  72. package/dist/learning-words.d.ts +3 -0
  73. package/dist/learning-words.js +3 -0
  74. package/dist/learning.d.ts +3 -2
  75. package/dist/learning.js +5 -3
  76. package/dist/mcp-oauth.d.ts +8 -0
  77. package/dist/mcp-oauth.js +7 -0
  78. package/dist/mcp-private-hosts.d.ts +13 -0
  79. package/dist/mcp-private-hosts.js +16 -0
  80. package/dist/openapi.d.ts +1 -0
  81. package/dist/openapi.js +195 -59
  82. package/dist/run-files.d.ts +6 -2
  83. package/dist/run-files.js +29 -7
  84. package/dist/run-launch.d.ts +6 -3
  85. package/dist/run-launch.js +2 -0
  86. package/dist/run-learning-served.d.ts +2 -2
  87. package/dist/run-reads-over-store.d.ts +5 -1
  88. package/dist/run-reads-over-store.js +8 -4
  89. package/dist/run-recordings.d.ts +20 -0
  90. package/dist/run-recordings.js +133 -0
  91. package/dist/runner/adapter-loop.d.ts +5 -1
  92. package/dist/runner/adapter-loop.js +20 -8
  93. package/dist/runner/adapter-run-spec.d.ts +16 -1
  94. package/dist/runner/adapter-run-spec.js +36 -11
  95. package/dist/runner/audit.d.ts +64 -0
  96. package/dist/runner/audit.js +338 -0
  97. package/dist/runner/beside.js +2 -2
  98. package/dist/runner/cli-run-spec.js +25 -12
  99. package/dist/runner/feedback-round.d.ts +9 -25
  100. package/dist/runner/feedback-round.js +19 -40
  101. package/dist/runner/harness-loops.js +1 -15
  102. package/dist/runner/journal-kinds.d.ts +0 -7
  103. package/dist/runner/journal-kinds.js +0 -7
  104. package/dist/runner/learning-dispatch.d.ts +0 -16
  105. package/dist/runner/learning-dispatch.js +4 -47
  106. package/dist/runner/learning-end.d.ts +62 -13
  107. package/dist/runner/learning-end.js +180 -74
  108. package/dist/runner/learning-factory.d.ts +1 -1
  109. package/dist/runner/learning-factory.js +1 -4
  110. package/dist/runner/learning-loop.d.ts +2 -38
  111. package/dist/runner/learning-loop.js +8 -116
  112. package/dist/runner/main.d.ts +11 -0
  113. package/dist/runner/main.js +30 -3
  114. package/dist/runner/mcp-run.d.ts +2 -2
  115. package/dist/runner/promotion.d.ts +78 -50
  116. package/dist/runner/promotion.js +371 -503
  117. package/dist/runner/reflect-hook.d.ts +15 -0
  118. package/dist/runner/reflect-hook.js +28 -14
  119. package/dist/runner/store-secrets.js +3 -1
  120. package/dist/runner/workflow-first.d.ts +6 -11
  121. package/dist/runner/workflow-first.js +24 -25
  122. package/dist/runs-over-store.d.ts +1 -1
  123. package/dist/sdk/runs.js +2 -1
  124. package/dist/secrets.js +2 -2
  125. package/dist/server.d.ts +4 -3
  126. package/dist/server.js +132 -26
  127. package/dist/store/agent-body.d.ts +5 -3
  128. package/dist/store/agent-body.js +14 -10
  129. package/dist/store/sqlite/store.js +1 -0
  130. package/dist/store/store.d.ts +3 -0
  131. package/dist/store-reads/learning.d.ts +18 -7
  132. package/dist/store-reads/learning.js +36 -23
  133. package/dist/store-reads/loop.d.ts +5 -39
  134. package/dist/store-reads/loop.js +21 -80
  135. package/dist/store-view.d.ts +5 -0
  136. package/dist/store-view.js +16 -2
  137. package/dist/template-eval.d.ts +7 -0
  138. package/dist/template-eval.js +54 -6
  139. package/dist/templates.d.ts +3 -1
  140. package/dist/templates.js +14 -1
  141. package/dist/timeline/computer.js +2 -1
  142. package/dist/tool-list.js +1 -0
  143. package/dist/tools.d.ts +7 -0
  144. package/dist/tools.js +11 -0
  145. package/dist/trigger-feed.js +67 -18
  146. package/dist/validate.js +7 -2
  147. package/dist/workspace/computer-for-claim.d.ts +7 -0
  148. package/dist/workspace/computer-for-claim.js +12 -2
  149. package/dist/workspace/paths.d.ts +4 -0
  150. package/dist/workspace/paths.js +9 -0
  151. package/dist/workspace/resolve-computer.d.ts +3 -1
  152. package/dist/workspace/run-tools.d.ts +1 -1
  153. package/dist/workspace/run-tools.js +14 -3
  154. package/launcher/agentrun-serve +31 -24
  155. package/package.json +10 -9
  156. package/templates/README.md +11 -2
  157. package/dist/console/assets/index-C3gNPz58.css +0 -1
  158. package/dist/console/assets/index-COGhx_2Z.js +0 -711
  159. package/dist/learn/general.d.ts +0 -69
  160. package/dist/learn/general.js +0 -75
  161. package/dist/learn/refit.d.ts +0 -48
  162. package/dist/learn/refit.js +0 -264
  163. package/dist/runner/step-guard.d.ts +0 -62
  164. package/dist/runner/step-guard.js +0 -93
package/dist/run-files.js CHANGED
@@ -73,8 +73,23 @@ const fileEntry = async (workspace, rel) => {
73
73
  const entry = await entryAt(workspace, rel);
74
74
  return entry?.kind === "file" ? entry : undefined;
75
75
  };
76
- /** File `rel` of `workspace`, raw, in reads of SEND_CHUNK: its length from the listing, so HEAD reads no byte. `who`
77
- * names who makes a file private, in the words of a 403. */
76
+ /** The one byte range a Range header asks of a file of `size` bytes, first and last byte; undefined for the whole file (no
77
+ * Range, or one this server does not take: another unit, several ranges, or a last byte before the first);
78
+ * "unsatisfiable" when it starts past the file's end. */
79
+ export function rangeOf(header, size) {
80
+ const asked = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? "");
81
+ if (!asked || (asked[1] === "" && asked[2] === ""))
82
+ return undefined;
83
+ if (asked[1] === "")
84
+ return Number(asked[2]) === 0 || size === 0 ? "unsatisfiable" : [Math.max(0, size - Number(asked[2])), size - 1];
85
+ const start = Number(asked[1]);
86
+ if (start >= size)
87
+ return "unsatisfiable";
88
+ const end = asked[2] === "" ? size - 1 : Math.min(Number(asked[2]), size - 1);
89
+ return end < start ? undefined : [start, end];
90
+ }
91
+ /** File `rel` of `workspace`, raw, in reads of SEND_CHUNK, whole or the one byte range its Range header asks (206): its
92
+ * length from the listing, so HEAD reads no byte. `who` names who makes a file private, in the words of a 403. */
78
93
  export async function sendFile(req, res, url, workspace, rel, who) {
79
94
  const unreadable = () => new ApiError("system_file_forbidden", `This file was created private by ${who}: this server cannot read it.`, { details: { reason: "unreadable" } });
80
95
  const entry = await fileEntry(workspace, rel);
@@ -82,9 +97,14 @@ export async function sendFile(req, res, url, workspace, rel, who) {
82
97
  throw new ApiError("not_found", "no such file");
83
98
  if (entry.unreadable)
84
99
  throw unreadable();
100
+ const range = rangeOf(req.headers?.range, entry.size);
101
+ if (range === "unsatisfiable")
102
+ throw new ApiError("range_not_satisfiable", `The range asked for starts past the file's end: it is ${entry.size} bytes.`, {}, { "content-range": `bytes */${entry.size}` });
103
+ const [start, last] = range ?? [0, entry.size - 1];
104
+ const length = last - start + 1;
85
105
  // A GET reads its first chunk before the head: a file gone, or swapped for a link, since the listing is a 404, not a
86
106
  // broken 200. A HEAD reads none.
87
- const first = req.method === "HEAD" ? new Uint8Array(0) : await workspace.read(rel, { offset: 0, length: Math.min(SEND_CHUNK, entry.size) }).catch((error) => {
107
+ const first = req.method === "HEAD" ? new Uint8Array(0) : await workspace.read(rel, { offset: start, length: Math.min(SEND_CHUNK, length) }).catch((error) => {
88
108
  if (isWorkspaceError(error, "REFUSED"))
89
109
  throw unreadable();
90
110
  if (skipped(error))
@@ -94,9 +114,11 @@ export async function sendFile(req, res, url, workspace, rel, who) {
94
114
  const type = typeOf(rel) ?? "application/octet-stream";
95
115
  const download = url.searchParams.get("download") === "1" || !INLINE_TYPES.has(type);
96
116
  const name = rel.split("/").at(-1).replace(/[^\w.-]/g, "_");
97
- res.writeHead(200, {
117
+ res.writeHead(range ? 206 : 200, {
98
118
  "content-type": type,
99
- "content-length": entry.size,
119
+ "content-length": length,
120
+ "accept-ranges": "bytes",
121
+ ...(range ? { "content-range": `bytes ${start}-${last}/${entry.size}` } : {}),
100
122
  "x-content-type-options": "nosniff",
101
123
  "cache-control": "no-store",
102
124
  ...(type.startsWith("text/html") ? { "content-security-policy": FILE_CSP } : {}),
@@ -107,13 +129,13 @@ export async function sendFile(req, res, url, workspace, rel, who) {
107
129
  // The length said is the listing's: a file that changes while it is sent is cut there, or the answer ends short.
108
130
  try {
109
131
  let sent = 0;
110
- for (let chunk = first;; chunk = await workspace.read(rel, { offset: sent, length: Math.min(SEND_CHUNK, entry.size - sent) })) {
132
+ for (let chunk = first;; chunk = await workspace.read(rel, { offset: start + sent, length: Math.min(SEND_CHUNK, length - sent) })) {
111
133
  if (chunk.length === 0 || res.destroyed)
112
134
  break;
113
135
  if (!res.write(chunk))
114
136
  await new Promise((resolve) => { res.once("drain", resolve); res.once("close", resolve); });
115
137
  sent += chunk.length;
116
- if (sent >= entry.size)
138
+ if (sent >= length)
117
139
  break;
118
140
  }
119
141
  }
@@ -84,10 +84,13 @@ export interface RunLaunch {
84
84
  /** `false`: the run never starts on a learned workflow, even one that fits its input (RunCreate `workflow_first`,
85
85
  * runner/workflow-first.ts); its agent takes it from its first turn. Absent: a fitting one serves first. */
86
86
  readonly workflowFirst?: false;
87
- /** A replay run (runner/promotion.ts): learned workflow `workflow` at `digest`, run alone on graded run `of`'s input to
88
- * decide whether that revision serves first (learn/promote.ts). Its guards read record-only (learn/promote.ts recordOnly), a hand-back ends it
89
- * with no agent turn, and it asks nothing at its end. Absent: a run of its own. */
87
+ /** A replay run (runner/promotion.ts): learned workflow `workflow` at `digest`, run alone on the agent's own run `of`'s input to
88
+ * decide whether that revision serves first (learn/promote.ts). A hand-back ends it with no agent turn, and it asks nothing at its end. Absent: a run of its own. */
90
89
  readonly replay?: Replay;
90
+ /** A shadow run (runner/audit.ts): the audit of run `of`, which learned workflow `workflow` at `digest` served. The same
91
+ * agent on the same input with learning off: its answer is what the served answer is compared with (learn/audit.ts),
92
+ * it is no row of the run list, and it asks nothing at its end. Absent: a run of its own. */
93
+ readonly audit?: Replay;
91
94
  /** The trigger and firing that started the run, or none for a person's run. */
92
95
  readonly trigger?: RunTrigger;
93
96
  /** Who the first message is from, when not the person: kept only through the fail-safe below. */
@@ -70,6 +70,7 @@ export function launchBody(launch) {
70
70
  ...(launch.learning ? { learning: { given: launch.learning.given.map((note) => ({ file: note.file, name: note.name })), seed: launch.learning.seed, section: launch.learning.section, ...(launch.learning.seedNotes !== undefined ? { seedNotes: launch.learning.seedNotes } : {}), ...(launch.learning.notesLeftOut?.length ? { notesLeftOut: [...launch.learning.notesLeftOut] } : {}), ...(launch.learning.skills?.length ? { skills: [...launch.learning.skills] } : {}), ...(launch.learning.notesOnly ? { notesOnly: true } : {}), ...(launch.learning.workflows?.length ? { workflows: [...launch.learning.workflows] } : {}), ...(launch.learning.gradeModel ? { gradeModel: launch.learning.gradeModel } : {}), ...(launch.learning.seedFailed ? { seedFailed: launch.learning.seedFailed } : {}), ...(launch.learning.use ? { use: true } : {}) } } : {}),
71
71
  ...(launch.workflowFirst === false ? { workflow_first: false } : {}),
72
72
  ...(launch.replay ? { replay: { of: launch.replay.of, workflow: launch.replay.workflow, digest: launch.replay.digest } } : {}),
73
+ ...(launch.audit ? { audit: { of: launch.audit.of, workflow: launch.audit.workflow, digest: launch.audit.digest } } : {}),
73
74
  ...(launch.trigger ? { trigger: launch.trigger } : {}),
74
75
  ...(launch.inputOrigin ? { input_origin: launch.inputOrigin } : {}),
75
76
  ...(launch.followUp ? { follow_up: true } : {}),
@@ -124,6 +125,7 @@ export function readLaunchBody(stored) {
124
125
  ...(stored.learning !== undefined ? { learning: readLearning(stored.learning) ?? { given: [], seed: null, section: "" } } : {}),
125
126
  ...(stored.workflow_first === false ? { workflowFirst: false } : {}),
126
127
  ...(readReplay(stored.replay) ? { replay: readReplay(stored.replay) } : {}),
128
+ ...(readReplay(stored.audit) ? { audit: readReplay(stored.audit) } : {}),
127
129
  ...(trigger ? { trigger } : {}),
128
130
  ...(inputOrigin ? { inputOrigin } : {}),
129
131
  ...(stored.follow_up === true ? { followUp: true } : {}),
@@ -74,9 +74,9 @@ export declare function servedRunLearning(deps: {
74
74
  feedback_status: "running" | "ended" | "not_run" | null;
75
75
  source: "feedback" | "eval";
76
76
  graded_at: string;
77
- path: "agent" | "workflow" | "handed_back" | "replay";
77
+ path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
78
78
  workflow_digest: string | null;
79
- feedback: "revise" | "look_back" | null;
79
+ feedback: "look_back" | null;
80
80
  run_id: string;
81
81
  correct: boolean;
82
82
  };
@@ -17,6 +17,9 @@ export interface RunReadsDeps {
17
17
  /** The run's Workspace for a server-side read (not the runner's claim-time openRunWorkspace): null when it has no folder
18
18
  * (an imported run never has one). */
19
19
  runWorkspace(store: RunReadsStore, runId: string): Promise<Workspace | null>;
20
+ /** The run's recordings folder on this machine, read-only (run-recordings.ts recordingsWorkspace): null when it recorded
21
+ * nothing. */
22
+ recordings(store: RunReadsStore, runId: string): Promise<Workspace | null>;
20
23
  /** The environment the plane re-check reads (tool-plane.ts recheckPlane): the server's keys as it holds them. */
21
24
  readonly env: NodeJS.ProcessEnv;
22
25
  /** The run's open live browser viewer, when its runner serves one (its link), or undefined. The runner publishes the
@@ -47,7 +50,8 @@ export declare function listRunFiles(store: RunReadsStore, runId: string, deps:
47
50
  truncated: boolean;
48
51
  }>;
49
52
  /** One of a run's files, through its Workspace (readRunFile): streamed to `res` as the route streams it, with the route's
50
- * path check and its 404 words; a withheld run refuses (403) before anything is streamed. */
53
+ * path check and its 404 words; a withheld run refuses (403) before anything is streamed. A path under recordings/ is
54
+ * one of the run's recordings (its recordings folder, beside its Workspace's), never a file the run made. */
51
55
  export declare function readRunFile(store: RunReadsStore, runId: string, rawPath: string, req: IncomingMessage, res: ServerResponse, url: URL, deps: RunReadsDeps): Promise<void>;
52
56
  /** A run's browser state (getRunBrowser): `live` with its viewer's link when its runner serves one; else `off` with why
53
57
  * when the run has no browser or its browser is unavailable here now (the kept plane re-checked, as a launch would); else
@@ -10,6 +10,7 @@ import { costIsBooked } from "./runner/metrics.js";
10
10
  import { runEntries, runTimeline } from "./store-reads/journal.js";
11
11
  import { StoreLaunchMissing } from "./store/index.js";
12
12
  import { isUnavailable, recheckPlane, whyUnavailable } from "./tool-plane.js";
13
+ import { RECORDINGS } from "./workspace/paths.js";
13
14
  /** The most files a list answers with (server.ts FILE_LIST_CAP). */
14
15
  export const FILE_LIST_CAP = 2_000;
15
16
  /** A run's files, through its Workspace (listRunFiles): every file, path-sorted, cut at the cap. A run with no folder lists
@@ -20,20 +21,23 @@ export async function listRunFiles(store, runId, deps) {
20
21
  if (await deps.withheld(store, runId))
21
22
  throw new ApiError("forbidden", WITHHELD_SIGN_IN);
22
23
  const workspace = await deps.runWorkspace(store, runId);
23
- const { files, deep } = workspace ? await listFiles(workspace, FILE_LIST_CAP) : { files: [], deep: false };
24
+ // A folder the run made named recordings is not listed: the route's recordings/ is the run's recordings.
25
+ const { files, deep } = workspace ? await listFiles(workspace, FILE_LIST_CAP, { owned: (name) => name === RECORDINGS }) : { files: [], deep: false };
24
26
  files.sort((a, b) => a.path.localeCompare(b.path));
25
27
  return { run_id: runId, files: files.slice(0, FILE_LIST_CAP), complete: true, truncated: deep || files.length > FILE_LIST_CAP };
26
28
  }
27
29
  /** One of a run's files, through its Workspace (readRunFile): streamed to `res` as the route streams it, with the route's
28
- * path check and its 404 words; a withheld run refuses (403) before anything is streamed. */
30
+ * path check and its 404 words; a withheld run refuses (403) before anything is streamed. A path under recordings/ is
31
+ * one of the run's recordings (its recordings folder, beside its Workspace's), never a file the run made. */
29
32
  export async function readRunFile(store, runId, rawPath, req, res, url, deps) {
30
33
  if (await deps.withheld(store, runId))
31
34
  throw new ApiError("forbidden", WITHHELD_SIGN_IN);
32
35
  const rel = checkedPath(decodedPath(rawPath), "the run's own, not a file it wrote");
33
- const workspace = await deps.runWorkspace(store, runId);
36
+ const recording = rel.startsWith(`${RECORDINGS}/`) ? rel.slice(RECORDINGS.length + 1) : undefined;
37
+ const workspace = await (recording === undefined ? deps.runWorkspace : deps.recordings)(store, runId);
34
38
  if (!workspace)
35
39
  throw new ApiError("not_found", "no such file");
36
- return sendFile(req, res, url, workspace, rel, "a tool in the run's box");
40
+ return sendFile(req, res, url, workspace, recording ?? rel, "a tool in the run's box");
37
41
  }
38
42
  /** Whether the run's revision grants the browser tool: an agentic revision whose tools name it. */
39
43
  async function grantsBrowser(store, revisionId) {
@@ -0,0 +1,20 @@
1
+ import { type Workspace } from "./workspace/index.js";
2
+ /** One recording as the run read lists it. `finished`: ffmpeg finished the file, or the run has ended and the file has
3
+ * stopped changing (an encoder cut short leaves a file that plays up to its last fragment). */
4
+ export type RecordingView = {
5
+ path: string;
6
+ computer: string;
7
+ seconds: number;
8
+ bytes: number;
9
+ finished: boolean;
10
+ };
11
+ /** The recordings `folder` holds as a read-only Workspace, or null when it holds none (the run recorded nothing). */
12
+ export declare function recordingsWorkspace(folder: string): Promise<Workspace | null>;
13
+ /** The recordings in `folder`, each computer's files in the order it recorded them: its path on the files route, its
14
+ * computer (its ref id, as its file is named: computer-record.ts names a computer's later files <computer>-2.mp4 and
15
+ * on), its length in seconds, its size, and whether it is finished: its trailer is there, or the run ended at `endedAt`
16
+ * and neither that end nor the file's last change is within twice the time the recorder gives ffmpeg to finish it
17
+ * (RECORDING_LIMITS.settleMs; the recorder stops at the computer's release, right after the run's end is saved, and a
18
+ * quiet screen's file may not have changed for a while before it). None when the folder isn't there. A file that can't
19
+ * be read is listed with 0 seconds. */
20
+ export declare function recordingsOf(folder: string, endedAt: number | null): Promise<RecordingView[]>;
@@ -0,0 +1,133 @@
1
+ // A run's screen recordings as the API serves them: the files computer-record.ts writes into the run's recordings folder
2
+ // on this machine (workspace/paths.ts recordingsFolder), beside its work/ folder. The run view lists them (`recordings`),
3
+ // and the run files route serves them under recordings/, read-only, to the readers of the run's other files.
4
+ //
5
+ // A file's length is read from its own boxes, never by running a program: ffmpeg's fragmented MP4 says each fragment's
6
+ // start (tfdt) and each frame's duration (trun, else tfhd's or trex's default), at its track's timescale (mdhd). A
7
+ // finished file ends with ffmpeg's trailer (mfra); one still being written has none, and its last box may be cut short,
8
+ // so it is read up to its last whole box. A read goes on from where the one before it stopped, so a console that polls a
9
+ // recording being written reads only what was added.
10
+ import { lstat, open, readdir } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+ import { RECORDING_LIMITS } from "./computer-record.js";
13
+ import { localWorkspace, readOnlyWorkspace } from "./workspace/index.js";
14
+ import { RECORDINGS } from "./workspace/paths.js";
15
+ /** The recordings `folder` holds as a read-only Workspace, or null when it holds none (the run recorded nothing). */
16
+ export async function recordingsWorkspace(folder) {
17
+ const there = await lstat(folder).catch(() => undefined);
18
+ return there?.isDirectory() ? readOnlyWorkspace(localWorkspace(folder)) : null;
19
+ }
20
+ /** The newest reads, by path: at most READS_KEPT. */
21
+ const reads = new Map();
22
+ const READS_KEPT = 256;
23
+ /** The boxes in `buf`, each its type and its body; a box cut short ends the walk. */
24
+ function* boxes(buf) {
25
+ for (let at = 0; at + 8 <= buf.length;) {
26
+ let length = buf.readUInt32BE(at);
27
+ let head = 8;
28
+ if (length === 1 && at + 16 <= buf.length)
29
+ [length, head] = [Number(buf.readBigUInt64BE(at + 8)), 16];
30
+ if (length < head || at + length > buf.length)
31
+ return;
32
+ yield [buf.toString("latin1", at + 4, at + 8), buf.subarray(at + head, at + length)];
33
+ at += length;
34
+ }
35
+ }
36
+ /** What box `type` says into `read`: the timescale, the default frame duration, and a fragment's end. */
37
+ function take(read, type, body) {
38
+ if (type === "moov" || type === "trak" || type === "mdia" || type === "mvex" || type === "moof")
39
+ for (const [inner, part] of boxes(body))
40
+ take(read, inner, part);
41
+ else if (type === "mdhd")
42
+ read.timescale = body.readUInt32BE(body[0] === 1 ? 20 : 12);
43
+ else if (type === "trex")
44
+ read.dflt = body.readUInt32BE(12);
45
+ else if (type === "traf") {
46
+ let start = 0;
47
+ let dflt = read.dflt;
48
+ let length = 0;
49
+ for (const [inner, part] of boxes(body)) {
50
+ const flags = part.readUInt32BE(0) & 0xffffff;
51
+ if (inner === "tfhd" && flags & 0x8)
52
+ dflt = part.readUInt32BE(8 + (flags & 0x1 ? 8 : 0) + (flags & 0x2 ? 4 : 0));
53
+ else if (inner === "tfdt")
54
+ start = part[0] === 1 ? Number(part.readBigUInt64BE(4)) : part.readUInt32BE(4);
55
+ else if (inner === "trun") {
56
+ const count = part.readUInt32BE(4);
57
+ const stride = 4 * [0x100, 0x200, 0x400, 0x800].filter((bit) => flags & bit).length;
58
+ for (let i = 0, at = 8 + (flags & 0x1 ? 4 : 0) + (flags & 0x4 ? 4 : 0); i < count; i += 1, at += stride)
59
+ length += flags & 0x100 ? part.readUInt32BE(at) : dflt;
60
+ }
61
+ }
62
+ read.end = Math.max(read.end, start + length);
63
+ }
64
+ }
65
+ /** File `path`'s read, `size` bytes long and changed at `mtimeMs` now: the last read when the file is unchanged (it is not
66
+ * opened), on from it when the file only grew, else from its start. */
67
+ async function readOf(path, size, mtimeMs) {
68
+ const kept = reads.get(path);
69
+ if (kept && kept.size === size && kept.mtimeMs === mtimeMs)
70
+ return kept;
71
+ const read = kept && kept.size <= size ? { ...kept } : { at: 0, size: 0, mtimeMs: 0, timescale: 0, dflt: 0, end: 0, finished: false };
72
+ const file = await open(path, "r");
73
+ try {
74
+ const head = Buffer.alloc(16);
75
+ while (read.at + 8 <= size) {
76
+ await file.read(head, 0, 16, read.at);
77
+ let length = head.readUInt32BE(0);
78
+ let skip = 8;
79
+ if (length === 1)
80
+ [length, skip] = [Number(head.readBigUInt64BE(8)), 16];
81
+ if (length < skip || read.at + length > size)
82
+ break;
83
+ const type = head.toString("latin1", 4, 8);
84
+ if (type === "mfra")
85
+ read.finished = true;
86
+ if (type === "moov" || type === "moof") {
87
+ const body = Buffer.alloc(length - skip);
88
+ await file.read(body, 0, body.length, read.at + skip);
89
+ take(read, type, body);
90
+ }
91
+ read.at += length;
92
+ }
93
+ }
94
+ finally {
95
+ await file.close();
96
+ }
97
+ read.size = size;
98
+ read.mtimeMs = mtimeMs;
99
+ reads.delete(path);
100
+ reads.set(path, read);
101
+ if (reads.size > READS_KEPT)
102
+ reads.delete(reads.keys().next().value);
103
+ return read;
104
+ }
105
+ /** The recordings in `folder`, each computer's files in the order it recorded them: its path on the files route, its
106
+ * computer (its ref id, as its file is named: computer-record.ts names a computer's later files <computer>-2.mp4 and
107
+ * on), its length in seconds, its size, and whether it is finished: its trailer is there, or the run ended at `endedAt`
108
+ * and neither that end nor the file's last change is within twice the time the recorder gives ffmpeg to finish it
109
+ * (RECORDING_LIMITS.settleMs; the recorder stops at the computer's release, right after the run's end is saved, and a
110
+ * quiet screen's file may not have changed for a while before it). None when the folder isn't there. A file that can't
111
+ * be read is listed with 0 seconds. */
112
+ export async function recordingsOf(folder, endedAt) {
113
+ const names = await readdir(folder).catch(() => []);
114
+ const files = new Set(names.filter((name) => name.endsWith(".mp4")));
115
+ const series = [...files].map((name) => {
116
+ const base = name.slice(0, -".mp4".length);
117
+ const later = /^(.+)-(\d+)$/.exec(base);
118
+ return later && Number(later[2]) >= 2 && files.has(`${later[1]}.mp4`) ? { name, computer: later[1], n: Number(later[2]) } : { name, computer: base, n: 1 };
119
+ });
120
+ series.sort((a, b) => (a.computer === b.computer ? a.n - b.n : a.computer < b.computer ? -1 : 1));
121
+ const listed = [];
122
+ for (const { name, computer } of series) {
123
+ const path = join(folder, name);
124
+ const file = await lstat(path).catch(() => undefined);
125
+ if (!file?.isFile())
126
+ continue;
127
+ const read = await readOf(path, file.size, file.mtimeMs).catch(() => undefined);
128
+ const seconds = read?.timescale ? Math.round((read.end / read.timescale) * 10) / 10 : 0;
129
+ const settled = endedAt !== null && Date.now() - Math.max(endedAt, file.mtimeMs) > 2 * RECORDING_LIMITS.settleMs;
130
+ listed.push({ path: `${RECORDINGS}/${name}`, computer, seconds, bytes: file.size, finished: read?.finished === true || settled });
131
+ }
132
+ return listed;
133
+ }
@@ -138,7 +138,7 @@ export interface AdapterRunSpec {
138
138
  readonly workflowFirst?: WorkflowFirst;
139
139
  /** The learned workflow that fits the run but that the money rule stopped from running first (workflow-first.ts
140
140
  * costLineOf): the loop keeps why on the root (WORKFLOW_FIRST, outcome needs_revision, the two numbers) as the agent
141
- * takes the run, and the run's end-of-run turn asks for its revision. */
141
+ * takes the run. The stop asks for no revision. */
142
142
  readonly workflowRevise?: WorkflowRevise;
143
143
  /** The run's end-of-run step, when its spec builds one (over the per-claim resources it holds, its Archil claim among
144
144
  * them): it wins over LoopDeps.endOfRun and is asked where that one is, in the end turn while the claim is held, before
@@ -207,6 +207,10 @@ export interface AdapterRunSpec {
207
207
  * words the loop says so in on the run's timeline as it parks (computer-deps.ts computerKeptWords). Absent: a park lets
208
208
  * the computer go. */
209
209
  readonly keptWords?: string;
210
+ /** The run waits on no one (an audit's shadow run, runner/audit.ts AUDIT_PARKED): where it would park (an approval, a
211
+ * raise of its cap, a person's answer) it ends failed at once in these words, saying what it would wait on, every call
212
+ * still waiting withdrawn in the end's commit (parkClaim). Absent: it parks. */
213
+ readonly neverWaits?: string;
210
214
  /** What the spec's tool host bindings registered (tools.ts ToolHost's onConversation, beforeResume, beforeRelease),
211
215
  * run where main's per-run process runs them (app.ts): each agent conversation's creating commit, once the claim's
212
216
  * Harness is open and before anything in it resumes, and when the claim lets the run go (its end, a park, a
@@ -73,6 +73,14 @@ function cardOf(tool, shown, args) {
73
73
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
74
74
  /** What a CLI's request held at a cut turn (TurnCut) is refused with: the turn ended at the person's question. */
75
75
  const TURN_CUT_AT_QUESTION = "the turn ended at its question to the person";
76
+ /** What a run that waits on no one (AdapterRunSpec.neverWaits) would have waited on, by its park's cause: its end says so. */
77
+ const WAITS_ON = {
78
+ approval: "a person's approval of a tool call",
79
+ answer: "a person's answer to its question",
80
+ cap: "a raise of its cap",
81
+ refusal: "a raise of its cap",
82
+ workflow: "a person's approval of a tool call",
83
+ };
76
84
  function turnCut() {
77
85
  let armedAt;
78
86
  let ask;
@@ -3580,14 +3588,11 @@ function adapterLoop(specOf, options, deps) {
3580
3588
  const theSession = session;
3581
3589
  const requestId = reflectRequestId(claim.runId, again, round, step);
3582
3590
  const theRecord = cliRecord;
3583
- // A grade's feedback round (feedbackNow): its first ask is told the grade first (feedback-round.ts feedbackAsk), and,
3584
- // when the agent never took the job (its learned workflow answered alone: its session is new), the job and the
3585
- // workflow's answer before it, cut of every secret the runner holds, as a follow-up's are.
3591
+ // A grade's feedback round (feedbackNow): its first ask is told the grade first (feedback-round.ts feedbackAsk), cut
3592
+ // of every secret the runner holds. Only a run the agent finished opens one, so its session saw the job.
3586
3593
  if (feedbackNow && !again && step === undefined) {
3587
3594
  const cut = (text) => (deps.redact ? deps.redact(text) : text);
3588
- const servedNow = theSession.state === "new" ? servedAnswerOf(await entriesOf(gate.journal, conversation.id, context)) : undefined;
3589
- const seen = servedNow && specNow ? { job: specNow.input, served: { workflow: servedNow.workflow, answer: cut(servedNow.answer) } } : undefined;
3590
- prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) }, seen)}\n\n${prompt}`;
3595
+ prompt = `${feedbackAsk({ ...feedbackNow, text: cut(feedbackNow.text) })}\n\n${prompt}`;
3591
3596
  }
3592
3597
  let timer;
3593
3598
  try {
@@ -3770,6 +3775,12 @@ function adapterLoop(specOf, options, deps) {
3770
3775
  * the park cuts (its call held at the tool bridge) may still be streaming its answer: closed under it, its booking
3771
3776
  * would be lost and the next claim would book the turn cut, at an unknown price. Past the bound, it is that cut. */
3772
3777
  async function parkClaim(on, theGate, cause) {
3778
+ // A run that waits on no one (AdapterRunSpec.neverWaits) ends here instead: its park's entry (the ask, the budget, the
3779
+ // question) landed with it parked, and this end, in the same claim, withdraws what waits (writeEnd), books what it
3780
+ // spent, and lets nothing go parked.
3781
+ const never = specNow?.neverWaits;
3782
+ if (never !== undefined && root)
3783
+ return writeEnd(on, root, theGate, { state: "failed", summary: `${never}: it would wait on ${WAITS_ON[cause]}` }, []);
3773
3784
  await releaseHost(on);
3774
3785
  await bookingsSettled();
3775
3786
  await keepAtPark(on, cause);
@@ -3879,8 +3890,9 @@ function adapterLoop(specOf, options, deps) {
3879
3890
  ...(data.metrics !== undefined ? { metrics: data.metrics } : {}),
3880
3891
  };
3881
3892
  // A person's stop or cancel withdraws every call still waiting for its answer, in the end's own commit: the approval
3882
- // card reads answered (withdrawn), never waiting for good on a final run.
3883
- const byPerson = data.state === "stopped" || stopReason?.kind === "command";
3893
+ // card reads answered (withdrawn), never waiting for good on a final run. So does the end of a run that waits on no one
3894
+ // (neverWaits): the ask its park wrote is withdrawn with it.
3895
+ const byPerson = data.state === "stopped" || stopReason?.kind === "command" || specNow?.neverWaits !== undefined;
3884
3896
  // A cancel's calls read cancelled with their run; a stop's, withdrawn.
3885
3897
  const withdrawn = byPerson ? withdrawnAnswers(await entriesOf(theGate.journal, conversation.id, context), isoNow(), stopReason?.kind === "command" && stopReason.cancel ? "canceled" : "withdrawn") : [];
3886
3898
  // A CLI's call on the record from its gate and never sent (parked, or its runner gone before its send): its record ends
@@ -135,9 +135,13 @@ export interface AdapterSpecDeps {
135
135
  * or standalone runner's loopback is its host's other services. */
136
136
  readonly mcpLoopback?: boolean;
137
137
  /** That server's own addresses (Serve.own: where it listens, and its public address on loopback), told with
138
- * mcpLoopback: a run's loopback request (an MCP server's, its authorization server's, a pin's listing) never goes to
138
+ * mcpLoopback: a run's loopback request (an MCP server's, its authorization server's, a pin's listing, calendar_events') never goes to
139
139
  * their ports, as the server's own requests never do. */
140
140
  readonly mcpOwn?: readonly string[];
141
+ /** More own addresses, read at each claim beside mcpOwn: a standalone runner's (runner/main.ts runnerLoop), the ones
142
+ * the server kept in the store at its last start (mcp-private-hosts.ts serverOwn), so a server on any port stays
143
+ * refused. Read only when mcpLoopback is set. */
144
+ readonly mcpOwnOf?: () => Promise<readonly string[]>;
141
145
  /** A template eval's fakes, by the agent a run is of (template-eval.ts, from its case: EvalFakes). Only the eval's own
142
146
  * runner, in the eval's process, is given it (runner/beside.ts); no environment variable, flag, setting or API field
143
147
  * maps onto it. Absent, or undefined for a run: none. */
@@ -315,9 +319,20 @@ export declare function buildToolHost(opts: {
315
319
  readonly toolSettings?: unknown;
316
320
  /** The run's template eval fakes, where the eval's own runner gives them (AdapterSpecDeps.evalFakes). */
317
321
  readonly fakes?: EvalFakes;
322
+ /** The server is a local install (AdapterSpecDeps.mcpLoopback): calendar_events may read a calendar on loopback. */
323
+ readonly loopback?: boolean;
324
+ /** That server's own addresses (AdapterSpecDeps.mcpOwn): never the ports calendar_events reads on loopback. */
325
+ readonly own?: readonly string[];
318
326
  }): ToolHost;
319
327
  /** The run's web host tools (tool-list.ts `host` rows: web_fetch, web_search, monid) as HostTool[], each bound through `host` by its
320
328
  * catalog name and wrapped as the hands are (host-tools.ts hostToolOf, with `ctx`), the one binding the pi spec and the
321
329
  * CLI spec share. Each runs under the adapter loop's one gate (spec.gate) on the claim's keys (host.env), and books its
322
330
  * paid requests on the run's one ledger itself (bookedIn): they carry no settle of their own. */
323
331
  export declare function webHostTools(host: ToolHost, granted: readonly string[], ctx: HostToolCtx): Promise<HostTool[]>;
332
+ /** What a claim's MCP servers and calendar_events may reach on loopback (mcpForClaim's and buildToolHost's `loopback` and
333
+ * `own`): nothing unless mcpLoopback; else loopback, never at mcpOwn's ports nor mcpOwnOf's, read now. Read once per
334
+ * claim. */
335
+ export declare function mcpReachOf(deps: Pick<AdapterSpecDeps, "mcpLoopback" | "mcpOwn" | "mcpOwnOf">): Promise<{
336
+ loopback?: true;
337
+ own?: readonly string[];
338
+ }>;
@@ -29,7 +29,7 @@ import { PORT_PROVIDER, tieredModels, tierProvider } from "../port-models.js";
29
29
  import { promptOf, readsFiles } from "../skills.js";
30
30
  import { openRunWorkspace } from "../workspace/run-workspace.js";
31
31
  import { layOwnSkills } from "../workspace/revision-skills.js";
32
- import { COMPUTER_ROOT, runFolder } from "../workspace/paths.js";
32
+ import { COMPUTER_ROOT, recordingsFolder, runFolder } from "../workspace/paths.js";
33
33
  import { runTools, withKindTools } from "../workspace/run-tools.js";
34
34
  import { placeRunInputs } from "../uploads.js";
35
35
  import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
@@ -47,6 +47,7 @@ import { journalEntries } from "./journal-reader.js";
47
47
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
48
48
  import { claimPromotion, promotionGate, replayCallsFor, replayClaimed, replayLaid, toolFlowsFor } from "./promotion.js";
49
49
  import { pathMetrics, servedOf, workflowFirstOf } from "./workflow-first.js";
50
+ import { AUDIT_PARKED, settleAudits, withAudit } from "./audit.js";
50
51
  import { pastRunsOverStore, runPathOverStore } from "../store-reads/learning.js";
51
52
  import { specBuilt } from "./spec-holds.js";
52
53
  import { archilClaim, MOUNT_TTL_MS } from "../workspace/archil-claim.js";
@@ -209,6 +210,8 @@ export function adapterRunSpecFromLaunch(launch, run, deps, claim) {
209
210
  }
210
211
  async function adapterSpec(launch, run, deps, claim, holds) {
211
212
  const context = BACKGROUND_CONTEXT;
213
+ // What this claim may reach on loopback, read once for its MCP servers and its calendar_events alike (mcpReachOf).
214
+ const reach = await mcpReachOf(deps);
212
215
  // The runner's one redactor (the loop's, LoopDeps.redact), for every text a secret could reach: the spec's log lines
213
216
  // (a release, a workspace's end), the model route's translation and the session's model proxy. A spec built with no
214
217
  // runner around it cuts every secret the runner's env holds. It holds the keys the claim opens (below), too.
@@ -298,7 +301,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
298
301
  // words before the session opens. The seal key is the runner's own (deps.sealKey), not re-read from the environment.
299
302
  // A credential the claim opens mid-run (a GitHub App token, a saved or per_run server's) joins the run's redactor.
300
303
  const hold = (values) => cut.hold(values);
301
- const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...(deps.mcpLoopback ? { loopback: true } : {}), ...(deps.mcpOwn ? { own: deps.mcpOwn } : {}) });
304
+ const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach });
302
305
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
303
306
  holds.hold({ passed: mcp });
304
307
  // The run's computer, from the one shared claim-time function (the CLI spec takes the same): none for a runner place, a
@@ -312,8 +315,9 @@ async function adapterSpec(launch, run, deps, claim, holds) {
312
315
  // A person's stop ends the claim's waits at once: a first image pull or registration (Agent37's runs minutes) among them.
313
316
  // Whether an earlier claim made the run a computer of its own is the run's journal's to say (hadComputer): a later
314
317
  // claim's is a new one whatever ended the earlier claim (a lost runner, a server's stop, a park past its keep). The
315
- // computer a park kept, attached again, brings its mount credential with it (inheritMount): none is minted.
316
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, hadComputer: () => hadComputer(deps.journal(claim), context), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
318
+ // computer a park kept, attached again, brings its mount credential with it (inheritMount): none is minted. A
319
+ // recording of its screen (computer.record) goes in the run's recordings folder, beside its folder, said on its timeline.
320
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
317
321
  // The run's shell is its computer's (600 s) where one mounts its folder; with none, Archil's serverless exec in Mode 2
318
322
  // (295 s), and in Mode 1 none at all: no bash family, its folder being one of this server's own (run-tools.ts).
319
323
  // A desktop's or a phone's hold (the person's take-over) wraps its ports: a call made while the person holds it waits,
@@ -426,7 +430,8 @@ async function adapterSpec(launch, run, deps, claim, holds) {
426
430
  const tierRoute = tierRoutes.get(by);
427
431
  return tierRoute && tierRoute.model === id ? capModelOf(tierRoute) : undefined;
428
432
  },
429
- // What its learning runs' grades took beside it, read by every gate with its own sessions (none: it queues none).
433
+ // What its learning runs' grades and its audit's shadow took beside it, read by every gate with its own sessions
434
+ // (none: it queues none).
430
435
  ...(besideOf ? { beside: besideOf } : {}),
431
436
  // The most requests on free models it makes, capped or not (AGENTRUN_FREE_MODEL_REQUESTS).
432
437
  freeRequests: freeModelRequestsOf(deps.env),
@@ -454,13 +459,17 @@ async function adapterSpec(launch, run, deps, claim, holds) {
454
459
  // chose them, scoped as the revision's own: each provider the run's gate does not deny, held by the run's one redactor,
455
460
  // onto the tools' environment alone. The model's route was built on the revision's keys above, so a decision key never
456
461
  // becomes its model's.
457
- // A replay run lays the workflow it replays record-only (runner/promotion.ts replayLaid).
462
+ // A replay run lays only the workflow it replays (runner/promotion.ts replayLaid).
458
463
  const laidFlows = replayLaid(launch, seedLaid?.workflows ?? []);
459
464
  // The learned workflow the run starts on, before its agent's first turn, when one fits its input (workflow-first.ts),
460
465
  // chosen before the learned_workflow tool is bound, so the tool runs the text that serves. Only a promoted digest
461
466
  // serves (runner/promotion.ts: replayed on the agent's graded inputs first, or promoted on its dry run with fewer than
462
467
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
463
- // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the run asks for its revision.
468
+ // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the agent takes the run.
469
+ // The audits that finished since are written first (runner/audit.ts settleAudits): a hold they make decides this claim.
470
+ const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey };
471
+ if (launch.learning && !launch.replay && !launch.audit)
472
+ await settleAudits(audits);
464
473
  const promotion = claimPromotion({
465
474
  store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
466
475
  });
@@ -502,7 +511,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
502
511
  // An agent whose computer is a browser the claim started gets the browser tool on that one session (tools.ts).
503
512
  const claimBrowser = computer.computer?.kind === "browser" ? computer.computer.browser : undefined;
504
513
  const fakes = deps.evalFakes?.(runRow.agentId);
505
- const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
514
+ const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
506
515
  gate.askedOn(host);
507
516
  // The run's tools. The hands (read/write/edit/bash and the background tools) are the kernel registry's over the run's
508
517
  // Workspace and computer (runTools.hostTools); the gate is the adapter loop's own (spec.gate), so they run as asked.
@@ -578,8 +587,10 @@ async function adapterSpec(launch, run, deps, claim, holds) {
578
587
  // Its learning folder is where the run's place keeps it — Mode 1 the agent's folder under the data directory, Mode 2 the
579
588
  // agent's folder on THIS claim's Archil disk (the proposal is checked against the seed on the disk, never this machine's
580
589
  // local path) — so the end-of-run step reads the run's own Workspace, the one the run worked in.
581
- // A replay run asks nothing at its end: it is the promotion's, never the agent's to learn from.
582
- const endOfRun = launch.replay ? undefined : learningEndOfRun(launch, {
590
+ // A replay run or an audit's shadow run asks nothing at its end: it is the promotion's, never the agent's to learn from.
591
+ // A run the promoted workflow served first starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
592
+ // withAudit): at its end, so the shadow's cap is what the run's own left.
593
+ const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
583
594
  store: deps.store,
584
595
  data: deps.data,
585
596
  ...(deps.env ? { env: deps.env } : {}),
@@ -595,7 +606,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
595
606
  learningFolder: archil === undefined
596
607
  ? (agentId) => learningFolderOf(deps.data, agentId)
597
608
  : (agentId) => learningWorkspace({ mode: "archil", agentId, archil }),
598
- });
609
+ }), { ...audits, launch });
599
610
  return {
600
611
  adapter,
601
612
  session,
@@ -620,6 +631,9 @@ async function adapterSpec(launch, run, deps, claim, holds) {
620
631
  // The tool host's install lifecycle (its bindings' onConversation/beforeResume/beforeRelease), run by the adapter loop.
621
632
  lifecycle: life,
622
633
  agentId: runRow.agentId,
634
+ // An audit's shadow run waits on no one: where it would park (an approval, a raise of its cap, a person's answer) it
635
+ // ends at once, its row `parked` (runner/audit.ts).
636
+ ...(launch.audit ? { neverWaits: AUDIT_PARKED } : {}),
623
637
  // The run's computer as the claim made it, with the person's hold on a desktop or phone: the loop shows the hold up,
624
638
  // applies a take-over and a hand-back to it, and answers the computer call channel's rows on it.
625
639
  ...(loopComputer ? { computer: loopComputer } : {}),
@@ -842,6 +856,8 @@ export function buildToolHost(opts) {
842
856
  ...(web ? { web } : {}),
843
857
  ...(now ? { now } : {}),
844
858
  ...(email ? { emailFake: email } : {}),
859
+ ...(opts.loopback ? { calendarLoopback: true } : {}),
860
+ ...(opts.own ? { serverOwn: opts.own } : {}),
845
861
  // The run's directory and its per-claim environment: the hands come from runTools, so the non-hand tools get the run's
846
862
  // environment only.
847
863
  where: { root, work: root, ref: { id: claim.runId } },
@@ -931,3 +947,12 @@ async function bindNonHandTools(host, kind, granted, run, context, results, root
931
947
  // seam when it lands; never a second journalSessions + runCap over the one journal (the double-book we closed).
932
948
  return tools;
933
949
  }
950
+ /** What a claim's MCP servers and calendar_events may reach on loopback (mcpForClaim's and buildToolHost's `loopback` and
951
+ * `own`): nothing unless mcpLoopback; else loopback, never at mcpOwn's ports nor mcpOwnOf's, read now. Read once per
952
+ * claim. */
953
+ export async function mcpReachOf(deps) {
954
+ if (!deps.mcpLoopback)
955
+ return {};
956
+ const own = [...(deps.mcpOwn ?? []), ...((await deps.mcpOwnOf?.()) ?? [])];
957
+ return { loopback: true, ...(own.length ? { own } : {}) };
958
+ }