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

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 (216) hide show
  1. package/CHANGELOG.md +173 -9
  2. package/README.md +246 -39
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/agents-store.js +7 -3
  6. package/dist/api-only.d.ts +8 -10
  7. package/dist/api-only.js +11 -12
  8. package/dist/capacity.d.ts +50 -0
  9. package/dist/capacity.js +49 -0
  10. package/dist/cli-learning/claude-wire.d.ts +41 -0
  11. package/dist/cli-learning/claude-wire.js +258 -0
  12. package/dist/cli-learning/cli.d.ts +11 -0
  13. package/dist/cli-learning/cli.js +241 -0
  14. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  15. package/dist/cli-learning/codex-worktree.js +119 -0
  16. package/dist/cli-learning/connections.d.ts +62 -0
  17. package/dist/cli-learning/connections.js +87 -0
  18. package/dist/cli-learning/entry.d.ts +1 -0
  19. package/dist/cli-learning/entry.js +4 -0
  20. package/dist/cli-learning/evidence.d.ts +78 -0
  21. package/dist/cli-learning/evidence.js +492 -0
  22. package/dist/cli-learning/hook.d.ts +33 -0
  23. package/dist/cli-learning/hook.js +544 -0
  24. package/dist/cli-learning/install.d.ts +33 -0
  25. package/dist/cli-learning/install.js +335 -0
  26. package/dist/cli-learning/observation-proof.d.ts +14 -0
  27. package/dist/cli-learning/observation-proof.js +10 -0
  28. package/dist/cli-learning/policy.d.ts +48 -0
  29. package/dist/cli-learning/policy.js +363 -0
  30. package/dist/cli-learning/schema.d.ts +16 -0
  31. package/dist/cli-learning/schema.js +27 -0
  32. package/dist/cli-learning/state.d.ts +23 -0
  33. package/dist/cli-learning/state.js +61 -0
  34. package/dist/cli.js +24 -2
  35. package/dist/compute-cost.d.ts +101 -0
  36. package/dist/compute-cost.js +250 -0
  37. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  38. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/email/email-faux.d.ts +3 -1
  41. package/dist/email/email-faux.js +3 -2
  42. package/dist/email/routes.js +22 -12
  43. package/dist/eval-previous.d.ts +52 -0
  44. package/dist/eval-previous.js +164 -0
  45. package/dist/file-types.d.ts +2 -0
  46. package/dist/file-types.js +3 -1
  47. package/dist/harness-install.d.ts +6 -2
  48. package/dist/harness-install.js +40 -8
  49. package/dist/harness.d.ts +1 -1
  50. package/dist/harness.js +3 -2
  51. package/dist/learn/check.d.ts +8 -5
  52. package/dist/learn/check.js +25 -24
  53. package/dist/learn/repick.d.ts +22 -13
  54. package/dist/learn/repick.js +57 -56
  55. package/dist/learn/secrets.js +14 -3
  56. package/dist/learn/workflow-draft.d.ts +4 -0
  57. package/dist/learn/workflow-draft.js +10 -7
  58. package/dist/learned-workflow.js +8 -8
  59. package/dist/learning-setting.js +2 -2
  60. package/dist/learning-words.d.ts +1 -1
  61. package/dist/learning-words.js +1 -1
  62. package/dist/mcp-pin-first.js +2 -1
  63. package/dist/mcp-private-hosts.d.ts +24 -3
  64. package/dist/mcp-private-hosts.js +53 -3
  65. package/dist/model-gateway.d.ts +2 -0
  66. package/dist/model-gateway.js +3 -1
  67. package/dist/native/runtimes.d.ts +2 -0
  68. package/dist/native/runtimes.js +2 -0
  69. package/dist/observation/learning.d.ts +32 -0
  70. package/dist/observation/learning.js +66 -0
  71. package/dist/observation/observer.d.ts +8 -1
  72. package/dist/observation/observer.js +89 -9
  73. package/dist/observation/schema.js +12 -4
  74. package/dist/observation/usage-identity.d.ts +9 -0
  75. package/dist/observation/usage-identity.js +11 -0
  76. package/dist/openapi.js +113 -29
  77. package/dist/paid-calls.d.ts +13 -6
  78. package/dist/paid-calls.js +14 -8
  79. package/dist/run-launch.d.ts +16 -2
  80. package/dist/run-launch.js +6 -1
  81. package/dist/run-timeline-served.js +5 -3
  82. package/dist/run-usage.d.ts +23 -8
  83. package/dist/run-usage.js +100 -18
  84. package/dist/run-view.d.ts +2 -0
  85. package/dist/run-view.js +12 -7
  86. package/dist/runner/adapter-loop.d.ts +4 -0
  87. package/dist/runner/adapter-loop.js +44 -27
  88. package/dist/runner/adapter-run-spec.d.ts +8 -3
  89. package/dist/runner/adapter-run-spec.js +15 -8
  90. package/dist/runner/beside.d.ts +13 -0
  91. package/dist/runner/beside.js +27 -8
  92. package/dist/runner/big-writes.d.ts +33 -0
  93. package/dist/runner/big-writes.js +105 -0
  94. package/dist/runner/cli-run-spec.js +16 -8
  95. package/dist/runner/disk-free.d.ts +44 -0
  96. package/dist/runner/disk-free.js +96 -0
  97. package/dist/runner/feedback-round.d.ts +12 -8
  98. package/dist/runner/feedback-round.js +16 -30
  99. package/dist/runner/harness-loops.js +3 -1
  100. package/dist/runner/held.d.ts +4 -1
  101. package/dist/runner/journal-kinds.d.ts +1 -1
  102. package/dist/runner/learning-end.js +13 -4
  103. package/dist/runner/main.d.ts +17 -6
  104. package/dist/runner/main.js +187 -45
  105. package/dist/runner/metrics.d.ts +4 -0
  106. package/dist/runner/metrics.js +9 -0
  107. package/dist/runner/presence.d.ts +11 -2
  108. package/dist/runner/presence.js +31 -3
  109. package/dist/runner/run-child-host.d.ts +27 -17
  110. package/dist/runner/run-child-host.js +70 -116
  111. package/dist/runner/run-child.js +3 -0
  112. package/dist/runner/run-errors.js +2 -0
  113. package/dist/runner/runner-check.d.ts +51 -0
  114. package/dist/runner/runner-check.js +206 -0
  115. package/dist/runner/runner-metrics.d.ts +19 -0
  116. package/dist/runner/runner-metrics.js +49 -0
  117. package/dist/runner/runner.d.ts +37 -0
  118. package/dist/runner/runner.js +43 -3
  119. package/dist/runner/save-slots.d.ts +9 -0
  120. package/dist/runner/save-slots.js +91 -0
  121. package/dist/runner/sdk-loop.js +34 -22
  122. package/dist/runs-over-store.d.ts +8 -1
  123. package/dist/runs-over-store.js +57 -9
  124. package/dist/sdk/runs.d.ts +25 -6
  125. package/dist/sdk/runs.js +107 -35
  126. package/dist/sdk/runtimes.d.ts +19 -0
  127. package/dist/sdk/runtimes.js +23 -0
  128. package/dist/sdk/schema.d.ts +14 -8
  129. package/dist/sdk/schema.js +18 -6
  130. package/dist/server.d.ts +7 -0
  131. package/dist/server.js +151 -28
  132. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  133. package/dist/start-switches.js +2 -0
  134. package/dist/stats.d.ts +4 -0
  135. package/dist/stats.js +1 -1
  136. package/dist/store/agent-body.d.ts +13 -2
  137. package/dist/store/agent-body.js +19 -4
  138. package/dist/store/dialect.d.ts +2 -0
  139. package/dist/store/dialect.js +1 -0
  140. package/dist/store/index.d.ts +3 -3
  141. package/dist/store/index.js +2 -2
  142. package/dist/store/postgres/connection.d.ts +5 -2
  143. package/dist/store/postgres/connection.js +19 -7
  144. package/dist/store/postgres/dialect.js +1 -0
  145. package/dist/store/postgres/migrate.d.ts +30 -0
  146. package/dist/store/postgres/migrate.js +72 -5
  147. package/dist/store/postgres/migration-lint.d.ts +8 -0
  148. package/dist/store/postgres/migration-lint.js +119 -0
  149. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  150. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  151. package/dist/store/postgres/store.d.ts +8 -3
  152. package/dist/store/postgres/store.js +31 -11
  153. package/dist/store/schema.d.ts +26 -4
  154. package/dist/store/schema.js +45 -4
  155. package/dist/store/sqlite/connection.d.ts +3 -3
  156. package/dist/store/sqlite/connection.js +3 -3
  157. package/dist/store/sqlite/run-launch.d.ts +9 -1
  158. package/dist/store/sqlite/run-launch.js +44 -0
  159. package/dist/store/sqlite/store.d.ts +19 -4
  160. package/dist/store/sqlite/store.js +180 -93
  161. package/dist/store/store-schema.d.ts +34 -0
  162. package/dist/store/store-schema.js +125 -0
  163. package/dist/store/store.d.ts +61 -2
  164. package/dist/store/store.js +13 -0
  165. package/dist/store-reads/analytics.d.ts +3 -2
  166. package/dist/store-reads/analytics.js +20 -8
  167. package/dist/store-reads/cap.d.ts +9 -5
  168. package/dist/store-reads/cap.js +28 -2
  169. package/dist/store-reads/decisions.d.ts +21 -0
  170. package/dist/store-reads/decisions.js +22 -0
  171. package/dist/store-reads/journal.d.ts +8 -2
  172. package/dist/store-reads/journal.js +27 -8
  173. package/dist/store-view.d.ts +9 -4
  174. package/dist/store-view.js +48 -25
  175. package/dist/template-eval.d.ts +15 -1
  176. package/dist/template-eval.js +92 -13
  177. package/dist/templates.d.ts +4 -3
  178. package/dist/templates.js +4 -3
  179. package/dist/timeline/labels.js +17 -0
  180. package/dist/tool-gate.d.ts +4 -2
  181. package/dist/tool-list.js +1 -0
  182. package/dist/tools.d.ts +6 -2
  183. package/dist/tools.js +13 -1
  184. package/dist/trigger-targets.d.ts +21 -5
  185. package/dist/trigger-targets.js +13 -10
  186. package/dist/unified-usage.d.ts +24 -0
  187. package/dist/unified-usage.js +400 -0
  188. package/dist/uploads-archil.d.ts +100 -0
  189. package/dist/uploads-archil.js +430 -0
  190. package/dist/uploads.d.ts +55 -1
  191. package/dist/uploads.js +185 -98
  192. package/dist/validate.js +1 -1
  193. package/dist/web-fake.d.ts +25 -0
  194. package/dist/web-fake.js +38 -1
  195. package/dist/web-save.d.ts +75 -0
  196. package/dist/web-save.js +235 -0
  197. package/dist/workspace/archil-claim.d.ts +5 -2
  198. package/dist/workspace/archil-claim.js +5 -2
  199. package/dist/workspace/archil-disk.d.ts +11 -1
  200. package/dist/workspace/archil-disk.js +43 -10
  201. package/dist/workspace/archil.d.ts +3 -0
  202. package/dist/workspace/archil.js +102 -16
  203. package/dist/workspace/computer-for-claim.d.ts +14 -0
  204. package/dist/workspace/computer-for-claim.js +46 -7
  205. package/dist/workspace/computer-intervals.d.ts +9 -3
  206. package/dist/workspace/computer-intervals.js +17 -8
  207. package/dist/workspace/pieced.d.ts +14 -0
  208. package/dist/workspace/pieced.js +23 -0
  209. package/dist/workspace/run-disk.js +32 -12
  210. package/dist/workspace/run-workspace.d.ts +1 -1
  211. package/dist/workspace/run-workspace.js +11 -6
  212. package/package.json +10 -10
  213. package/skills/agentrun-serve/SKILL.md +52 -7
  214. package/templates/README.md +36 -7
  215. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
  216. package/dist/console/assets/index-CR2ZGei1.css +0 -1
package/dist/tool-list.js CHANGED
@@ -6,6 +6,7 @@ export const TOOL_LIST = Object.freeze({
6
6
  ask_person: { table: true, replay: "safe", blurb: "Ask you a question mid-run" },
7
7
  web_fetch: { table: true, askable: true, replay: "safe", host: true, blurb: "Read a public web page" },
8
8
  web_search: { table: true, askable: true, replay: "safe", host: true, blurb: "Search the web" },
9
+ web_save: { table: true, askable: true, replay: "never", host: true, blurb: "Save a public file into the run's folder" },
9
10
  email_search: { table: true, askable: true, replay: "safe", host: true, blurb: "Search the email account's mail" },
10
11
  email_read: { table: true, askable: true, replay: "safe", host: true, blurb: "Read an email or its thread" },
11
12
  email_draft: { table: true, askable: true, replay: "never", host: true, blurb: "Save an email draft" },
package/dist/tools.d.ts CHANGED
@@ -11,6 +11,7 @@ import type { Refusal } from "@parcha/agentrun-kernel";
11
11
  import { type ShellPlace } from "@parcha/agentrun-kernel/kernel";
12
12
  import { type SearchOn } from "./web-search.js";
13
13
  import { type WebFake } from "./web-fake.js";
14
+ import { type SaveSlots } from "./web-save.js";
14
15
  import { type Plane, type Resolution, type Tooling, type ToolSettingsMap } from "./tool-plane.js";
15
16
  import type { DenyFrom, SettingFrom } from "./tool-gate.js";
16
17
  import type { LiveHandover, LiveViewerStore } from "./browser-live.js";
@@ -122,8 +123,8 @@ export type ToolHost = {
122
123
  /** The run's own models a native web_search goes through (hosted-search.ts), asked as a search runs: on the runner, the
123
124
  * session's port (its proxy, policy, key, price and cap), this run's alone. Absent: a native search has no model. */
124
125
  search?: SearchOn;
125
- /** A template eval's web fake for this run (web-fake.ts): its web_search and web_fetch answer from it, never the
126
- * network. Only the eval's own runner sets it (runner/beside.ts evalFakes). Absent: the plane's providers. */
126
+ /** A template eval's web fake for this run (web-fake.ts): its web_search, web_fetch and web_save answer from it, never
127
+ * the network. Only the eval's own runner sets it (runner/beside.ts evalFakes). Absent: the plane's providers. */
127
128
  web?: WebFake;
128
129
  /** The run's clock where a template eval case sets one (its `now`): a draft's or a send's Date reads it. Absent: the real
129
130
  * clock. */
@@ -137,6 +138,9 @@ export type ToolHost = {
137
138
  /** That server's own addresses (Serve.own, AdapterSpecDeps.mcpOwn): calendar_events never reads on loopback at their
138
139
  * ports, a redirect's hop included, as the server's own read (calendar/routes.ts) never does. */
139
140
  serverOwn?: readonly string[];
141
+ /** web_save's download slots: in a run's own process, its runner's gate over the channel (runner/save-slots.ts).
142
+ * Absent: this process's (web-save.ts SERVER_SLOTS). */
143
+ saveSlots?: SaveSlots;
140
144
  };
141
145
  /** A fake mail account's servers, on loopback (email/email-faux.ts), and the kind of server it plays: what email_file's
142
146
  * description says, which a loopback account saved as `other` would otherwise read as folders. */
package/dist/tools.js CHANGED
@@ -33,7 +33,8 @@ import { sessionRecordings } from "./computer-record.js";
33
33
  import { forModel } from "./result.js";
34
34
  import { fetchFor, pagesOf, WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
35
35
  import { searchFor, WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
36
- import { fakeFetch, fakeSearch } from "./web-fake.js";
36
+ import { fakeFetch, fakeSaveOptions, fakeSearch } from "./web-fake.js";
37
+ import { SAVE_MAX_BYTES, WEB_SAVE_TOOL, webSaveTool } from "./web-save.js";
37
38
  import { browserNeeds, explainsView, isUnavailable, NO_PARALLEL_KEY, PICKABLE, planeOf, PROVIDERS, serverGate, whyUnavailable, withDefaults } from "./tool-plane.js";
38
39
  import { fauxFetch, PARALLEL_KEY_ENV } from "./decisions.js";
39
40
  import { keyNeeded } from "./key-words.js";
@@ -624,6 +625,17 @@ export const TOOLS = Object.freeze({
624
625
  bind: async (host) => installTool(host, "web-search", booking(webSearchTool(host.env, host.search, host.web && ((args, provider) => fakeSearch(host.web, args, provider))))),
625
626
  effect: async (args, run) => bookedIn(run.ledger, () => searchFor(run.env, args, run.signal, run.search)),
626
627
  },
628
+ // web_save (web-save.ts). It makes no paid request, so nothing books it. No node or call node names it: a workflow's
629
+ // effect has only a local work path, not the run's Workspace.
630
+ [WEB_SAVE_TOOL]: {
631
+ summary: `Download one public file into the run's work/ (a bare name under media/), never overwriting: { url, path } -> { ok: true, path, bytes, content_type, url } or { ok: false, url, refused | error }; at most ${SAVE_MAX_BYTES / (1024 * 1024)} MiB, a media type only when its bytes agree.`,
632
+ needs: [],
633
+ nodes: false,
634
+ bind: async (host) => {
635
+ const web = host.web;
636
+ return installTool(host, "web-save", webSaveTool(() => host.workspace ?? localWorkspace(host.where.work), async () => (web ? fakeSaveOptions(web) : fetchOptions(host.env, FAUX_ENV)), host.saveSlots));
637
+ },
638
+ },
627
639
  // The email tools (email/tools.ts) on the server's one email account (Settings → Email), every harness's as web_fetch is;
628
640
  // the mail libraries load at the first bind.
629
641
  [EMAIL_SEARCH]: emailTool(EMAIL_SEARCH),
@@ -28,11 +28,7 @@ export interface TriggerTargetDeps {
28
28
  * when it ended; undefined for a run that is unknown or did not complete (the run view). `carried`: the top-level
29
29
  * fields the output schema it was checked against (its pinned revision's, never the agent's current one) names in
30
30
  * `x-carried` (answer-json.ts carriedFields), absent when it names none. */
31
- completedOutput(runId: string): Promise<{
32
- output: unknown;
33
- endedAt: string | null;
34
- carried?: readonly string[];
35
- } | undefined>;
31
+ completedOutput(runId: string): Promise<CompletedOutput | undefined>;
36
32
  }
37
33
  /** The most bytes of a previous run's result a triggered run is handed, as JSON: past it, it is handed none, said so. */
38
34
  export declare const PREVIOUS_RESULT_MAX_BYTES: number;
@@ -46,6 +42,26 @@ export declare const previousCarriedWords: (runId: string, endedAt: string | nul
46
42
  /** What a triggered run is told when its trigger's previous result is over PREVIOUS_RESULT_MAX_BYTES (and no carried
47
43
  * fields of it fit, its carried arrays' entries dropped). */
48
44
  export declare const previousResultTooLarge: (runId: string) => string;
45
+ /** A completed run's result as the trigger reads it back (TriggerTargetDeps.completedOutput). */
46
+ export type CompletedOutput = {
47
+ output: unknown;
48
+ endedAt: string | null;
49
+ carried?: readonly string[];
50
+ };
51
+ /** What a triggered run is handed of its trigger's last completed run `runId`, whose result is `done`: `whole`, its
52
+ * result.output as it is; `carried`, its carried `fields` alone, `dropped` the entries each carried array gave up from its
53
+ * front, by field (0 for one that gave up none; a carried field that is no array is not in it); `too_large`, nothing,
54
+ * said so; `none`, nothing at all (it has no output: its answer did not meet its schema). `text` is the words the run's
55
+ * message carries it in after the trigger's (empty for none). previousResultOf hands the text; a template eval grades
56
+ * the rest (eval-previous.ts handedPrevious). */
57
+ export type PreviousHandover = {
58
+ kind: "whole" | "carried" | "too_large" | "none";
59
+ text: string;
60
+ run_id?: string;
61
+ fields?: string[];
62
+ dropped?: Record<string, number>;
63
+ };
64
+ export declare function previousHandover(runId: string, done: CompletedOutput): PreviousHandover;
49
65
  /** The trigger-facing run policy: the subset of the trigger engine's deps this module owns. The engine's other deps (an
50
66
  * adapter's sealed settings, the failed-firing webhook) stay server-wired. */
51
67
  export type TriggerTargets = {
@@ -32,18 +32,20 @@ async function previousResultOf(store, deps, trigger) {
32
32
  const firings = (await store.triggers.firings(trigger.id)).filter((firing) => firing.key !== trigger.firing_key && firing.runId).slice(0, PREVIOUS_FIRINGS_READ);
33
33
  for (const firing of firings) {
34
34
  const done = await deps.completedOutput(firing.runId);
35
- if (!done)
36
- continue;
37
- if (done.output === null || done.output === undefined)
38
- return "";
39
- const json = JSON.stringify(done.output, null, 2);
40
- const bytes = Buffer.byteLength(json);
41
- if (bytes <= PREVIOUS_RESULT_MAX_BYTES)
42
- return previousResultWords(firing.runId, done.endedAt, json);
43
- return carriedOf(firing.runId, done, bytes) ?? previousResultTooLarge(firing.runId);
35
+ if (done)
36
+ return previousHandover(firing.runId, done).text;
44
37
  }
45
38
  return "";
46
39
  }
40
+ export function previousHandover(runId, done) {
41
+ if (done.output === null || done.output === undefined)
42
+ return { kind: "none", text: "" };
43
+ const json = JSON.stringify(done.output, null, 2);
44
+ const bytes = Buffer.byteLength(json);
45
+ if (bytes <= PREVIOUS_RESULT_MAX_BYTES)
46
+ return { kind: "whole", text: previousResultWords(runId, done.endedAt, json), run_id: runId };
47
+ return carriedOf(runId, done, bytes) ?? { kind: "too_large", text: previousResultTooLarge(runId), run_id: runId };
48
+ }
47
49
  /** A previous result over the limit, `bytes` whole, as its carried fields alone (`done.carried`, the ones it holds),
48
50
  * measured as the whole is. When they are over PREVIOUS_RESULT_MAX_BYTES, carried arrays give up entries from the front
49
51
  * (the convention: a template keeps a carried array oldest first; the engine reads no dates), one at a time, from the
@@ -83,7 +85,8 @@ function carriedOf(runId, done, bytes) {
83
85
  if (Buffer.byteLength(json) > PREVIOUS_RESULT_MAX_BYTES)
84
86
  return undefined;
85
87
  }
86
- return previousCarriedWords(runId, done.endedAt, fields, bytes, json, fields.flatMap((field) => (dropped.has(field) ? [[field, dropped.get(field)]] : [])));
88
+ const text = previousCarriedWords(runId, done.endedAt, fields, bytes, json, fields.flatMap((field) => (dropped.has(field) ? [[field, dropped.get(field)]] : [])));
89
+ return { kind: "carried", text, run_id: runId, fields, dropped: Object.fromEntries(fields.flatMap((field) => (Array.isArray(picked[field]) ? [[field, dropped.get(field) ?? 0]] : []))) };
87
90
  }
88
91
  /** The bytes of a carried array from entry `from` on, as JSON.stringify(picked, null, 2) lays it out one level into the
89
92
  * object: `[]`, or `[\n`, each entry at four spaces (its own inner lines four further in) joined by `,\n`, then `\n ]`.
@@ -0,0 +1,24 @@
1
+ import type { Store } from './store/store.js';
2
+ import type { AnalyticsFilter } from './store-reads/analytics.js';
3
+ declare const fields: readonly ["input", "output", "cache_read", "cache_write"];
4
+ type Counts = Record<typeof fields[number], number | null> & {
5
+ tokens: number | null;
6
+ };
7
+ export type UnifiedUsage = Counts & {
8
+ known_runs: number;
9
+ unknown_runs: number;
10
+ observed_sessions: number;
11
+ unknown_sessions: number;
12
+ partial_days: number;
13
+ retention_limited: boolean;
14
+ by_day: {
15
+ day: string;
16
+ tokens: number | null;
17
+ }[];
18
+ by_harness: {
19
+ harness: string;
20
+ tokens: number | null;
21
+ }[];
22
+ };
23
+ export declare function unifiedUsage(store: Store, filter?: AnalyticsFilter, now?: number): Promise<UnifiedUsage>;
24
+ export {};
@@ -0,0 +1,400 @@
1
+ /** One token view over recorded runs and native observations. Requestless aggregates only establish a
2
+ * lower bound on overlapping usage; select coherent views instead of assuming one completely covers another. */
3
+ import { createHash } from 'node:crypto';
4
+ import { runReadState } from './store-reads/runs.js';
5
+ import { isShadowRun } from './learn/audit.js';
6
+ import { DEFAULT_HARNESS } from './harness.js';
7
+ import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';
8
+ import { journalEntries } from './runner/journal-reader.js';
9
+ import { REQUEST_COST, runMetricsOf } from './timeline/index.js';
10
+ import { usageIdentityOf } from './observation/usage-identity.js';
11
+ const DAY = 86_400_000, RETENTION = 90 * DAY;
12
+ const fields = ['input', 'output', 'cache_read', 'cache_write'];
13
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
14
+ const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
15
+ const plus = (values) => { const sum = values.reduce((a, b) => a + b, 0); return Number.isSafeInteger(sum) ? sum : null; };
16
+ const date = (ms) => new Date(ms).toISOString().slice(0, 10);
17
+ const runtime = (value) => typeof value === 'string'
18
+ ? ['codex', 'codex-cli', 'codex-sdk'].includes(value) ? 'codex'
19
+ : ['claude', 'claude-code', 'claude-code-cli', 'claude-agent-sdk'].includes(value) ? 'claude-code' : undefined : undefined;
20
+ const nativeKey = (harness, session) => harness && typeof session === 'string' && session
21
+ ? `${harness}:${createHash('sha256').update(session).digest('hex')}` : undefined;
22
+ const empty = () => ({ tokens: null, input: null, output: null, cache_read: null, cache_write: null });
23
+ function runCounts(metrics) {
24
+ const result = { input: count(metrics.input), output: count(metrics.output), cache_read: count(metrics.cacheRead), cache_write: count(metrics.cacheWrite) };
25
+ return { ...result, tokens: fields.every(key => result[key] !== null) ? plus(fields.map(key => result[key])) : null };
26
+ }
27
+ function sourceCounts(usage) {
28
+ const input = count(usage.input_tokens), output = count(usage.output_tokens);
29
+ const read = count(usage.cache_read_tokens), write = count(usage.cache_write_tokens);
30
+ return { tokens: input !== null && output !== null ? plus([input, output]) : null, output,
31
+ input: input !== null && read !== null && write !== null && read + write <= input ? input - read - write : null,
32
+ cache_read: read, cache_write: write };
33
+ }
34
+ export async function unifiedUsage(store, filter = {}, now = Date.now()) {
35
+ const from = filter.from === undefined ? -Infinity : Date.parse(filter.from);
36
+ const to = filter.to === undefined ? Infinity : Date.parse(filter.to);
37
+ const archived = new Map();
38
+ const isArchived = async (agent) => {
39
+ if (!archived.has(agent))
40
+ archived.set(agent, (await store.agents.get(agent))?.archivedAt != null);
41
+ return archived.get(agent);
42
+ };
43
+ const runs = [];
44
+ const selectedNative = new Set();
45
+ const revisions = new Map();
46
+ for (const run of await store.runs.list({ purged: true, ...(filter.agent ? { agentId: filter.agent } : {}) })) {
47
+ if (run.archivedAt !== null || isShadowRun(run.id) || await isArchived(run.agentId))
48
+ continue;
49
+ if (!revisions.has(run.revisionId))
50
+ revisions.set(run.revisionId, await store.agents.revision(run.revisionId));
51
+ const revision = revisions.get(run.revisionId), body = object(revision?.body), metrics = object(run.metrics);
52
+ const cli = object(body.cli_learning), sdk = object(body.sdk), native = object(body.native);
53
+ const cliRuntime = cli.runtime === 'codex' ? 'codex-cli' : cli.runtime === 'claude-code' ? 'claude-code-cli' : cli.runtime;
54
+ let harness = metrics.cli_runtime ?? metrics.sdk_runtime ?? metrics.native_runtime ?? cliRuntime ?? sdk.runtime ?? native.runtime ?? run.importedFrom?.source ?? body.harness ?? DEFAULT_HARNESS;
55
+ let session = metrics.cli_session_id ?? metrics.sdk_session_id ?? metrics.native_session_id ?? run.importedFrom?.session;
56
+ const inRange = !(run.startedAt < from || run.startedAt >= to);
57
+ // A filtered observation may match a historical run's native identity, even outside this date range.
58
+ if (!inRange && !filter.agent)
59
+ continue;
60
+ const isCli = Boolean(metrics.cli_runtime || Object.keys(cli).length);
61
+ const isSdk = Boolean(isCli || metrics.sdk_runtime || Object.keys(sdk).length);
62
+ const metadata = run.purgedAt == null && (isCli || (inRange && isSdk))
63
+ ? await store.runs.usageMetadata(run.id, { completion: inRange && isSdk }) : undefined;
64
+ let window = {};
65
+ if (isCli) {
66
+ window = object(metadata?.cli);
67
+ if (!session) {
68
+ session = window.session_id;
69
+ harness = window.runtime ?? harness;
70
+ }
71
+ }
72
+ const key = nativeKey(runtime(harness), session);
73
+ if (key)
74
+ selectedNative.add(key);
75
+ if (!inRange)
76
+ continue;
77
+ runs.push({ id: run.id, key, imported: run.importedFrom !== null,
78
+ opaqueImport: Boolean(metrics.remote_history_sha256 || String(session).startsWith('redacted-')),
79
+ purged: run.purgedAt != null, runtimeErased: run.purgedAt != null && !Object.keys(body).length,
80
+ nativeReflection: Boolean(window.native_grading),
81
+ ...(key && key === nativeKey(runtime(window.runtime), window.session_id) && typeof window.turn_id === 'string' && window.turn_id
82
+ ? { window: window.turn_id } : {}),
83
+ sdk: isSdk, usage: metadata?.completionUsage,
84
+ fact: { ...(runReadState(run, revision?.kind === 'workflow' ? 'workflow' : 'agentic') === 'running' ? empty() : runCounts(metrics)),
85
+ day: date(run.startedAt), harness: String(harness), runId: run.id } });
86
+ }
87
+ const connections = new Map();
88
+ const observed = [];
89
+ let sourceSelected = false;
90
+ for (const row of await store.settings.all({ prefix: 'observation.connector.' })) {
91
+ const connector = object(row.value);
92
+ for (const raw of Object.values(object(connector.sessions))) {
93
+ const session = object(raw);
94
+ if (typeof session.id !== 'string' || !runtime(session.harness))
95
+ continue;
96
+ const harness = runtime(session.harness);
97
+ // Accounting identity is independent of current learning readiness. Older persisted sessions
98
+ // still carry their verified identity in the association until their next ingestion migrates it.
99
+ const identity = usageIdentityOf(session.usage_identity) ?? usageIdentityOf(session.learning_association);
100
+ const key = identity ? `${harness}:${identity.native_session_hash}` : `observation:${connector.id}:${session.id}`;
101
+ let agent;
102
+ if (identity) {
103
+ if (!connections.has(identity.connection_id))
104
+ connections.set(identity.connection_id, object(await store.settings.get(`cli-learning-connection:${identity.connection_id}`)).agent_id);
105
+ agent = connections.get(identity.connection_id);
106
+ }
107
+ if (filter.agent && filter.agent !== session.id && filter.agent !== agent && !selectedNative.has(key))
108
+ continue;
109
+ sourceSelected = true;
110
+ const received = Date.parse(session.received_at), facts = [], partial = new Set();
111
+ let overlaps = false;
112
+ for (const [day, models] of Object.entries(object(session.usage_by_day))) {
113
+ if (!/^\d{4}-\d\d-\d\d$/.test(day))
114
+ continue;
115
+ const start = Date.parse(day), end = start + DAY;
116
+ if (end < now - RETENTION)
117
+ continue;
118
+ const values = Object.values(object(models)).map(value => sourceCounts(object(value)));
119
+ if (end <= from || start >= to)
120
+ continue;
121
+ overlaps = true;
122
+ if (start < from || end > to) {
123
+ partial.add(day);
124
+ continue;
125
+ }
126
+ for (const value of values) {
127
+ facts.push({ ...value, day, harness });
128
+ }
129
+ }
130
+ if (!overlaps && !(received >= from && received < to) && filter.agent !== session.id)
131
+ continue;
132
+ observed.push({ id: session.id, key, collector: row.key, verified: !!identity, received, harness, facts, partial });
133
+ }
134
+ }
135
+ // Copies of a verified session may cover disjoint days. Choose the most reported copy for each UTC day,
136
+ // then the freshest receipt and stable id. Same-day requestless aggregates cannot be safely added together.
137
+ const copies = new Map();
138
+ for (const session of observed) {
139
+ const group = copies.get(session.key) ?? [];
140
+ group.push(session);
141
+ copies.set(session.key, group);
142
+ }
143
+ const authorities = new Map();
144
+ const uncertainSources = new Set();
145
+ const better = (next, old) => !old || next.score > old.score
146
+ || (next.score === old.score && (next.session.received > old.session.received
147
+ || (next.session.received === old.session.received && next.session.id < old.session.id)));
148
+ const collectorViews = new Map();
149
+ for (const [key, group] of copies) {
150
+ const days = new Map();
151
+ const perCollector = new Map();
152
+ const partial = new Set();
153
+ for (const session of group) {
154
+ for (const day of session.partial)
155
+ partial.add(day);
156
+ const own = new Map();
157
+ for (const fact of session.facts) {
158
+ const items = own.get(fact.day) ?? [];
159
+ items.push(fact);
160
+ own.set(fact.day, items);
161
+ }
162
+ for (const [day, facts] of own) {
163
+ const next = { session, facts, score: facts.reduce((sum, fact) => sum + (fact.tokens ?? 0), 0) }, old = days.get(day);
164
+ if (old)
165
+ uncertainSources.add(key);
166
+ if (better(next, old))
167
+ days.set(day, next);
168
+ const ownDays = perCollector.get(session.collector) ?? new Map();
169
+ if (better(next, ownDays.get(day)))
170
+ ownDays.set(day, next);
171
+ perCollector.set(session.collector, ownDays);
172
+ }
173
+ }
174
+ authorities.set(key, { ...group[0], facts: [...days.values()].flatMap(day => day.facts), partial });
175
+ for (const [collector, ownDays] of perCollector) {
176
+ const views = collectorViews.get(group[0].harness) ?? new Map();
177
+ views.set(collector, [...(views.get(collector) ?? []), ...[...ownDays.values()].flatMap(day => day.facts)]);
178
+ collectorViews.set(group[0].harness, views);
179
+ }
180
+ }
181
+ const facts = [], partial = new Set();
182
+ const knownRuns = new Set(), unknownRuns = new Set();
183
+ const nativeFacts = new Map(), opaqueAlternatives = new Map();
184
+ const otherNative = new Set([
185
+ ...runs.filter(run => !run.imported && run.key && run.fact.tokens !== null).map(run => runtime(run.fact.harness)),
186
+ ...[...authorities.values()].filter(source => source.facts.some(fact => fact.tokens !== null)).map(source => source.harness),
187
+ ]);
188
+ const groups = new Map();
189
+ const alternative = (harness, fact) => {
190
+ const alternatives = opaqueAlternatives.get(harness) ?? [];
191
+ alternatives.push(fact);
192
+ opaqueAlternatives.set(harness, alternatives);
193
+ };
194
+ for (const run of runs) {
195
+ const harness = runtime(run.fact.harness);
196
+ if (run.purged && !run.key && run.fact.tokens !== null && (harness || (run.runtimeErased && otherNative.size))) {
197
+ // Purge intentionally deletes native identities and receipts. Keep its counters without recreating
198
+ // private provenance or pretending that an opaque native aggregate is disjoint from observed usage.
199
+ alternative(harness ?? '*', run.fact);
200
+ continue;
201
+ }
202
+ if (run.imported && run.key && harness && otherNative.has(harness) && run.fact.tokens !== null) {
203
+ // Old local imports retain exact child counters, but not child identities. Verify the complete
204
+ // journal before separating the root; a missing journal or namespaced/redacted root proves no split.
205
+ let root;
206
+ if (!run.opaqueImport && !run.purged)
207
+ try {
208
+ const entries = await journalEntries(store.readJournal(run.id), BACKGROUND_CONTEXT);
209
+ const complete = runCounts(runMetricsOf(entries));
210
+ const own = runCounts(runMetricsOf(entries.filter(entry => entry.kind !== REQUEST_COST || object(entry.data).request !== 'subagent')));
211
+ if (complete.tokens !== null && own.tokens !== null && fields.every(field => complete[field] === run.fact[field] && own[field] <= complete[field]))
212
+ root = own;
213
+ }
214
+ catch { /* Retain the saved aggregate as an alternative, never guess missing provenance. */ }
215
+ if (!root || root.tokens !== run.fact.tokens) {
216
+ alternative(harness, run.fact);
217
+ unknownRuns.add(run.id);
218
+ }
219
+ if (!root)
220
+ continue;
221
+ run.fact = { ...run.fact, ...root };
222
+ }
223
+ if (run.key) {
224
+ const group = groups.get(run.key) ?? [];
225
+ group.push(run);
226
+ groups.set(run.key, group);
227
+ }
228
+ else {
229
+ facts.push(run.fact);
230
+ if (run.fact.tokens === null)
231
+ unknownRuns.add(run.id);
232
+ }
233
+ }
234
+ const recordedRuntimes = new Set([...groups.values()].flat().filter(run => run.fact.tokens !== null).map(run => runtime(run.fact.harness)));
235
+ for (const harness of opaqueAlternatives.keys())
236
+ recordedRuntimes.add(harness);
237
+ const unidentifiedOverlap = new Set([...authorities.values()].filter(session => !session.verified
238
+ && session.facts.some(fact => fact.tokens !== null) && (recordedRuntimes.has(session.harness) || recordedRuntimes.has('*'))).map(session => session.harness));
239
+ let observed_sessions = 0;
240
+ for (const [key, session] of authorities) {
241
+ if (!groups.has(key))
242
+ groups.set(key, []);
243
+ for (const day of session.partial)
244
+ partial.add(day);
245
+ if (session.facts.some(fact => fact.tokens !== null))
246
+ observed_sessions++;
247
+ else
248
+ uncertainSources.add(key);
249
+ }
250
+ for (const [key, group] of groups) {
251
+ const session = authorities.get(key), sourceFacts = session?.facts ?? [];
252
+ const windows = new Map(), alternatives = [];
253
+ for (const run of group) {
254
+ if (run.fact.tokens === null) {
255
+ facts.push(run.fact);
256
+ unknownRuns.add(run.id);
257
+ continue;
258
+ }
259
+ let fact = run.fact, window;
260
+ if (run.sdk && !run.purged) {
261
+ const usage = object(run.usage);
262
+ const task = runCounts({ input: usage?.input_tokens, output: usage?.output_tokens,
263
+ cacheRead: usage?.cache_read_tokens, cacheWrite: usage?.cache_write_tokens });
264
+ if (task.tokens !== null && fields.every(field => fact[field] >= task[field])) {
265
+ // The immutable receipt separates reflection. Current SDK reflection is an independent HTTP
266
+ // call; historical native graders created observable sessions without retaining their identities.
267
+ const remainder = Object.fromEntries(fields.map(field => [field, fact[field] - task[field]]));
268
+ const tokens = plus(fields.map(field => remainder[field]));
269
+ if (tokens !== null && tokens > 0) {
270
+ const harness = runtime(fact.harness);
271
+ const couldObserveReflection = run.nativeReflection && ([...authorities.values()].some(source => source.key !== key && source.harness === harness && source.facts.some(item => item.tokens !== null))
272
+ || runs.some(other => other.id !== run.id && other.key !== key && runtime(other.fact.harness) === harness && other.fact.tokens !== null));
273
+ if (couldObserveReflection) {
274
+ alternative(harness, fact);
275
+ unknownRuns.add(run.id);
276
+ }
277
+ else
278
+ facts.push({ ...fact, ...remainder, tokens });
279
+ }
280
+ fact = { ...fact, ...task };
281
+ window = run.window;
282
+ }
283
+ }
284
+ if (!window) {
285
+ alternatives.push(fact);
286
+ continue;
287
+ }
288
+ // Only a pinned CLI turn plus its immutable receipt identifies disjoint native prompt usage.
289
+ // SDK/import row timestamps are bookkeeping, not proof of native request boundaries.
290
+ const old = windows.get(window);
291
+ if (!old)
292
+ windows.set(window, { fact, runs: [run.id] });
293
+ else {
294
+ old.runs.push(run.id);
295
+ if (fact.tokens > old.fact.tokens || (fact.tokens === old.fact.tokens && run.id < old.fact.runId))
296
+ old.fact = fact;
297
+ for (const id of old.runs)
298
+ unknownRuns.add(id);
299
+ }
300
+ }
301
+ facts.push(...sourceFacts.filter(fact => fact.tokens === null));
302
+ // An old disconnect may already have erased a verified identity. Do not invent it or
303
+ // add this observation to potentially overlapping native runs; compare collector views below.
304
+ if (session && !session.verified && unidentifiedOverlap.has(session.harness))
305
+ continue;
306
+ const observed = sourceFacts.filter(fact => fact.tokens !== null), captured = [...windows.values()].map(window => window.fact);
307
+ const score = (items) => plus(items.map(fact => fact.tokens));
308
+ if (observed.length && captured.length)
309
+ for (const window of windows.values())
310
+ for (const id of window.runs)
311
+ unknownRuns.add(id);
312
+ // Offline hooks can register a prompt after native execution. Server start/end timestamps cannot
313
+ // establish disjointness from observer UTC days. Distinct pinned turns may sum, as may distinct
314
+ // observer days, but those complete views remain alternatives without native request-level coverage.
315
+ // Preserve the selected view's entire breakdown; per-field maxima can invent a nonexistent total.
316
+ let selected = !observed.length || (captured.length && (score(captured) ?? Infinity) > (score(observed) ?? Infinity)) ? captured : observed;
317
+ if (alternatives.length && (selected.length || alternatives.length > 1))
318
+ for (const run of group)
319
+ unknownRuns.add(run.id);
320
+ alternatives.sort((a, b) => a.runId.localeCompare(b.runId));
321
+ for (const fact of alternatives)
322
+ if (!selected.length || fact.tokens > (score(selected) ?? Infinity))
323
+ selected = [fact];
324
+ const harness = session?.harness ?? runtime(group[0].fact.harness);
325
+ const cohort = nativeFacts.get(harness) ?? [];
326
+ cohort.push(...selected);
327
+ nativeFacts.set(harness, cohort);
328
+ }
329
+ for (const [harness, alternatives] of opaqueAlternatives) {
330
+ if (harness === '*')
331
+ continue;
332
+ // Opaque descendants, historical native reflection and purged native counters can overlap other
333
+ // sessions of this runtime. Compare whole views; independent managed work and HTTP reflection stay additive.
334
+ let selected = nativeFacts.get(harness) ?? [];
335
+ const ambiguous = selected.length > 0 || alternatives.length > 1;
336
+ alternatives.sort((a, b) => a.runId.localeCompare(b.runId));
337
+ for (const fact of alternatives)
338
+ if (!selected.length || fact.tokens > (plus(selected.map(item => item.tokens)) ?? Infinity))
339
+ selected = [fact];
340
+ nativeFacts.set(harness, selected);
341
+ if (ambiguous) {
342
+ for (const run of runs)
343
+ if (runtime(run.fact.harness) === harness)
344
+ unknownRuns.add(run.id);
345
+ }
346
+ }
347
+ for (const harness of unidentifiedOverlap) {
348
+ let selected = nativeFacts.get(harness) ?? [];
349
+ for (const [, view] of [...(collectorViews.get(harness) ?? new Map())].sort(([a], [b]) => a.localeCompare(b))) {
350
+ const known = view.filter(fact => fact.tokens !== null);
351
+ if (known.length && (!selected.length || (plus(known.map(fact => fact.tokens)) ?? Infinity) > (plus(selected.map(fact => fact.tokens)) ?? Infinity)))
352
+ selected = known;
353
+ }
354
+ nativeFacts.set(harness, selected);
355
+ for (const session of authorities.values())
356
+ if (session.harness === harness && !session.verified)
357
+ uncertainSources.add(session.key);
358
+ for (const run of runs)
359
+ if (runtime(run.fact.harness) === harness && (run.key || run.purged))
360
+ unknownRuns.add(run.id);
361
+ }
362
+ const unscoped = opaqueAlternatives.get('*');
363
+ if (unscoped?.length) {
364
+ let selected = [...nativeFacts.values()].flat();
365
+ unscoped.sort((a, b) => a.runId.localeCompare(b.runId));
366
+ for (const fact of unscoped) {
367
+ unknownRuns.add(fact.runId);
368
+ if (!selected.length || fact.tokens > (plus(selected.map(item => item.tokens)) ?? Infinity))
369
+ selected = [fact];
370
+ }
371
+ nativeFacts.clear();
372
+ nativeFacts.set('*', selected);
373
+ }
374
+ facts.push(...[...nativeFacts.values()].flat());
375
+ for (const fact of facts)
376
+ if (fact.runId && fact.tokens !== null)
377
+ knownRuns.add(fact.runId);
378
+ const known = facts.filter(fact => fact.tokens !== null);
379
+ const unknown_sessions = uncertainSources.size;
380
+ const any = facts.length > 0 || unknown_sessions > 0 || unknownRuns.size > 0;
381
+ const totals = { tokens: known.length ? plus(known.map(fact => fact.tokens)) : any ? null : 0,
382
+ ...Object.fromEntries(fields.map(key => [key, known.some(fact => fact[key] === null) ? null
383
+ : known.length ? plus(known.map(fact => fact[key])) : any ? null : 0])) };
384
+ const grouped = (key) => {
385
+ const groups = new Map();
386
+ for (const fact of facts) {
387
+ const group = groups.get(fact[key]) ?? [];
388
+ group.push(fact);
389
+ groups.set(fact[key], group);
390
+ }
391
+ return [...groups].sort(([a], [b]) => a.localeCompare(b)).map(([name, group]) => {
392
+ const known = group.filter(fact => fact.tokens !== null);
393
+ return { name, tokens: known.length ? plus(known.map(fact => fact.tokens)) : null };
394
+ });
395
+ };
396
+ return { ...totals, known_runs: knownRuns.size, unknown_runs: unknownRuns.size, observed_sessions, unknown_sessions, partial_days: partial.size,
397
+ retention_limited: sourceSelected && from < now - RETENTION,
398
+ by_day: grouped('day').map(({ name, tokens }) => ({ day: name, tokens })),
399
+ by_harness: grouped('harness').map(({ name, tokens }) => ({ harness: name, tokens })) };
400
+ }