@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52

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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -1,4 +1,5 @@
1
1
  import type { McpCallResult, McpTool } from "@parcha/agentrun-kernel";
2
+ import { type MediaReader } from "./fal-price.js";
2
3
  import { type Workspace } from "./workspace/index.js";
3
4
  /** The longest answer the model reads whole; past it, the rest is filed in the run's work/ as lines read pages through
4
5
  * (filed-answer.ts). Within the host's result bound (HOST_RESULT_MAX_CHARS), so every harness passes it whole. */
@@ -6,11 +7,13 @@ export declare const MCP_CLIP = 60000;
6
7
  /** The longest one upstream call may take, and its first connection. */
7
8
  export declare const CALL_MS = 120000;
8
9
  export declare const CONNECT_MS = 30000;
9
- /** Each pinned server: its URL then, the granted tools as it listed them, and the prices its owner declared for them. */
10
+ /** Each pinned server: its URL then, the granted tools as it listed them, the prices its owner declared for them, and
11
+ * the meter that prices its other calls (`fal`: fal-price.ts). */
10
12
  export type McpPin = Record<string, {
11
13
  url: string;
12
14
  tools: McpTool[];
13
15
  prices?: Record<string, number>;
16
+ meter?: string;
14
17
  }>;
15
18
  /** Each granted server's URL now, and its credential's headers when that URL is the pinned one (the claim step's). */
16
19
  export type McpCredentials = Record<string, {
@@ -20,14 +23,40 @@ export type McpCredentials = Record<string, {
20
23
  unopened?: string; /** When its credential ends (ms): a token minted for the run's launch (a github_app server's), whose calls past it are refused unsent, in words. */
21
24
  expires_at?: number;
22
25
  }>;
23
- /** The servers a save pins from: each one's URL, its tools as it lists them now, and its owner's prices. */
26
+ /** The servers a save pins from: each one's URL, its tools as it lists them now, its owner's prices, and either its
27
+ * owner's toolkit for it or, for a pin carried over, the meter it was pinned with. */
24
28
  export interface McpServerSource {
25
29
  server(name: string): {
26
30
  url: string;
27
31
  tools: readonly McpTool[];
28
32
  prices?: Readonly<Record<string, number>>;
33
+ toolkit?: string | null;
34
+ meter?: string;
29
35
  } | undefined;
30
36
  }
37
+ /** A meter's price for one call: what to hold before it leaves and why (`basis`), why it can't be priced
38
+ * (`unpriceable`, in words; the hold then covers only what could be), and what it charged, by the server's reply
39
+ * (none: no reply came back). Null: unknown. */
40
+ export type McpQuote = {
41
+ holdUsd: number;
42
+ basis: string;
43
+ unpriceable?: string;
44
+ chargeOf(reply: Record<string, unknown> | undefined): number | null;
45
+ };
46
+ /** A server's keys scoped to the run (fal's submission keys, fal-price.ts falKeys): `out`, a call's arguments as they
47
+ * leave; `back`, the text of its answer or error as the model reads it, each scoped key read as the agent's own. */
48
+ export type McpKeys = {
49
+ out(tool: string, args: Record<string, unknown>): Record<string, unknown>;
50
+ back(text: string): string;
51
+ };
52
+ /** A server that prices its own calls. `ask` calls one of the server's tools with the run's credential, unbooked and
53
+ * unrecorded, and answers its raw result (none: it failed). `keys`: the keys it scopes to the run, on every call of
54
+ * the server, billed or not. */
55
+ export interface McpMeter {
56
+ keys?: McpKeys;
57
+ bills(tool: string): boolean;
58
+ quote(tool: string, args: Record<string, unknown>, ask: (tool: string, args: Record<string, unknown>) => Promise<Record<string, unknown> | undefined>, signal: AbortSignal): Promise<McpQuote>;
59
+ }
31
60
  /** The most schema nodes, and the deepest nesting, a tool's declarations are checked through: past either the tool is
32
61
  * refused, never walked further. */
33
62
  export declare const HEADER_SCAN_NODES = 10000;
@@ -75,6 +104,14 @@ export interface McpGatewayOptions {
75
104
  * throws (a store read failed, the call was stopped) refuses the call unsent too, in words, and the run goes on. Only
76
105
  * the runner's MCP claim step passes it: a github_app token whose App was disconnected or replaced. */
77
106
  beforeCall?: (server: string, signal: AbortSignal) => Promise<void>;
107
+ /** Whether the run has a spend cap: under one, a metered call that cannot be priced is refused unsent. None: it has. */
108
+ capped?: () => boolean;
109
+ /** Reads a metered job's input media, for one priced by its length. None: such a job cannot be priced. */
110
+ media?: MediaReader;
111
+ /** For tests: the clock a meter's prices are kept by. */
112
+ now?: () => number;
113
+ /** The run's id: what a meter scopes a server's keys to (McpMeter.keys). None: no key is scoped. */
114
+ run?: string;
78
115
  }
79
116
  /** A run's journal commit. */
80
117
  export type McpCommit = <T>(change: (tx: unknown) => Promise<T>) => Promise<T>;
@@ -15,9 +15,14 @@
15
15
  // - A tool its owner priced (the server's `prices`) is held at that price on the run's one ledger and booked as the
16
16
  // run's tool cost (paid-calls.ts paidStep): refused unsent when the cap cannot take it, or when no ledger books it. A
17
17
  // tool with no price runs, marked "not metered" on the run's root (TOOL_UNMETERED), outside the run's cost.
18
+ // - A server with a meter (McpMeter; fal's, fal-price.ts) prices each billed call itself before it leaves: held and
19
+ // booked the same way, at the meter's quote. A call it cannot price is refused unsent under a spend cap, and with
20
+ // none runs booked as an unknown charge. A meter's keys (McpMeter.keys; fal's submission keys on fal's own host) are
21
+ // scoped to the run on every call of its server as it leaves, and read back as the agent's own in what the model reads.
18
22
  import { randomUUID } from "node:crypto";
19
23
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
20
24
  import { TOOL_UNMETERED } from "./timeline/index.js";
25
+ import { meterFor, meterNamed } from "./fal-price.js";
21
26
  import { filedAnswer } from "./filed-answer.js";
22
27
  import { paidLedger, paidStep } from "./paid-calls.js";
23
28
  import { metaToolOf } from "./mcp-meta.js";
@@ -123,8 +128,9 @@ export function mcpPinOf(names, source) {
123
128
  const declared = mcpHeaderProblem(tool.inputSchema);
124
129
  if (declared)
125
130
  throw new Error(`The MCP tool ${name} declares a header it cannot send: ${declared}.`);
131
+ const meter = saved.meter ?? meterNamed(saved.url, saved.toolkit);
126
132
  if (!Object.hasOwn(pin, parsed.server))
127
- pin[parsed.server] = { url: saved.url, tools: [] };
133
+ pin[parsed.server] = { url: saved.url, tools: [], ...(meter ? { meter } : {}) };
128
134
  const pinned = pin[parsed.server];
129
135
  pinned.tools.push(tool);
130
136
  const price = saved.prices && Object.hasOwn(saved.prices, tool.name) ? saved.prices[tool.name] : undefined;
@@ -188,6 +194,7 @@ export function mcpGateway(options) {
188
194
  * another account connects again, so no session made as one account carries another's calls. */
189
195
  const clients = new Map();
190
196
  const pins = new Map(Object.entries(options.pin));
197
+ const meters = new Map([...pins].map(([server, pinned]) => [server, meterFor(pinned, { media: options.media, now: options.now, run: options.run })]));
191
198
  const credentials = { get: (server) => (Object.hasOwn(options.credentials, server) ? options.credentials[server] : undefined) };
192
199
  /** Each server's last HTTP status, which tells a refused credential from another failure. (An address refusal is never
193
200
  * kept here: it is read from each call's own error, since calls to one server run at once.) */
@@ -314,12 +321,15 @@ export function mcpGateway(options) {
314
321
  /** The call itself, to a server whose address is the pinned one. A gate's decision or a paid call's hold goes around
315
322
  * it, in `call` below: the one place every harness's call passes before anything is sent. */
316
323
  /** `sending`, when given, runs once the server is connected and right before the call leaves: its refusal (a text)
317
- * keeps the call from leaving. A call that never got that far (a failed connect, a stop) never ran it. */
318
- const forward = async (server, url, headers, tool, args, signal, sending, outcome = {}) => {
324
+ * keeps the call from leaving. A call that never got that far (a failed connect, a stop) never ran it. `outcome`
325
+ * takes the server's raw result, when one came back. */
326
+ const forward = async (server, url, headers, tool, args, signal, sending, outcome = {}, back) => {
319
327
  let connected = false;
320
328
  // Read at each use: a token refreshed while the call is out, and sent, is scrubbed with the one it took.
321
329
  const held = callSet(server);
322
- const clean = scrubberOf(server, hold(server, headers), held.values);
330
+ const scrubbed = scrubberOf(server, hold(server, headers), held.values);
331
+ // Every text the model reads of the call (its answer, a filed one, an error), its keys read as the agent's own.
332
+ const clean = back ? (text) => back(scrubbed(text)) : scrubbed;
323
333
  hold(server, queryOf(server));
324
334
  try {
325
335
  const upstream = await until(connect(server, url, headers), signal);
@@ -332,7 +342,9 @@ export function mcpGateway(options) {
332
342
  // The pinned definition, so the SDK mirrors its x-mcp-header parameters into Mcp-Param-* headers on a 2026-07-28
333
343
  // server, as its own listing would have it do.
334
344
  const result = (await upstream.callTool({ name: tool.name, arguments: args }, { signal, timeout: options.bounds?.callMs ?? CALL_MS, toolDefinition: { name: tool.name, inputSchema: tool.inputSchema } }));
335
- return said(await textOf(server, tool.name, result, clean), result.isError === true);
345
+ outcome.raw = result;
346
+ // A meter's own read (`quiet`): its raw result is all that is wanted, nothing filed for a model to read.
347
+ return said(outcome.quiet ? "" : await textOf(server, tool.name, result, clean), result.isError === true);
336
348
  }
337
349
  catch (error) {
338
350
  if (signal.aborted)
@@ -405,23 +417,29 @@ export function mcpGateway(options) {
405
417
  const listed = pinnedTools.find((t) => t.name === tool);
406
418
  // Whether the call left for the server: only then is it booked, at its price or as not metered.
407
419
  let went = false;
420
+ let raw;
421
+ // The server's keys scoped to the run as the call leaves (fal's submission keys): its price is read from the call as
422
+ // the agent made it.
423
+ const keys = meters.get(server)?.keys;
408
424
  const call = async (mark = async () => undefined) => {
409
425
  const outcome = {};
410
- const result = await forward(server, url, credentials.get(server)?.headers ?? {}, listed, args, signal, async () => {
426
+ const result = await forward(server, url, credentials.get(server)?.headers ?? {}, listed, keys ? keys.out(tool, args) : args, signal, async () => {
411
427
  const refused = await mark();
412
428
  went = refused === undefined;
413
429
  return refused;
414
- }, outcome);
430
+ }, outcome, keys?.back);
415
431
  // The request's own address check refused it after the mark: it never left, so nothing is booked.
416
432
  if (outcome.unsent)
417
433
  went = false;
434
+ raw = outcome.raw;
418
435
  return result;
419
436
  };
420
437
  const name = mcpToolName(server, tool);
421
438
  const label = { tool: name, charged_by: server, call: callId };
422
439
  const commit = options.commit?.();
423
440
  const price = prices && Object.hasOwn(prices, tool) ? prices[tool] : undefined;
424
- if (price === undefined) {
441
+ const meter = price === undefined && meters.get(server)?.bills(tool) ? meters.get(server) : undefined;
442
+ if (price === undefined && !meter) {
425
443
  const result = await call();
426
444
  if (commit && went)
427
445
  await record(commit, TOOL_UNMETERED, label).catch(() => undefined);
@@ -430,11 +448,24 @@ export function mcpGateway(options) {
430
448
  // On the runner's one ledger (paid-calls.ts Ledger.paid): held there at its price before it leaves and settled at its
431
449
  // price once it left (nothing when it never left), in place of this process's spend and the root's marks.
432
450
  const onLedger = paidLedger();
433
- if (onLedger) {
451
+ if (!onLedger)
452
+ return said(`${name} was not sent: this call has no run to book its price under.`, true);
453
+ if (price !== undefined) {
434
454
  const stepped = await paidStep(onLedger, callId ?? name, { name, holdUsd: price, basis: `the price its owner set for ${name}`, by: label.charged_by }, () => call(), () => (went ? price : 0));
435
455
  return "refused" in stepped ? said(stepped.refused, true) : stepped.result;
436
456
  }
437
- return said(`${name} was not sent: this call has no run to book its price under.`, true);
457
+ // The meter reads its prices from the server itself: the run's credential, no record, no booking.
458
+ const ask = async (asked, input) => {
459
+ const outcome = { quiet: true };
460
+ await forward(server, url, credentials.get(server)?.headers ?? {}, { name: asked, inputSchema: { type: "object" } }, input, signal, undefined, outcome);
461
+ return outcome.raw;
462
+ };
463
+ const quote = await meter.quote(tool, args, ask, signal);
464
+ if (quote.unpriceable && (options.capped?.() ?? true))
465
+ return said(`${name} was not sent: ${quote.unpriceable}, so a run with a spend cap can't send it. Nothing was sent.`, true);
466
+ // Settled by the server's reply; one that left and brought none back is an unknown charge.
467
+ const stepped = await paidStep(onLedger, callId ?? name, { name, holdUsd: quote.holdUsd, basis: quote.basis, by: label.charged_by }, () => call(), () => (went ? quote.chargeOf(raw) : 0));
468
+ return "refused" in stepped ? said(stepped.refused, true) : stepped.result;
438
469
  };
439
470
  const gateway = {
440
471
  servers: [...pins].map(([name, pinned]) => ({ name, tools: pinned.tools })),
@@ -54,7 +54,7 @@ export async function pinFirst(revision, deps) {
54
54
  }
55
55
  let pin;
56
56
  try {
57
- pin = mcpPinOf(granted, { server: (name) => { const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices }; } });
57
+ pin = mcpPinOf(granted, { server: (name) => { const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices, toolkit: listing.toolkit }; } });
58
58
  }
59
59
  catch {
60
60
  return undefined;
@@ -227,6 +227,7 @@ export declare class McpServersOverStore {
227
227
  reason?: string;
228
228
  })[];
229
229
  prices: McpPrices;
230
+ toolkit: string | null;
230
231
  } | undefined>;
231
232
  /** `listing`, and when it is refused as a server that signs in with OAuth (auth_required, `auth: oauth`), whether that
232
233
  * sign-in can start with no Client ID entered (`details.oauth.registration`, McpSignIns.registration), so the console
@@ -218,10 +218,11 @@ export class McpServersOverStore {
218
218
  const row = await this.store.mcp.server(name);
219
219
  if (!row)
220
220
  return undefined;
221
+ const { toolkit } = await this.sourceOf(row);
221
222
  const url = new URL(row.url);
222
223
  const pinned = (tools) => {
223
224
  const listed = marked(row.url, { tools });
224
- return { url: row.url, tools: listed.tools, prices: pricesListed((row.prices ?? undefined), listed.tools) };
225
+ return { url: row.url, tools: listed.tools, prices: pricesListed((row.prices ?? undefined), listed.tools), toolkit };
225
226
  };
226
227
  const send = await this.reached(row.auth, url, stop);
227
228
  try {
@@ -0,0 +1,2 @@
1
+ /** The length of the media file `bytes`, in seconds; undefined when it can't be read from them. */
2
+ export declare function mediaSeconds(bytes: Uint8Array): number | undefined;
@@ -0,0 +1,136 @@
1
+ // A media file's length in seconds, read from its bytes alone: an ISO file's movie header (mp4, m4a, mov), a WAV's data
2
+ // chunk over its byte rate, an MP3's frame count (Xing, Info or VBRI) or, with none, its frames walked one by one. Pure: no decoder, nothing read past the bytes given. Undefined for anything else, or a file cut short of the
3
+ // header its length is in.
4
+ const tag = (b, at, text) => at >= 0 && b.length >= at + text.length && [...text].every((c, i) => b[at + i] === c.charCodeAt(0));
5
+ const u32 = (b, at) => (b[at] * 0x1000000) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
6
+ const u32le = (b, at) => b[at] + (b[at + 1] << 8) + (b[at + 2] << 16) + b[at + 3] * 0x1000000;
7
+ const length = (seconds) => (Number.isFinite(seconds) && seconds > 0 ? seconds : undefined);
8
+ /** The boxes of an ISO file between `from` and `to`: each one's type and where its body starts and ends. A box that runs
9
+ * past `to`, or is smaller than its own header, ends the walk. */
10
+ function* boxes(b, from, to) {
11
+ for (let at = from; at + 8 <= to;) {
12
+ let size = u32(b, at);
13
+ let head = 8;
14
+ if (size === 1) {
15
+ if (at + 16 > to)
16
+ return;
17
+ size = u32(b, at + 8) * 0x100000000 + u32(b, at + 12);
18
+ head = 16;
19
+ }
20
+ else if (size === 0)
21
+ size = to - at;
22
+ if (size < head || at + size > to)
23
+ return;
24
+ yield { type: String.fromCharCode(b[at + 4], b[at + 5], b[at + 6], b[at + 7]), start: at + head, end: at + size };
25
+ at += size;
26
+ }
27
+ }
28
+ /** An ISO file's length: its moov's mvhd, duration over timescale (64-bit in version 1). */
29
+ function isoSeconds(b) {
30
+ for (const top of boxes(b, 0, b.length)) {
31
+ if (top.type !== "moov")
32
+ continue;
33
+ for (const { type, start, end } of boxes(b, top.start, top.end)) {
34
+ if (type !== "mvhd")
35
+ continue;
36
+ const wide = b[start] === 1;
37
+ if (end - start < (wide ? 32 : 20))
38
+ return undefined;
39
+ const scale = u32(b, start + (wide ? 20 : 12));
40
+ const ticks = wide ? u32(b, start + 24) * 0x100000000 + u32(b, start + 28) : u32(b, start + 16);
41
+ return scale > 0 ? length(ticks / scale) : undefined;
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+ /** A WAV's length: its data chunk's bytes (those in the file, when it states more) over its fmt chunk's byte rate. */
47
+ function wavSeconds(b) {
48
+ let rate;
49
+ for (let at = 12; at + 8 <= b.length;) {
50
+ const size = u32le(b, at + 4);
51
+ if (tag(b, at, "fmt ")) {
52
+ if (at + 20 > b.length)
53
+ return undefined;
54
+ rate = u32le(b, at + 16);
55
+ }
56
+ else if (tag(b, at, "data"))
57
+ return rate ? length(Math.min(size, b.length - at - 8) / rate) : undefined;
58
+ at += 8 + size + (size % 2);
59
+ }
60
+ return undefined;
61
+ }
62
+ // MPEG audio, by version bits (3: MPEG-1, 2: MPEG-2, 0: MPEG-2.5) and layer bits (3: I, 2: II, 1: III).
63
+ const RATES = { 3: [44_100, 48_000, 32_000], 2: [22_050, 24_000, 16_000], 0: [11_025, 12_000, 8_000] };
64
+ const KBPS_V1 = {
65
+ 3: [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
66
+ 2: [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384],
67
+ 1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
68
+ };
69
+ const KBPS_V2 = {
70
+ 3: [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256],
71
+ 2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
72
+ 1: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
73
+ };
74
+ /** The MPEG audio frame header at `at`, or undefined when those four bytes are none. */
75
+ function frameAt(b, at) {
76
+ if (at + 4 > b.length || b[at] !== 0xff || (b[at + 1] & 0xe0) !== 0xe0)
77
+ return undefined;
78
+ const version = (b[at + 1] >> 3) & 3;
79
+ const layer = (b[at + 1] >> 1) & 3;
80
+ const rate = RATES[version]?.[(b[at + 2] >> 2) & 3];
81
+ const kbps = (version === 3 ? KBPS_V1 : KBPS_V2)[layer]?.[b[at + 2] >> 4];
82
+ if (!rate || !kbps)
83
+ return undefined;
84
+ const padding = (b[at + 2] >> 1) & 1;
85
+ const mono = b[at + 3] >> 6 === 3;
86
+ const samples = layer === 3 ? 384 : layer === 2 || version === 3 ? 1152 : 576;
87
+ const bytes = layer === 3 ? (Math.floor((12 * kbps * 1000) / rate) + padding) * 4 : Math.floor(((samples / 8) * kbps * 1000) / rate) + padding;
88
+ return { rate, samples, bytes, side: version === 3 ? (mono ? 17 : 32) : mono ? 9 : 17 };
89
+ }
90
+ /** The furthest past a tag an MP3's first frame is looked for. */
91
+ const SYNC_SCAN = 64 * 1024;
92
+ /** Every frame's samples over its rate, from the frame at `at` to `end`. A last frame cut short ends it; bytes that stop
93
+ * being frames before that give no length, since a bitrate guessed for them could read the file short. */
94
+ function walkedSeconds(b, at, end) {
95
+ let seconds = 0;
96
+ while (at < end) {
97
+ const frame = frameAt(b, at);
98
+ if (!frame)
99
+ return undefined;
100
+ if (at + frame.bytes > end)
101
+ break;
102
+ seconds += frame.samples / frame.rate;
103
+ at += frame.bytes;
104
+ }
105
+ return length(seconds);
106
+ }
107
+ /** An MP3's length: its first frame's Xing, Info or VBRI frame count times a frame's samples over its rate; with none,
108
+ * its frames walked one by one (a variable bitrate needs no header), the first taken only when another follows it. */
109
+ function mp3Seconds(b) {
110
+ let start = 0;
111
+ // An ID3v2 tag: its size is four 7-bit bytes, with a 10-byte footer when flagged.
112
+ if (tag(b, 0, "ID3") && b.length >= 10)
113
+ start = 10 + ((b[6] & 0x7f) << 21) + ((b[7] & 0x7f) << 14) + ((b[8] & 0x7f) << 7) + (b[9] & 0x7f) + (b[5] & 0x10 ? 10 : 0);
114
+ const end = b.length - (tag(b, b.length - 128, "TAG") ? 128 : 0);
115
+ for (let at = start; at < Math.min(end, start + SYNC_SCAN); at++) {
116
+ const frame = frameAt(b, at);
117
+ if (!frame)
118
+ continue;
119
+ const xing = at + 4 + frame.side;
120
+ if ((tag(b, xing, "Xing") || tag(b, xing, "Info")) && xing + 12 <= b.length && b[xing + 7] & 1)
121
+ return length((u32(b, xing + 8) * frame.samples) / frame.rate);
122
+ if (tag(b, at + 36, "VBRI") && at + 54 <= b.length)
123
+ return length((u32(b, at + 50) * frame.samples) / frame.rate);
124
+ if (at + frame.bytes === end || frameAt(b, at + frame.bytes))
125
+ return walkedSeconds(b, at, end);
126
+ }
127
+ return undefined;
128
+ }
129
+ /** The length of the media file `bytes`, in seconds; undefined when it can't be read from them. */
130
+ export function mediaSeconds(bytes) {
131
+ if (tag(bytes, 4, "ftyp") || tag(bytes, 4, "moov") || tag(bytes, 4, "mdat") || tag(bytes, 4, "free") || tag(bytes, 4, "wide"))
132
+ return isoSeconds(bytes);
133
+ if (tag(bytes, 0, "RIFF") && tag(bytes, 8, "WAVE"))
134
+ return wavSeconds(bytes);
135
+ return mp3Seconds(bytes);
136
+ }
package/dist/openapi.js CHANGED
@@ -272,8 +272,13 @@ const COST_WORDS = {
272
272
  unpriced: { type: "integer", minimum: 0, description: "Beside `so_far_usd`: how many of its charges have no known figure, or count at their hold." },
273
273
  upper_bound: { const: true, description: "`usd` counts a request a crash or a stop cut at the hold its cap kept for it: the most it can have cost." },
274
274
  };
275
+ /** Which attempt at a turn a part of a run's usage was made in (store run_attempts), and whether it is billable. */
276
+ const ATTEMPT_FIELDS = {
277
+ attempt: { type: ["integer", "null"], minimum: 1, description: "The attempt at its turn this was made in: 1 the turn's first, 2 its first redo, and so on. A turn is redone when the claim working it was cut (its runner drained for a deploy, crashed or lost its lease, or the turn was tried again) and another claim worked it again. Null for a run whose claims kept no attempt (one from before this server kept them).", "x-agentrun-serve": "runusage/5" },
278
+ billable: { type: "boolean", description: "False for model requests an attempt sent and never finished (cut in flight, or cut off by a crash) when a later attempt worked its turn again: that attempt sends them again, so their cost is the infrastructure's (the run's `infra_usd`), not the task's. True for every other part: an answered request, a paid call, browser and computer time, which the attempt that takes a turn over reuses, and every part of a run whose claims kept no attempt. Data only: `usd`, `total` and the run's `cost.usd` hold it either way, and nothing is charged differently by it.", "x-agentrun-serve": "runusage/5" },
279
+ };
275
280
  const RUN_USAGE_LINE = {
276
- type: "object", additionalProperties: false, required: ["meter", "model", "provider", "charged_by", "quantity", "unit", "basis", "usd"],
281
+ type: "object", additionalProperties: false, required: ["meter", "model", "provider", "charged_by", "quantity", "unit", "basis", "attempt", "billable", "usd"],
277
282
  properties: {
278
283
  meter: { enum: ["tokens", "tools", "browser_time", "compute_time"], description: "`tokens`: model requests, by model. `tools`: paid tool calls, by who charged for them; a workflow decision Parallel answered on its own API (this server's PARALLEL_API_KEY) is one, on the `parallel` line, never on `tokens`. `browser_time`: browser session time, by browser provider. `compute_time`: the time of the computers the run made, by provider and resource (`resource`, a GPU's `gpu_type`), priced by the operator's per-resource settings; sum a provider's lines for its compute figure.", "x-agentrun-serve": "runusage/5" },
279
284
  model: { type: ["string", "null"], description: "On `tokens`: the model the requests were sent on, as the run's booking names it (a workflow decision's model too, but for a decision Parallel charged, which is on the `parallel` `tools` line). One line per model and route: the same model reached two ways is two lines. Null on the other meters, and when the record names none." },
@@ -282,6 +287,7 @@ const RUN_USAGE_LINE = {
282
287
  quantity: { type: ["number", "null"], minimum: 0, description: "In `unit`, as measured: never rounded to a billing increment, never topped up to a minimum. On `tokens`, the requests' input, cache read, cache write and output tokens as each reported them (a workflow decision's as its receipt does; a request that reported none is in `unmetered_requests`, in no token); on `tools`, the charges booked, one per paid call (a decision Parallel charged is one); on `browser_time`, the seconds this server's clock charged the provider's sessions for, its minimum per session included as the browser charged it; on `compute_time`, every second of every such computer of the run's times its figure (vCPUs, GiB of memory, GPUs, or GB of disk over a 730-hour month), a computer still open counted up to `measured_to`. Null when nothing measured it, or when a computer's figure is unknown (its provider said none and its create asked none)." },
283
288
  unit: { enum: ["token", "call", "second", "vcpu_second", "gib_second", "gpu_second", "gb_month"] },
284
289
  basis: { enum: ["reported", "estimate", "unpriced"], description: "How `usd` was reached. On `tokens`, as the run's `cost.basis` is, over the line's requests alone: `reported` when every request priced had its gateway's or provider's own figure, `estimate` when any was priced from a price table, `unpriced` when none was priced. On `tools`, `reported` when every charge with a figure is the provider's own (monid's answer says what it charged), `estimate` when any is a price this server holds (an MCP tool's saved price, Parallel's, a Parallel decision's list price), `unpriced` when none has a figure. On `browser_time`, `estimate` when any charge has a figure (the provider's price per hour on this server's clock, never its invoice), else `unpriced`. On `compute_time`, `estimate` when the run's ledger booked any of it at the operator's price (or its provider bills nothing, at $0), else `unpriced` (no price set for the resource, or its figure unknown): its time ran outside the run's cap, and `usd` is null." },
290
+ ...ATTEMPT_FIELDS,
285
291
  usd: { type: ["number", "null"], minimum: 0, description: "The line's cost on this server, as booked, joined by the rule `cost.usd` is (float noise rounded off at 1e-12). Null when a charge of it is unknown: never $0 for unknown." },
286
292
  ...COST_WORDS,
287
293
  requests: { type: "integer", minimum: 0, description: "On `tokens`: the model requests booked." },
@@ -298,7 +304,7 @@ const RUN_USAGE_LINE = {
298
304
  /** One browser session on GET /runs/{run_id}/usage (browser-sessions.ts). */
299
305
  const BROWSER_SESSION = {
300
306
  type: "object", additionalProperties: false,
301
- required: ["provider", "tag", "provider_session_id", "started_at", "ended_at", "release_reason", "charged_seconds", "provider_record", "provider_record_status"],
307
+ required: ["provider", "tag", "provider_session_id", "started_at", "ended_at", "release_reason", "charged_seconds", "provider_record", "provider_record_status", "attempt", "billable"],
302
308
  properties: {
303
309
  provider: { type: "string", description: "The browser provider, as the `browser_time` line's `provider` names it." },
304
310
  tag: { type: "string", description: "The run's own name for the session, the same on every read." },
@@ -317,12 +323,13 @@ const BROWSER_SESSION = {
317
323
  },
318
324
  },
319
325
  provider_record_status: { enum: ["read", "not_offered", "not_found", "failed", "no_session", null], description: "What came of reading the provider's record: `read`; `not_offered`, the provider keeps none this server reads; `not_found`, the provider did not know the session; `failed`, the read failed or timed out; `no_session`, none was made. Null while the session's end is not recorded." },
326
+ ...ATTEMPT_FIELDS,
320
327
  },
321
328
  };
322
329
  /** One computer a run made on GET /runs/{run_id}/usage (run-usage.ts computerIntervalsOf, store computer_intervals). */
323
330
  const COMPUTER_INTERVAL = {
324
331
  type: "object", additionalProperties: false,
325
- required: ["provider", "provider_id", "kind", "gpu", "cpus", "memory_mb", "disk_gb", "started_at", "ended_at", "kept", "booked_seconds"],
332
+ required: ["provider", "provider_id", "kind", "gpu", "cpus", "memory_mb", "disk_gb", "started_at", "ended_at", "kept", "booked_seconds", "attempt", "billable"],
326
333
  properties: {
327
334
  provider: { type: "string", description: "The computer provider, as this server's registry names it (the agent's computer setting's `provider`: `docker`, `e2b`, `daytona`, ...)." },
328
335
  provider_id: { type: "string", description: "The provider's own id for the computer, by which its console, its API and its invoice find it." },
@@ -339,10 +346,11 @@ const COMPUTER_INTERVAL = {
339
346
  ended_at: { type: ["string", "null"], format: "date-time", description: "When the provider's delete of the computer answered ok, on this server's clock. Null while none did: the computer may still be running (a run that ended with one open left it behind), or its delete failed or its answer is unknown. Never a guessed end." },
340
347
  kept: { type: "boolean", description: "The run's park kept the computer past its claim, for the person's answer (it is deleted once its keep's time passes, or at the run's end)." },
341
348
  booked_seconds: { type: "number", minimum: 0, description: "How much of the computer's time a claim of the run held and booked on the run's ledger. The rest of its life is time no claim held (`unheld_quantity` on its `compute_time` lines). 0 for one whose provider has no price set, or that bills nothing.", "x-agentrun-serve": "runusage/4" },
349
+ ...ATTEMPT_FIELDS,
342
350
  },
343
351
  };
344
352
  const RUN_USAGE = {
345
- type: "object", additionalProperties: false, required: ["run_id", "ended_at", "currency", "total", "lines", "browser_sessions", "computer_intervals", "reason"],
353
+ type: "object", additionalProperties: false, required: ["run_id", "ended_at", "currency", "total", "lines", "browser_sessions", "computer_intervals", "infra_usd", "reason"],
346
354
  properties: {
347
355
  run_id: ref("schemas/Id"),
348
356
  ended_at: { type: ["string", "null"], format: "date-time", description: "When the run ended: the moment the lines cover. Null while it is at work. The lines change only while the run works, and a follow-up can open an ended run again (a trigger's often does); its next end is a later one. Keep `ended_at` beside the lines: a later read with another `ended_at`, or null, means the run moved since. `run.ended` fires at each end." },
@@ -354,6 +362,7 @@ const RUN_USAGE = {
354
362
  lines: { type: ["array", "null"], items: RUN_USAGE_LINE, description: "`tokens` lines first, then `tools`, then `browser_time`, then `compute_time`, each by its model, charger or provider (`compute_time` then by resource). A meter the run used nothing of has no line. Null when the server can't split the run (`reason`)." },
355
363
  browser_sessions: { type: ["array", "null"], items: BROWSER_SESSION, description: "One record per browser session the run opened, in the order it opened them, for matching `browser_time` to the provider's own records and invoice by its session id. Empty for a run that opened none. Null exactly when `lines` is. Its words are cut of this server's secrets and the run's sign-ins, as the lines' names are.", "x-agentrun-serve": "runusage/2" },
356
364
  computer_intervals: { type: ["array", "null"], items: COMPUTER_INTERVAL, description: "One record per computer the run made through its provider (a sandbox, a desktop, a phone), by when each was made: how long each lived for the run, one left running after it (`ended_at` null), and the provider's own id to match its invoice by. Not the agent's own persistent computer, a paired computer, or a browser's sessions (those are `browser_sessions`). Their time is on the `compute_time` lines. Empty for a run that made none (or one made before this server kept them). Null exactly when `lines` is. Its words are cut of this server's secrets and the run's sign-ins, as the lines' names are.", "x-agentrun-serve": "runusage/3" },
365
+ infra_usd: { type: ["number", "null"], minimum: 0, description: "What the infrastructure's own redo cost: the sum of the lines that are not `billable` (requests a cut attempt never finished and a later attempt sent again, after a deploy's drain, a crash, a lost lease or a retry). 0 for a run none of whose attempts left one. A request cut in flight has no known cost, so a run that has one reads null here: never a guess. Inside `total` and `cost.usd`, never beside them: data to compare, nothing charged differently. Null exactly when `lines` is, and when one such line's cost is unknown.", "x-agentrun-serve": "runusage/5" },
357
366
  reason: { enum: ["running", "not_booked", "reopened", null], description: "Why `lines` is null: `running`, the run is at work and its booking still moves; `not_booked`, its figure is not its booking's (an imported run's, a native or SDK run's harness figure, a CLI run whose model requests went past its model proxy); `reopened`, a learning run a follow-up opened again, whose `cost.usd` is its first round's and whose booking can't be split by round. Null with lines." },
358
367
  },
359
368
  };
@@ -820,6 +829,7 @@ const LEARNING_REASON = {
820
829
  "`cancelled`: a person cancelled the run. `crashed`: the run's process went. `reflect_failed`: the compile turn ended on an error.",
821
830
  "`empty`: the compile turn kept no workflow and the owner gave no correction, or the run was not asked its compile turn because its only tool work was its learned workflows, each answering, with nothing said after its first message (its `detail` says so). `checker`: the checks (or the workflow's dry run) refused it, or the owner's correction would pass corrections.md's cap, and nothing was written to git.",
822
831
  "`use`: the run was started with `learning: \"use\"`: it started from what its agent learned and keeps nothing, so it was never asked its end-of-run turn.",
832
+ "`reset`: the run read what its agent learned before a reset of the agent's learning (DELETE /v2/agents/{agent_id}/learning), so nothing it learned is kept and it was never asked its end-of-run turn.",
823
833
  ].join(" "),
824
834
  };
825
835
  // ---- learning/1: what a person sees and controls of an agent's learning (learning-routes.ts) ---------------------------
@@ -1073,6 +1083,10 @@ const COMPUTERS_VIEW = closed({
1073
1083
  groups: { type: "array", items: { type: "string" }, description: "The capability groups the kind needs, then those it brings when a provider declares them." },
1074
1084
  tools: { type: "array", items: { type: "string" }, description: "The model's tools the kind brings, by name." },
1075
1085
  settings: { type: "array", items: { type: "string" }, description: "The fields an agent's computer of this kind may set beside its kind and provider; none for kind none. Whether a provider offers a value is its own (images, persistent, gpu)." },
1086
+ record: {
1087
+ ...closedWith({ available: { type: "boolean", description: "Whether an agent's computer of this kind may set `record: true` here: the kind records (a desktop, a phone or a browser) and this server has ffmpeg on its PATH, read at each call." } }, { why: { type: "string", description: "Why not, in plain words: the kind has no screen to record, or this server has no ffmpeg. Absent when `available`." } }),
1088
+ description: "Whether a run of this kind can record a video of its screen on this server (an agent's `computer.record`), and why not.",
1089
+ },
1076
1090
  providers: { type: "array", items: COMPUTER_PROVIDER, description: "The providers that serve the kind." },
1077
1091
  }, {
1078
1092
  why: { type: "string", description: "Why it is not offered." },
@@ -1348,7 +1362,7 @@ const TEMPLATE = closed({
1348
1362
  parameters: { type: "object", description: "What apply takes in `parameters`, put where the package writes `${parameters.<name>}`: the package's `parameters`, compiled as `inputs` are, a closed JSON Schema object (no properties when it names none). Apply fills a blank one with its `default` and checks them as a run's input is checked." },
1349
1363
  input_schema: { type: ["object", "null"], description: "What each run of its agent takes as `input`: the package's `inputs`, compiled to the JSON Schema apply sets as the agent's `input_schema`. Null: the package names none, and a run takes `{content}`." },
1350
1364
  secrets: { type: "array", items: { type: "string" }, description: "The keys this server must have, by variable name (a saved key counts), before apply makes anything." },
1351
- budget: { type: ["object", "null"], additionalProperties: false, required: ["per_run_usd"], properties: { per_run_usd: { type: "number" } }, description: "Each run's limit: per_run_usd, its spend cap (the agent's max_cost_usd), required of a package with triggers." },
1365
+ budget: { type: ["object", "null"], additionalProperties: false, required: ["per_run_usd"], properties: { per_run_usd: { type: "number" }, max_requests: { type: "integer", minimum: 1, "x-agentrun-serve": "maxrequests/1" } }, description: "Each run's limits: per_run_usd, its spend cap (the agent's max_cost_usd), required of a package with triggers; max_requests, when given, the most requests on free models it makes (the agent's max_requests), under the server's own limit." },
1352
1366
  learning: { oneOf: [{ type: "boolean" }, { type: "object" }], description: "The agent's `learning` as apply sets it, as an agent definition takes it: true, false, or the loop's settings (kyb's `{agree_on: [\"verdict.decision\"]}`: its check and audit compare two answers on the verdict's decision alone)." },
1353
1367
  approvals_default: { enum: ["ask", "never"], description: "What the package recommends for the agent's approvals: `ask`, the agent asks its person before a tool runs; `never`, it runs unattended (a template whose job runs on triggers). Deny settings and pins hold either way: a pinned write can only go where its pin says." },
1354
1368
  triggers: { type: "array", items: { type: "object" }, description: "The triggers apply makes on its agent: POST /triggers bodies with no agent_id, placeholders unfilled. A trigger's `enabled` may be `${parameters.<name>}`, a boolean parameter with a default: apply makes it on or off by that value." },
@@ -1388,10 +1402,9 @@ const TEMPLATE_APPLIED = closedWith({
1388
1402
  agent_id: { type: "string", description: "The agent made, or the one updated (GET /agents/{agent_id})." },
1389
1403
  revision_version: { type: "integer", minimum: 1, description: "The number of the agent's revision this apply wrote, its current one now (its `definition.version`): 1 for an agent it made; on an update with agent_id, the new revision's; on one that changed nothing (`agent_change` unchanged), the current revision it kept." },
1390
1404
  agent_change: { enum: ["made", "updated", "unchanged"], description: "What the apply did to the agent: `made` it (201); `updated` it, a new revision written (an update with agent_id); or left it `unchanged`: an update whose package and parameters its current revision already holds writes no revision, and `revision_version` is that current one. Its triggers are reconciled either way (`triggers`)." }, servers: { type: "object", additionalProperties: { type: ["string", "null"] }, description: "The saved MCP server each of the package's toolkits runs on, by toolkit; null: none here matches it (said under `mcp.<toolkit>`)." },
1391
- trigger_ids: { type: "array", items: { type: "string" }, description: "Its triggers, in the package's order (GET /triggers/{trigger_id})." },
1392
1405
  triggers: {
1393
1406
  type: "array",
1394
- description: "The same triggers, in the same order, each as the apply left it: every one it made or kept, of any kind. A trigger the apply skipped (said in `warnings`) is not here.",
1407
+ description: "Its triggers, in the package's order, each as the apply left it (GET /triggers/{trigger_id}): every one it made or kept, of any kind. A trigger the apply skipped (said in `warnings`) is not here, so a package trigger is found by its `name`, never by its index in the package.",
1395
1408
  items: closed({
1396
1409
  trigger_id: { type: "string" },
1397
1410
  name: { type: "string", description: "Its name: the package's name for it." },
@@ -1404,7 +1417,7 @@ const TEMPLATE_APPLIED = closedWith({
1404
1417
  }, {
1405
1418
  webhook_secrets: {
1406
1419
  type: "array",
1407
- description: "Each webhook trigger it made, in trigger_ids' order; absent when it made none. Each carries its secret's metadata (`secret`) and, in the first answer to the owner's signed-in session alone, its `signing_secret`, shown this once as POST /triggers shows it; to the API token, or on a replay under the same Idempotency-Key, `secret_set` and `note` in its place.",
1420
+ description: "Each webhook trigger it made, in `triggers`' order; absent when it made none. Each carries its secret's metadata (`secret`) and, in the first answer to the owner's signed-in session alone, its `signing_secret`, shown this once as POST /triggers shows it; to the API token, or on a replay under the same Idempotency-Key, `secret_set` and `note` in its place.",
1408
1421
  items: closedWith({ trigger_id: { type: "string" }, secret: { ...ref("schemas/SecretMeta"), description: "Its signing secret's metadata, named `trigger:<id>`. Never the value." } }, {
1409
1422
  signing_secret: { type: "string", pattern: "^whsec_[A-Za-z0-9+/]+={0,2}$", description: "Its signing secret, shown this once: in the apply's first answer to the owner's signed-in session alone." },
1410
1423
  secret_set: { const: true },
@@ -1579,6 +1592,8 @@ const REPLAY_OUTCOMES = closed({
1579
1592
  failed: { ...COUNT, description: "Replay runs a step failed in, or still at work past the replay's deadline: no evidence either way, never scored." },
1580
1593
  skipped_write: { ...COUNT, description: "Replay runs stopped at a write (an MCP tool its server does not mark read-only, or any tool not known to read) that the graded run's recording does not have with the same arguments: a replay never runs a write, so these are neither scored nor wrong; a replay whose every input was skipped holds the revision." },
1581
1594
  }, "How many of its replay runs ended each way: what each run did.");
1595
+ /** One input a check did not agree on (learn/promote.ts CheckDisagreement). */
1596
+ const CHECK_DISAGREEMENT = closedWith({ run: { type: "string" }, input: { type: "string", description: "The run's input, as text or JSON, cut at 1200 characters." }, agent: NULL_STRING }, { draft: { type: "string", description: "What it answered instead." }, escalated: { type: "string", description: "Why it handed the input back." }, failed: { const: true, description: "A step failed on it, or its run was still at work past the check's deadline, or never created by then." }, differs_on: { type: "string", description: "When `grader` compared it: the decision the two answers differ on, in the fast model's words, or why its verdict could not be had (\"the comparison could not be read\", \"the cap held the comparison\", or \"the comparison read an earlier answer\" when the agent's run answered again after it was compared). Cut at 1200 characters." } });
1582
1597
  /** A compiled draft's one check (learn/promote.ts CheckRecord): its bar while it replays, its numbers once decided. */
1583
1598
  const PROMOTION_CHECK = closedWith({
1584
1599
  compile_after: { type: "integer", minimum: 1, description: "The agent definition's `learning.compile_after` when the check began: how many of the agent's newest completed runs it read inputs from." },
@@ -1596,10 +1611,20 @@ const PROMOTION_CHECK = closedWith({
1596
1611
  outcomes: { ...REPLAY_OUTCOMES, description: "How each input it ran on came out, one per input: a replay run never created, or not ended, by the check's deadline is `failed`." },
1597
1612
  unstarted: { ...COUNT, minimum: 1, description: "How many of its replay runs were never created by the check's deadline (the server stopped after reserving them, say), each a `failed` input. Left out when none. Every one: its replay's read is `failed`." },
1598
1613
  skipped_tools: SKIPPED_TOOLS,
1599
- disagreements: { type: "array", items: closedWith({ run: { type: "string" }, input: { type: "string", description: "The run's input, as text or JSON, cut at 1200 characters." }, agent: NULL_STRING }, { draft: { type: "string", description: "What it answered instead." }, escalated: { type: "string", description: "Why it handed the input back." }, failed: { const: true, description: "A step failed on it, or its run was still at work past the check's deadline, or never created by then." }, differs_on: { type: "string", description: "When `grader` compared it: the decision the two answers differ on, in the fast model's words, or why its verdict could not be had (\"the comparison could not be read\", \"the cap held the comparison\", or \"the comparison read an earlier answer\" when the agent's run answered again after it was compared). Cut at 1200 characters." } }), description: "On a hold: each input it did not agree on, which the agent's next run reads as data in its one recompile." },
1614
+ disagreements: { type: "array", items: CHECK_DISAGREEMENT, description: "On a hold: each input it did not agree on, which the agent's next run reads as data in its one recompile." },
1600
1615
  stopped: { const: true, description: "The recompile's check held it too, or there was nothing to check it on (no input of the agent's it takes, or every input skipped at a write: `n` 0, `reason` starting \"nothing to check it on\", which asks no recompile): nothing compiles again until a hold or its owner acts; the agent keeps the runs." },
1601
- released: { type: "integer", minimum: 1, description: "A connected agent's check (`via` sdk): how many of its reserved native turns could not be its baseline (cancelled or failed, a learned workflow in the turn, redacted evidence, no shadow report, or a shadow that did not answer) and were given back to wait for the next turn the draft takes. The fifth stops it with nothing checked. Left out when none." },
1616
+ released: { type: "integer", minimum: 1, description: "A connected agent's check (`via` sdk): how many of its reserved native turns in a row since the last one checked could not be its baseline (failed, a learned workflow in the turn, redacted evidence, no shadow report, or a shadow that did not answer; a cancel never counts) and were given back to wait for the next turn the draft takes. The fifth holds it, never promoted, and the next compile's revision is checked afresh. Left out when none." },
1602
1617
  fresh_reads: { type: "integer", minimum: 1, description: "A connected agent's check (`via` sdk): how many fresh read-only calls its shadow made where the native turn's recording had no result (the host's opt-in `shadowReadFallback`). Left out when every call was answered from the recording." },
1618
+ turns: { ...closedWith({
1619
+ n: { ...COUNT, description: "The native turns checked so far: each whose shadow answered or handed back, and each the backend never completed within an hour (`failed`)." },
1620
+ agreed: { ...COUNT, description: "How many of them the shadow answered alone with the native answer." },
1621
+ alone: { ...COUNT, description: "How many of them the shadow answered alone." },
1622
+ of: { type: "array", items: { type: "string" }, description: "The agent's runs of those turns, newest first." },
1623
+ outcomes: { ...REPLAY_OUTCOMES, description: "How each turn came out, one per turn." },
1624
+ }, {
1625
+ disagreements: { type: "array", items: CHECK_DISAGREEMENT, description: "Each turn it did not agree on." },
1626
+ fresh_reads: { type: "integer", minimum: 1, description: "The fresh read-only calls its shadows made, as `fresh_reads` counts them." },
1627
+ }), description: "A connected agent's check (`via` sdk) still collecting native turns. A check decides once, on `compile_after` inputs, so this one waits for that many turns, the agent answering each, then decides on all of them. Left out once decided, and on a server replay; a check stopped or set aside before it held them keeps the turns it had." },
1603
1628
  });
1604
1629
  const PROMOTION = closedWith({
1605
1630
  workflow: { type: "string" },
@@ -1613,7 +1638,7 @@ const PROMOTION = closedWith({
1613
1638
  inputs: { type: "array", items: { type: "string" }, description: "On a replaying record: the graded run each of `runs` replays, in the same order. Its runs are reserved before they are created; one not created a few minutes on is created by the next claim." },
1614
1639
  replay_id: { type: "string", description: "The replay's id, on its replaying record and the one that decided it: GET .../revisions/{digest}/replays/{replay_id} reads it, whether a run's claim or its owner started it." },
1615
1640
  commit: { type: "string", description: "The learning commit whose workflow.json is this revision's text: what it serves from as the champion while a newer revision replays." },
1616
- via: { const: "sdk", description: "A connected (SDK) agent's check, on its reservation and on the record that decides it: its one run (`runs`) is the agent's own native turn, checked by the caller's shadow, not a replay run. A `replaying` one with no `runs` waits for the next native turn the draft takes. A turn the backend never completes within an hour is one failed input. Left out for a server replay." },
1641
+ via: { const: "sdk", description: "A connected (SDK) agent's check, on each reservation and on the record that decides it: its one run (`runs`) is the agent's own native turn reserved now, checked by the caller's shadow, not a replay run. A `replaying` one with no `runs` waits for the next native turn the draft takes. It collects its checked turns (`check.turns`) until it holds `check.compile_after` of them, then decides once on all of them, as a server replay decides once on its inputs. A turn the backend never completes within an hour is one failed input. Left out for a server replay." },
1617
1642
  audit: closedWith({
1618
1643
  window: { type: "integer", minimum: 1, description: "The definition's `learning.hold_window` when it was held." },
1619
1644
  disagree: { type: "integer", minimum: 1, description: "The definition's `learning.hold_disagree` when it was held." },
@@ -1729,6 +1754,13 @@ const LEARNING_EXTENSIONS = {
1729
1754
  description: "Read at main's head with git's plumbing; every text cut of the host's secrets as they are now, and a file name holding one `[redacted]` whole. An agent whose learning was never on has no folder: `main` null, `corrections` empty and every page empty. An archived agent's is readable." + " " + SIGN_IN_WITHHELD,
1730
1755
  parameters: [AGENT_ID], responses: { "200": json(AGENT_LEARNING, "The agent's learning."), ...errors(401, 403, 404, 429, 500) }, ...MARK,
1731
1756
  },
1757
+ delete: {
1758
+ operationId: "deleteAgentLearning", tags: ["agents"], summary: "Reset the agent's learning: everything it learned deleted, the agent and its runs kept",
1759
+ description: "Deletes what the agent learned: its learning folder whole (`corrections.md`, its learned workflows, their history and the audit ledger), on this server and on every Archil disk its runs used (its own disk, and a disk a run's launch named, where Archil mode keeps it; nothing else on those disks), then its promotion records and grades. The agent, its definition, its runs and everything kept of them (their files, timelines, costs and each one's learning) stay, so the run list, `GET /stats` and `GET /usage` read the same after; a served run's cost keeps its share of its workflow revision's compile and check (the revision's name, digest and `compile_after` are kept for it, nothing else of its records). A run's learning diff (`GET /runs/{run_id}/learning/diff`, the text it merged) is the folder's and goes with it: 404 after. From then on no run is given a correction or a learned workflow of before, and the agent's next run takes the agent path; learning starts again from the agent's runs, as for a new agent. Its learning work in flight is stopped first: a run that exists only for learning (a check's or an owner's replay, an audit's shadow run) is cancelled and waited for. A run of the agent's own still going (queued, running or parked) carries its learning with it (what it was started with, its compile turn and look-back at its end) and is never cancelled for this: while one is, or a learning run this server cannot end (an SDK run) or one not ended in time, it is `409 learning_busy`, each named in `details.runs`, and nothing of the agent's learning is deleted. `204` when done; idempotent: an agent that never learned, or one reset already, is `204` too. An agent being deleted is `409 agent_not_runnable`. While an Archil disk that holds its learning can't be reached (Archil off on this server, no key, or Archil refusing) it is `503 unavailable`, retryable, with its learning here and its records kept; the next call finishes it. A reset that failed on the way (anything but `409`) may have removed part of the agent's learning, so from then on learning reads no run from before it, as after a reset done. Resetting takes the owner's session (the password sign-in, or the console on a server bound to loopback) or the API token, as deleting an agent does: any other console session is `403 forbidden`. Served in the API-only profile (`AGENTRUN_API_ONLY=1`) too, with the token, as the other learning writes take it.",
1760
+ parameters: [AGENT_ID],
1761
+ responses: { "204": { description: "The agent's learning is reset." }, ...errors(401, 403, 404, 409, 429, 500, 503) },
1762
+ "x-agentrun-serve": "learningreset/1",
1763
+ },
1732
1764
  },
1733
1765
  "/agents/{agent_id}/learning/cost": {
1734
1766
  get: {
@@ -3645,6 +3677,7 @@ const FIELD_EXTENSIONS = {
3645
3677
  repick_max_chars: { type: "integer", minimum: 1, maximum: REPICK_MAX_CHARS_MAX, default: REPICK_MAX_CHARS_DEFAULT, description: "The most characters of state a re-pick over the pages sends its model: past it, the longest strings (the pages) are cut first, each to one length and marked where it was cut. Its cost is the served run's, under the run's cost cap like every model request of the run. Read with `repick`, at each compile." },
3646
3678
  } }], default: false, description: "Whether an agentic revision's runs learn: `true`, its owner's corrections and learned workflows; an object, the same with the loop's numbers set on it (`compile_after`, `agree_min`, `alone_min`, `agree_on`, `audit_every`, `audit_every_later`, `audit_later_after`, `hold_window`, `hold_disagree`, `stop_window`, `repick`, `repick_max_chars`, each optional: one left out is its default; `true` is every default); `false`, nothing. A run that learns starts from what its agent has learned, its corrections.md whole in its instructions under `# Learned` and its learned workflows behind its learned_workflow tool; once its job is due, it is asked one compile turn that writes the job as a learned workflow, checked and committed. Kept when a definition says so, true, false or an object (its numbers in one order); a number out of range or an unknown key is a 422 `wrong_type`; absent, off, and an answer shows none. An edit that leaves it out keeps the agent's. A workflow revision keeps none. On a server whose learning is off (`capabilities.features.learning`), no run learns, whatever this says.", "x-agentrun-serve": "learning/1" },
3647
3679
  checkout: { enum: ["pull_request", "none"], description: "What the server checks out in each run's folder before its first turn, an agentic definition's alone. `pull_request`: the pull request the run's GitHub event names (a GitHub trigger's firing: its repository, number, head and base), at its head, detached, in `repo/`, with its base and their merge base fetched beside it (refs `pr/head`, `pr/base`, `pr/merge-base`). The fetch is the server's own, one command on the run's folder, with an installation token of the server's GitHub App narrowed to that repository and `contents: read`, which the agent never holds: it is never in the folder, the checkout's git config, its remote's URL, the agent's environment or the log. With no App, or one not installed there, the fetch is anonymous, which a public repository answers. The run's system prompt says what was checked out, or why nothing was (no pull request named, the fetch failed), so it can read the change another way, such as the GitHub MCP. The checkout is removed when the run's claim ends. An edit that leaves it out keeps the agent's; `none` clears it. A template sets it from its manifest's `checkout`.", "x-agentrun-serve": "checkout/1" },
3680
+ max_requests: { type: "integer", minimum: 0, description: "The most requests on free models (a catalog price of all zeros, which a dollar cap cannot stop) each of the agent's runs makes, below the server's own limit (`limits.free_model_requests`, AGENTRUN_FREE_MODEL_REQUESTS): a run stops at the lower of the two. The request after that many is not sent, and the run ends `failed`, its error `spend_cap_reached`: \"Not sent: this run reached its 20-request limit for free models.\" (the number is the limit it stopped at). It counts what the server's limit counts; a paid request never counts. Above 0 sets it, 0 clears it, and an edit that leaves it out keeps the agent's. A template sets it from its manifest's `budget.max_requests`.", "x-agentrun-serve": "maxrequests/1" },
3648
3681
  },
3649
3682
  AgentCreate: {
3650
3683
  note: { type: "string", maxLength: 2000, description: "What the revision changes, kept with it (GET /agents/{agent_id}/revisions).", "x-agentrun-serve": "definitionbody/1" },
@@ -4425,7 +4458,7 @@ export function openapiDocument(capabilityOf, adapters = TRIGGER_ADAPTERS) {
4425
4458
  composio_account_ambiguous: closed({ server: { type: "string" }, user_id: { type: "string", description: "The Composio user the server runs as." }, accounts: { type: "array", items: closed({ id: { type: "string", description: "Composio's id for the connected account." }, created_at: { type: "string", description: "When it was connected, as Composio says." } }), description: "The user's ACTIVE accounts for the toolkit, oldest first." } }),
4426
4459
  composio_in_use: closed({ triggers: { type: "array", items: closed({ id: { type: "string" }, name: { type: "string" } }), description: "The composio triggers that use it." } }),
4427
4460
  runs_in_flight: closed({ runs: { type: "array", items: { type: "string" }, description: "The agent's runs not ended (DELETE /agents/{agent_id})." } }),
4428
- learning_busy: closed({ runs: { type: "array", items: { type: "string" }, description: "What of the agent's learning is at work (DELETE /agents/{agent_id}): each run of it not ended (its compile turn, a check's replay or an audit's shadow among them), by its id." } }),
4461
+ learning_busy: closed({ runs: { type: "array", items: { type: "string" }, description: "What of the agent's learning is at work (DELETE /agents/{agent_id}, DELETE /agents/{agent_id}/learning): each run of it not ended (a run of its own, whose compile turn and look-back are at its end, a check's replay or an audit's shadow among them), by its id." } }),
4429
4462
  run_not_final: closed({ runs: { type: "array", items: { type: "string" }, description: "What is live (DELETE /runs/{run_id}, and an archived agent's DELETE /agents/{agent_id}): the run itself, each run made from it that is live, or each live run of the agent, by its id." } }),
4430
4463
  purged: {
4431
4464
  oneOf: [