@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.39

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 (410) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/README.md +325 -124
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-BNhZs-jp.css +1 -0
  37. package/dist/console/assets/index-BQv5aOGB.js +700 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +84 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +10 -0
  46. package/dist/email/answer.js +182 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +380 -0
  53. package/dist/email/names.d.ts +20 -0
  54. package/dist/email/names.js +40 -0
  55. package/dist/email/routes.d.ts +9 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +20 -0
  58. package/dist/email/tools.js +517 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +9 -2
  93. package/dist/learn/compile.js +52 -16
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +106 -51
  97. package/dist/learn/promote.js +82 -189
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +26 -8
  109. package/dist/learning-cost.js +17 -7
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +33 -2
  118. package/dist/local-models.js +43 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +1 -0
  164. package/dist/openapi.js +394 -85
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +7 -2
  170. package/dist/port-models.js +5 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +11 -0
  180. package/dist/refusal-words.js +13 -2
  181. package/dist/run-launch.d.ts +10 -1
  182. package/dist/run-launch.js +11 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +42 -35
  191. package/dist/run-view.js +79 -44
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +42 -11
  195. package/dist/runner/adapter-loop.js +651 -247
  196. package/dist/runner/adapter-run-spec.d.ts +37 -12
  197. package/dist/runner/adapter-run-spec.js +139 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +94 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +37 -13
  217. package/dist/runner/journal-kinds.js +9 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +12 -3
  237. package/dist/runner/model-route.js +139 -18
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +74 -8
  243. package/dist/runner/promotion.js +365 -124
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +554 -130
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/index.d.ts +1 -1
  278. package/dist/store/native-command-owner.d.ts +10 -0
  279. package/dist/store/native-command-owner.js +47 -0
  280. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  281. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  282. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  283. package/dist/store/postgres/store.js +3 -0
  284. package/dist/store/schema.d.ts +7 -0
  285. package/dist/store/schema.js +20 -1
  286. package/dist/store/sqlite/run-patch.d.ts +8 -1
  287. package/dist/store/sqlite/run-patch.js +14 -3
  288. package/dist/store/sqlite/store.js +133 -18
  289. package/dist/store/store.d.ts +52 -7
  290. package/dist/store-reads/analytics.d.ts +7 -7
  291. package/dist/store-reads/analytics.js +23 -5
  292. package/dist/store-reads/cap.js +8 -6
  293. package/dist/store-reads/journal.d.ts +5 -0
  294. package/dist/store-reads/journal.js +85 -41
  295. package/dist/store-reads/learning.d.ts +85 -5
  296. package/dist/store-reads/learning.js +45 -17
  297. package/dist/store-reads/runs.d.ts +5 -0
  298. package/dist/store-reads/runs.js +3 -2
  299. package/dist/store-view.js +75 -21
  300. package/dist/template-eval.d.ts +73 -11
  301. package/dist/template-eval.js +535 -75
  302. package/dist/templates.d.ts +70 -20
  303. package/dist/templates.js +191 -34
  304. package/dist/text-urls.d.ts +38 -0
  305. package/dist/text-urls.js +170 -0
  306. package/dist/timeline/index.d.ts +3 -2
  307. package/dist/timeline/index.js +3 -2
  308. package/dist/timeline/labels.d.ts +5 -2
  309. package/dist/timeline/labels.js +29 -6
  310. package/dist/timeline/origin.d.ts +1 -1
  311. package/dist/timeline/origin.js +2 -2
  312. package/dist/timeline/render-text.js +1 -1
  313. package/dist/timeline/timeline.d.ts +66 -4
  314. package/dist/timeline/timeline.js +160 -30
  315. package/dist/timeline/util.d.ts +5 -0
  316. package/dist/timeline/util.js +44 -8
  317. package/dist/timeline/web-calls.d.ts +17 -0
  318. package/dist/timeline/web-calls.js +106 -0
  319. package/dist/tool-gate.d.ts +42 -42
  320. package/dist/tool-gate.js +97 -91
  321. package/dist/tool-list.d.ts +4 -1
  322. package/dist/tool-list.js +8 -1
  323. package/dist/tool-names.d.ts +18 -13
  324. package/dist/tool-names.js +19 -17
  325. package/dist/tool-plane.d.ts +17 -13
  326. package/dist/tool-plane.js +12 -5
  327. package/dist/tools.d.ts +44 -16
  328. package/dist/tools.js +28 -28
  329. package/dist/trigger-adapter.d.ts +85 -5
  330. package/dist/trigger-adapter.js +6 -0
  331. package/dist/trigger-adapters.js +3 -1
  332. package/dist/trigger-composio.d.ts +10 -0
  333. package/dist/trigger-composio.js +122 -0
  334. package/dist/trigger-email.d.ts +4 -0
  335. package/dist/trigger-email.js +228 -0
  336. package/dist/trigger-signatures.d.ts +6 -10
  337. package/dist/trigger-signatures.js +16 -16
  338. package/dist/trigger-targets.d.ts +1 -1
  339. package/dist/trigger-targets.js +4 -3
  340. package/dist/trigger-webhook.js +6 -4
  341. package/dist/triggers.d.ts +94 -9
  342. package/dist/triggers.js +263 -62
  343. package/dist/uploads.d.ts +9 -0
  344. package/dist/uploads.js +27 -0
  345. package/dist/validate.js +1 -7
  346. package/dist/web-fake.d.ts +56 -0
  347. package/dist/web-fake.js +102 -0
  348. package/dist/web-fetch-direct.d.ts +3 -0
  349. package/dist/web-fetch-direct.js +4 -1
  350. package/dist/web-fetch.d.ts +5 -1
  351. package/dist/web-fetch.js +8 -31
  352. package/dist/web-search.d.ts +51 -2
  353. package/dist/web-search.js +116 -18
  354. package/dist/webhooks.d.ts +2 -1
  355. package/dist/webhooks.js +5 -1
  356. package/dist/workflow/node-runner.js +10 -2
  357. package/dist/workspace/archil-claim.d.ts +3 -0
  358. package/dist/workspace/archil-claim.js +9 -2
  359. package/dist/workspace/computer-deps.d.ts +22 -9
  360. package/dist/workspace/computer-deps.js +78 -37
  361. package/dist/workspace/computer-for-claim.d.ts +54 -4
  362. package/dist/workspace/computer-for-claim.js +179 -39
  363. package/dist/workspace/computer-janitor.d.ts +10 -3
  364. package/dist/workspace/computer-janitor.js +96 -29
  365. package/dist/workspace/computer-kept.d.ts +82 -0
  366. package/dist/workspace/computer-kept.js +147 -0
  367. package/dist/workspace/computer-mcp.js +4 -3
  368. package/dist/workspace/computer-ports.d.ts +23 -3
  369. package/dist/workspace/computer-ports.js +115 -5
  370. package/dist/workspace/index.d.ts +1 -2
  371. package/dist/workspace/index.js +1 -2
  372. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  373. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  374. package/dist/workspace/resolve-computer.d.ts +15 -3
  375. package/dist/workspace/resolve-computer.js +10 -7
  376. package/dist/workspace/revision-skills.d.ts +6 -2
  377. package/dist/workspace/revision-skills.js +12 -5
  378. package/dist/workspace/run-end-computers.d.ts +30 -0
  379. package/dist/workspace/run-end-computers.js +137 -0
  380. package/dist/workspace/run-tools.d.ts +28 -29
  381. package/dist/workspace/run-tools.js +29 -30
  382. package/dist/wrap-up.d.ts +19 -5
  383. package/dist/wrap-up.js +31 -4
  384. package/package.json +13 -9
  385. package/skills/agentrun-serve/SKILL.md +248 -10
  386. package/templates/README.md +117 -23
  387. package/templates/TOOLS.md +168 -0
  388. package/templates/code-review/agent.md +18 -4
  389. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  390. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  391. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  392. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  393. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  394. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  395. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  396. package/templates/code-review/skills/review/DEEP.md +2 -2
  397. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  398. package/templates/code-review/skills/review/SKILL.md +7 -3
  399. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  400. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  401. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  402. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  403. package/dist/console/assets/index-CjqQirbo.css +0 -1
  404. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  405. package/dist/host-calls.d.ts +0 -20
  406. package/dist/host-calls.js +0 -12
  407. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  408. package/dist/runner/adapters/pi-computer.js +0 -51
  409. package/dist/workspace/computer-script.d.ts +0 -53
  410. package/dist/workspace/computer-script.js +0 -172
@@ -0,0 +1,919 @@
1
+ /** Hosted CLI observation protocol. A connector's receipts, session views and counters commit in one CAS.
2
+ * Observation never launches a run, imports credentials, creates a runnable definition or enables learning. */
3
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { NATIVE_OBSERVATION_HARNESSES, nativeObservationProtocol } from "../native/runtimes.js";
5
+ const PREFIX = "observation.connector.";
6
+ const DAY = 86_400_000;
7
+ const OFFLINE = 120_000;
8
+ const MAX_RECEIPTS = 100_000;
9
+ const RECEIPT_WINDOW = 7 * DAY;
10
+ const SESSION_WINDOW = 90 * DAY;
11
+ const MAX_SESSIONS = 1_000;
12
+ const MAX_CONNECTORS = 100;
13
+ // The Collector sends up to 100 normalized usage records as uncompressed OTLP JSON.
14
+ // Its envelope is larger than a control message; both wire and expanded logs stay bounded.
15
+ export const MAX_OTLP_PAYLOAD_BYTES = 1_048_576;
16
+ const COUNTS = [
17
+ "input_tokens",
18
+ "output_tokens",
19
+ "cache_read_tokens",
20
+ "cache_write_tokens",
21
+ ];
22
+ export class ObservationError extends Error {
23
+ status;
24
+ code;
25
+ details;
26
+ constructor(status, code, details = {}) {
27
+ super(code);
28
+ this.status = status;
29
+ this.code = code;
30
+ this.details = details;
31
+ }
32
+ }
33
+ function refuse(status, code, details = {}) {
34
+ throw new ObservationError(status, code, details);
35
+ }
36
+ const hash = (v) => createHash("sha256").update(v).digest("hex");
37
+ const canonical = (v) => Array.isArray(v)
38
+ ? `[${v.map(canonical).join(",")}]`
39
+ : v !== null && typeof v === "object"
40
+ ? `{${Object.keys(v)
41
+ .sort()
42
+ .map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)
43
+ .join(",")}}`
44
+ : JSON.stringify(v);
45
+ const fingerprint = (v) => hash(canonical(v));
46
+ const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v)
47
+ ? v
48
+ : refuse(422, "connector_invalid");
49
+ const exact = (v, keys) => {
50
+ if (Object.keys(v).some((k) => !keys.includes(k)))
51
+ refuse(422, "connector_invalid");
52
+ };
53
+ const id = (v) => typeof v === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(v);
54
+ const uuid = (v) => typeof v === "string" &&
55
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
56
+ const harness = (v) => nativeObservationProtocol(v) !== undefined;
57
+ const safeInt = (v, min = 0) => typeof v === "number" && Number.isSafeInteger(v) && v >= min;
58
+ const activities = new Set([
59
+ "unknown",
60
+ "working",
61
+ "idle",
62
+ "waiting_input",
63
+ "finished",
64
+ "failed",
65
+ "stopped",
66
+ ]);
67
+ const timestamp = (v) => typeof v === "string" &&
68
+ /^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(v) &&
69
+ Number.isFinite(Date.parse(v));
70
+ const key = (connectorId) => PREFIX + connectorId;
71
+ const empty = () => ({
72
+ input_tokens: 0,
73
+ output_tokens: 0,
74
+ cache_read_tokens: 0,
75
+ cache_write_tokens: 0,
76
+ total_tokens: 0,
77
+ cache_hit_rate: null,
78
+ overflow: false,
79
+ });
80
+ const unavailable = () => ({ ...empty(), cache_read_tokens: null, cache_write_tokens: null });
81
+ function plus(total, usage, exact = true) {
82
+ total.input_tokens += usage.input_tokens;
83
+ total.output_tokens += usage.output_tokens;
84
+ total.total_tokens = total.input_tokens + total.output_tokens;
85
+ for (const k of ["cache_read_tokens", "cache_write_tokens"])
86
+ total[k] =
87
+ total[k] === null || usage[k] === undefined ? null : total[k] + usage[k];
88
+ total.cache_hit_rate =
89
+ total.input_tokens > 0 && total.cache_read_tokens !== null
90
+ ? total.cache_read_tokens / total.input_tokens
91
+ : null;
92
+ if (!Number.isSafeInteger(total.total_tokens)) {
93
+ if (exact)
94
+ refuse(409, "connector_token_total_limit");
95
+ total.overflow = true;
96
+ total.input_tokens = Math.min(total.input_tokens, Number.MAX_SAFE_INTEGER);
97
+ total.output_tokens = Math.min(total.output_tokens, Number.MAX_SAFE_INTEGER);
98
+ total.total_tokens = Number.MAX_SAFE_INTEGER;
99
+ for (const k of ["cache_read_tokens", "cache_write_tokens"])
100
+ if (total[k] !== null)
101
+ total[k] = Math.min(total[k], Number.MAX_SAFE_INTEGER);
102
+ total.cache_hit_rate = null;
103
+ }
104
+ }
105
+ function selections(input) {
106
+ if (!Array.isArray(input) || input.length > 1000)
107
+ refuse(422, "connector_invalid");
108
+ const seen = new Set();
109
+ return input.map((v) => {
110
+ const s = obj(v);
111
+ exact(s, [
112
+ "source_id",
113
+ "harness",
114
+ "mode",
115
+ "external_session_id",
116
+ "include_future_sessions",
117
+ ]);
118
+ if (!id(s.source_id) ||
119
+ seen.has(s.source_id) ||
120
+ !harness(s.harness) ||
121
+ !["session", "project", "harness"].includes(s.mode) ||
122
+ typeof s.include_future_sessions !== "boolean")
123
+ refuse(422, "connector_invalid");
124
+ seen.add(s.source_id);
125
+ if (s.mode === "session"
126
+ ? !id(s.external_session_id) || s.include_future_sessions
127
+ : (s.external_session_id !== undefined &&
128
+ s.external_session_id !== null) ||
129
+ !s.include_future_sessions)
130
+ refuse(422, "connector_invalid");
131
+ return {
132
+ ...s,
133
+ external_session_id: s.external_session_id ?? null,
134
+ };
135
+ });
136
+ }
137
+ function checkMode(row, sources) {
138
+ const supported = new Set(row.adapters.map((v) => obj(v).harness));
139
+ if (sources.some((s) => !supported.has(s.harness)))
140
+ refuse(403, "connector_source_denied");
141
+ if (row.ingestion_mode === "otlp" &&
142
+ (sources.some((s) => s.mode !== "harness") ||
143
+ new Set(sources.map((s) => s.harness)).size !== sources.length))
144
+ refuse(422, "connector_invalid");
145
+ }
146
+ export const observationCapabilities = () => ({
147
+ version: 1,
148
+ ingestion_modes: ["polling", "otlp"],
149
+ supported_harnesses: [...NATIVE_OBSERVATION_HARNESSES],
150
+ logs_formats: ["json"],
151
+ logs_endpoint_template: "/api/v2/control/connectors/{connector_id}/otel/v1/logs",
152
+ selections_revision_header: "X-AgentRun-Selections-Revision",
153
+ max_log_records: 100,
154
+ max_payload_bytes: MAX_OTLP_PAYLOAD_BYTES,
155
+ token_usage: {
156
+ supported_harnesses: [...NATIVE_OBSERVATION_HARNESSES],
157
+ model_attribute: "agentrun.model",
158
+ count_attributes: COUNTS.map((k) => "agentrun." + k),
159
+ input_includes_cache: true,
160
+ },
161
+ privacy: {
162
+ metadata_only: true,
163
+ session_id_attribute: "agentrun.session_id",
164
+ session_id_format: "sha256",
165
+ raw_session_ids: false,
166
+ },
167
+ });
168
+ export class Observations {
169
+ store;
170
+ now;
171
+ constructor(store, now = Date.now) {
172
+ this.store = store;
173
+ this.now = now;
174
+ }
175
+ stamp() {
176
+ return new Date(this.now()).toISOString();
177
+ }
178
+ async rows() {
179
+ return (await this.store.settings.all({ prefix: PREFIX }))
180
+ .filter((r) => r.key.startsWith(PREFIX))
181
+ .map((r) => r.value);
182
+ }
183
+ async row(connectorId) {
184
+ const r = (await this.store.settings.get(key(connectorId)));
185
+ if (!r)
186
+ refuse(404, "connector_not_found");
187
+ return r;
188
+ }
189
+ authorize(row, credential) {
190
+ if (row.state !== "active" ||
191
+ Date.parse(row.credential_expires_at) <= this.now() ||
192
+ !credential.startsWith("arc_") ||
193
+ !timingSafeEqual(Buffer.from(hash(credential)), Buffer.from(row.credential_hash)))
194
+ refuse(401, "connector_unauthorized");
195
+ }
196
+ async authenticate(connectorId, credential) {
197
+ const r = (await this.store.settings.get(key(connectorId)));
198
+ if (!r)
199
+ refuse(401, "connector_unauthorized");
200
+ this.authorize(r, credential);
201
+ }
202
+ async change(connectorId, edit, credential) {
203
+ for (let tries = 0; tries < 30; tries++) {
204
+ const previous = await this.row(connectorId);
205
+ if (credential !== undefined)
206
+ this.authorize(previous, credential);
207
+ const next = structuredClone(previous);
208
+ const answer = edit(next);
209
+ next.updated_at = this.stamp();
210
+ if (await this.store.settings.replaceIf(key(connectorId), previous, next))
211
+ return answer;
212
+ }
213
+ return refuse(503, "connector_busy");
214
+ }
215
+ summary(row) {
216
+ return {
217
+ id: row.id,
218
+ workspace_id: "local",
219
+ kind: "connector",
220
+ state: row.state,
221
+ display_name: row.display_name,
222
+ owner_user_id: "owner",
223
+ cli_version: row.cli_version,
224
+ adapters: row.adapters,
225
+ ingestion_mode: row.ingestion_mode,
226
+ selections: row.selections,
227
+ selections_revision: row.selections_revision,
228
+ last_heartbeat_at: row.last_heartbeat_at,
229
+ dropped_events: row.dropped_events,
230
+ created_at: row.created_at,
231
+ updated_at: row.updated_at,
232
+ can_manage: true,
233
+ receipt_count: Object.keys(row.receipts).length,
234
+ receipt_capacity: MAX_RECEIPTS,
235
+ storage_full: Object.keys(row.receipts).length >= MAX_RECEIPTS,
236
+ connection_state: row.state === "revoked"
237
+ ? "disconnected"
238
+ : Date.parse(row.credential_expires_at) <= this.now()
239
+ ? "offline"
240
+ : row.last_heartbeat_at &&
241
+ Date.parse(row.last_heartbeat_at) + OFFLINE > this.now()
242
+ ? "online"
243
+ : "offline",
244
+ };
245
+ }
246
+ async register(input) {
247
+ const b = obj(input);
248
+ exact(b, [
249
+ "workspace_id",
250
+ "installation_id",
251
+ "operation_id",
252
+ "display_name",
253
+ "cli_version",
254
+ "adapters",
255
+ "selections",
256
+ "ingestion_mode",
257
+ ]);
258
+ if (b.workspace_id !== "local")
259
+ refuse(403, "workspace_not_authorized");
260
+ if (!uuid(b.installation_id) ||
261
+ !uuid(b.operation_id) ||
262
+ typeof b.display_name !== "string" ||
263
+ !/^[^/\\\x00-\x1f\x7f]{1,80}$/.test(b.display_name) ||
264
+ typeof b.cli_version !== "string" ||
265
+ !/^[A-Za-z0-9_.+\-]{1,64}$/.test(b.cli_version) ||
266
+ !Array.isArray(b.adapters) ||
267
+ b.adapters.length < 1 ||
268
+ b.adapters.length > 2 ||
269
+ !["polling", "otlp"].includes(b.ingestion_mode ?? "polling"))
270
+ refuse(422, "connector_invalid");
271
+ const adapters = b.adapters.map((v) => {
272
+ const a = obj(v);
273
+ exact(a, ["harness", "adapter_version", "activity"]);
274
+ if (!harness(a.harness) ||
275
+ typeof a.adapter_version !== "string" ||
276
+ !/^[A-Za-z0-9_.+\-]{1,64}$/.test(a.adapter_version) ||
277
+ !["unknown", "lifecycle"].includes(a.activity))
278
+ refuse(422, "connector_invalid");
279
+ return a;
280
+ });
281
+ if (new Set(adapters.map((a) => a.harness)).size !== adapters.length)
282
+ refuse(422, "connector_invalid");
283
+ const selected = selections(b.selections);
284
+ if (!selected.length)
285
+ refuse(422, "connector_invalid");
286
+ checkMode({ adapters, ingestion_mode: b.ingestion_mode ?? "polling" }, selected);
287
+ // Installation id chooses one durable connector; registration retries rotate via the owner-only endpoint.
288
+ const connectorId = "oc_" + hash(b.installation_id).slice(0, 40);
289
+ const prior = await this.store.settings.get(key(connectorId));
290
+ const credential = "arc_" + randomBytes(48).toString("base64url");
291
+ if (prior) {
292
+ // Re-enrollment is an owner grant. A revoked connector can adopt the newly approved
293
+ // mode, but a concurrent active connection cannot be silently replaced. Keep its
294
+ // receipts and history; fresh credentials and revision fence all previous uploads.
295
+ return this.change(connectorId, (row) => {
296
+ if (row.state !== "revoked")
297
+ refuse(409, "connector_reauthentication_required", { connector_id: connectorId });
298
+ for (const s of selected) {
299
+ const f = fingerprint(s);
300
+ if (Object.hasOwn(row.source_bindings, s.source_id) && row.source_bindings[s.source_id] !== f)
301
+ refuse(409, "connector_source_rebound");
302
+ Object.defineProperty(row.source_bindings, s.source_id, {
303
+ value: f, enumerable: true, writable: true, configurable: true,
304
+ });
305
+ }
306
+ if (Object.keys(row.source_bindings).length > 1000)
307
+ refuse(422, "connector_source_limit");
308
+ const mode = b.ingestion_mode ?? "polling";
309
+ if (row.ingestion_mode !== mode)
310
+ row.ingestion_epoch = (row.ingestion_epoch ?? 0) + 1;
311
+ row.ingestion_mode = mode;
312
+ row.adapters = adapters;
313
+ row.selections = selected;
314
+ row.selections_revision++;
315
+ row.display_name = b.display_name;
316
+ row.cli_version = b.cli_version;
317
+ row.operation_id = b.operation_id;
318
+ row.credential_hash = hash(credential);
319
+ row.credential_expires_at = new Date(this.now() + 90 * DAY).toISOString();
320
+ row.state = "active";
321
+ row.last_heartbeat_at = null;
322
+ return { connector: this.summary(row), credential, credential_expires_at: row.credential_expires_at };
323
+ });
324
+ }
325
+ const row = {
326
+ id: connectorId,
327
+ workspace_id: "local",
328
+ installation_id: b.installation_id,
329
+ operation_id: b.operation_id,
330
+ display_name: b.display_name,
331
+ cli_version: b.cli_version,
332
+ adapters,
333
+ ingestion_mode: b.ingestion_mode ?? "polling",
334
+ selections: selected,
335
+ selections_revision: 1,
336
+ source_bindings: Object.fromEntries(selected.map((s) => [s.source_id, fingerprint(s)])),
337
+ credential_hash: hash(credential),
338
+ credential_expires_at: new Date(this.now() + 90 * DAY).toISOString(),
339
+ state: "active",
340
+ created_at: this.stamp(),
341
+ updated_at: this.stamp(),
342
+ last_heartbeat_at: null,
343
+ dropped_events: 0,
344
+ window: 0,
345
+ count: 0,
346
+ sessions: {},
347
+ receipts: {},
348
+ receipt_floor: 0,
349
+ };
350
+ const saved = (await this.store.settings.putIfAbsent(key(connectorId), row, { prefix: PREFIX, limit: MAX_CONNECTORS }));
351
+ if (saved === undefined)
352
+ refuse(429, "connector_capacity_exceeded");
353
+ if (saved.credential_hash !== row.credential_hash)
354
+ refuse(409, "connector_reauthentication_required", {
355
+ connector_id: connectorId,
356
+ });
357
+ return {
358
+ connector: this.summary(saved),
359
+ credential,
360
+ credential_expires_at: saved.credential_expires_at,
361
+ };
362
+ }
363
+ async rotate(connectorId) {
364
+ const credential = "arc_" + randomBytes(48).toString("base64url");
365
+ return this.change(connectorId, (row) => {
366
+ row.state = "active";
367
+ row.credential_hash = hash(credential);
368
+ row.credential_expires_at = new Date(this.now() + 90 * DAY).toISOString();
369
+ row.last_heartbeat_at = null;
370
+ return {
371
+ connector: this.summary(row),
372
+ credential,
373
+ credential_expires_at: row.credential_expires_at,
374
+ };
375
+ });
376
+ }
377
+ async revoke(connectorId) {
378
+ return this.change(connectorId, (row) => {
379
+ row.state = "revoked";
380
+ return this.summary(row);
381
+ });
382
+ }
383
+ async select(connectorId, input) {
384
+ const b = obj(input);
385
+ exact(b, ["selections_revision", "selections"]);
386
+ const selected = selections(b.selections);
387
+ return this.change(connectorId, (row) => {
388
+ if (b.selections_revision !== row.selections_revision)
389
+ refuse(409, "connector_selection_revision_mismatch", {
390
+ selections_revision: row.selections_revision,
391
+ });
392
+ checkMode(row, selected);
393
+ for (const s of selected) {
394
+ const f = fingerprint(s);
395
+ if (Object.hasOwn(row.source_bindings, s.source_id) &&
396
+ row.source_bindings[s.source_id] !== f)
397
+ refuse(409, "connector_source_rebound");
398
+ Object.defineProperty(row.source_bindings, s.source_id, {
399
+ value: f,
400
+ enumerable: true,
401
+ writable: true,
402
+ configurable: true,
403
+ });
404
+ }
405
+ if (Object.keys(row.source_bindings).length > 1000)
406
+ refuse(422, "connector_source_limit");
407
+ if (canonical(row.selections) !== canonical(selected)) {
408
+ row.selections = selected;
409
+ row.selections_revision++;
410
+ }
411
+ return this.summary(row);
412
+ });
413
+ }
414
+ async heartbeat(connectorId, credential, input) {
415
+ const b = obj(input);
416
+ exact(b, ["dropped_events"]);
417
+ if (!safeInt(b.dropped_events ?? 0))
418
+ refuse(422, "connector_invalid");
419
+ return this.change(connectorId, (row) => {
420
+ row.last_heartbeat_at = this.stamp();
421
+ row.dropped_events = Math.max(row.dropped_events, b.dropped_events ?? 0);
422
+ return {
423
+ connector_id: row.id,
424
+ selections_revision: row.selections_revision,
425
+ selections: row.selections,
426
+ heartbeat_interval_seconds: 30,
427
+ };
428
+ }, credential);
429
+ }
430
+ async events(connectorId, credential, input) {
431
+ const b = obj(input);
432
+ exact(b, ["selections_revision", "events"]);
433
+ if (!safeInt(b.selections_revision, 1) ||
434
+ !Array.isArray(b.events) ||
435
+ b.events.length < 1 ||
436
+ b.events.length > 100)
437
+ refuse(422, "connector_invalid");
438
+ const events = b.events.map((v) => {
439
+ const e = obj(v);
440
+ exact(e, [
441
+ "event_id",
442
+ "source_id",
443
+ "external_session_id",
444
+ "sequence",
445
+ "type",
446
+ "occurred_at",
447
+ "metadata",
448
+ ]);
449
+ const m = obj(e.metadata);
450
+ exact(m, ["harness", "activity"]);
451
+ if (!uuid(e.event_id) ||
452
+ !id(e.source_id) ||
453
+ !id(e.external_session_id) ||
454
+ !safeInt(e.sequence, 1) ||
455
+ e.type !== "session_observed" ||
456
+ !timestamp(e.occurred_at) ||
457
+ Date.parse(e.occurred_at) > this.now() + 300_000 ||
458
+ !harness(m.harness) ||
459
+ !activities.has(m.activity))
460
+ refuse(422, "connector_invalid");
461
+ return e;
462
+ });
463
+ return this.ingest(connectorId, credential, b.selections_revision, events, "polling");
464
+ }
465
+ async ingest(connectorId, credential, revision, events, mode) {
466
+ return this.change(connectorId, (row) => {
467
+ if (row.ingestion_mode !== mode)
468
+ refuse(409, "connector_ingestion_mode_mismatch");
469
+ if (row.selections_revision !== revision)
470
+ refuse(409, "connector_selection_revision_mismatch", {
471
+ selections_revision: row.selections_revision,
472
+ });
473
+ pruneConnector(row, this.now(), true);
474
+ const window = Math.floor(this.now() / 60_000);
475
+ if (row.window !== window) {
476
+ row.window = window;
477
+ row.count = 0;
478
+ }
479
+ let receiptCount = Object.keys(row.receipts).length;
480
+ for (const e of events) {
481
+ const source = row.selections.find((s) => s.source_id === e.source_id && s.harness === e.metadata.harness);
482
+ if (!source ||
483
+ (source.mode === "session" &&
484
+ source.external_session_id !== e.external_session_id))
485
+ refuse(403, "connector_source_denied");
486
+ if (Date.parse(e.occurred_at) < row.receipt_floor)
487
+ continue;
488
+ const request = fingerprint(e), prior = row.receipts[e.event_id];
489
+ if (prior) {
490
+ if (prior.hash !== request)
491
+ refuse(409, "idempotency_conflict");
492
+ continue;
493
+ }
494
+ if (row.count >= 2000)
495
+ refuse(429, "connector_rate_limited");
496
+ if (receiptCount >= MAX_RECEIPTS)
497
+ refuse(429, "connector_receipt_capacity_exceeded", {
498
+ retry_after_seconds: Math.max(1, Math.ceil((Object.values(row.receipts).reduce((earliest, r) => Math.min(earliest, Date.parse(r.occurred_at)), Infinity) +
499
+ RECEIPT_WINDOW -
500
+ this.now()) /
501
+ 1000)),
502
+ });
503
+ const sessionId = "os_" +
504
+ hash([connectorId, e.metadata.harness, e.external_session_id].join(":")).slice(0, 40), old = row.sessions[sessionId];
505
+ if (!old && Object.keys(row.sessions).length >= MAX_SESSIONS)
506
+ refuse(429, "connector_session_capacity_exceeded");
507
+ const at = this.stamp();
508
+ row.receipts[e.event_id] = {
509
+ hash: request,
510
+ occurred_at: e.occurred_at,
511
+ };
512
+ receiptCount++;
513
+ row.count++;
514
+ const newer = (old?.ingestion_epoch ?? 0) !== (row.ingestion_epoch ?? 0) || (mode === "otlp"
515
+ ? BigInt(e.source_time) >
516
+ BigInt(old?.source_time ?? String((old?.sequence ?? 0) * 1000))
517
+ : e.sequence > (old?.sequence ?? 0));
518
+ if (!old || (!e.initial_only && newer))
519
+ row.sessions[sessionId] = {
520
+ id: sessionId,
521
+ source_id: e.source_id,
522
+ external_session_id: e.external_session_id,
523
+ harness: e.metadata.harness,
524
+ activity: e.metadata.activity,
525
+ sequence: e.sequence,
526
+ ingestion_epoch: row.ingestion_epoch ?? 0,
527
+ ...(e.source_time ? { source_time: e.source_time } : {}),
528
+ occurred_at: e.occurred_at,
529
+ received_at: at,
530
+ created_at: old?.created_at ?? at,
531
+ updated_at: at,
532
+ usage_by_day: old?.usage_by_day ?? {},
533
+ };
534
+ if (e.usage) {
535
+ const session = row.sessions[sessionId];
536
+ const date = at.slice(0, 10);
537
+ const day = (session.usage_by_day[date] ??= {});
538
+ const previous = Object.hasOwn(day, e.usage.model)
539
+ ? day[e.usage.model]
540
+ : undefined;
541
+ const next = empty();
542
+ if (previous)
543
+ plus(next, previous);
544
+ plus(next, e.usage);
545
+ day[e.usage.model] = {
546
+ model: e.usage.model,
547
+ input_tokens: next.input_tokens,
548
+ output_tokens: next.output_tokens,
549
+ ...(next.cache_read_tokens === null
550
+ ? {}
551
+ : { cache_read_tokens: next.cache_read_tokens }),
552
+ ...(next.cache_write_tokens === null
553
+ ? {}
554
+ : { cache_write_tokens: next.cache_write_tokens }),
555
+ };
556
+ // Reject before committing if this connector's retained aggregates exceed exact integer accounting.
557
+ const total = empty();
558
+ for (const saved of Object.values(row.sessions))
559
+ for (const daily of Object.values(saved.usage_by_day))
560
+ for (const u of Object.values(daily))
561
+ plus(total, u);
562
+ }
563
+ }
564
+ if (mode === "otlp" && events.length)
565
+ row.last_heartbeat_at = this.stamp();
566
+ return { accepted_event_ids: events.map((e) => e.event_id) };
567
+ }, credential);
568
+ }
569
+ async otlp(connectorId, credential, input, revision) {
570
+ if (!safeInt(revision, 1))
571
+ refuse(400, "connector_otlp_invalid");
572
+ const b = obj(input), resources = b.resourceLogs ?? b.resource_logs ?? [];
573
+ if (!Array.isArray(resources) || resources.length > 100)
574
+ refuse(400, "connector_otlp_invalid");
575
+ const events = [];
576
+ let rejected = 0, total = 0;
577
+ const current = await this.row(connectorId);
578
+ this.authorize(current, credential);
579
+ if (current.ingestion_mode !== "otlp")
580
+ refuse(409, "connector_ingestion_mode_mismatch");
581
+ if (current.selections_revision !== revision)
582
+ refuse(409, "connector_selection_revision_mismatch", {
583
+ selections_revision: current.selections_revision,
584
+ });
585
+ for (const item of resources) {
586
+ const resource = obj(item), attrs = attributes(obj(resource.resource ?? {}).attributes ?? []);
587
+ const h = stringValue(attrs["agentrun.harness"]), source = stringValue(attrs["agentrun.source_id"]);
588
+ if (!current.selections.some((s) => s.source_id === source &&
589
+ s.harness === h &&
590
+ s.mode === "harness" &&
591
+ s.include_future_sessions))
592
+ refuse(403, "connector_source_denied");
593
+ const scopes = resource.scopeLogs ?? resource.scope_logs ?? [];
594
+ if (!Array.isArray(scopes) || scopes.length > 100)
595
+ refuse(400, "connector_otlp_invalid");
596
+ for (const value of scopes) {
597
+ const scope = obj(value), logs = scope.logRecords ?? scope.log_records ?? [];
598
+ if (!Array.isArray(logs) || (total += logs.length) > 100)
599
+ refuse(413, "request_too_large");
600
+ for (const record of logs) {
601
+ const log = obj(record), a = attributes(log.attributes ?? []), name = stringValue(a["event.name"]), session = stringValue(a["agentrun.session_id"]);
602
+ const activity = nativeActivity(h, name), rawStamp = log.timeUnixNano ?? log.time_unix_nano;
603
+ let nanos;
604
+ try {
605
+ if (typeof rawStamp !== "string" || !/^\d{1,20}$/.test(rawStamp))
606
+ throw Error();
607
+ nanos = BigInt(rawStamp);
608
+ }
609
+ catch {
610
+ rejected++;
611
+ continue;
612
+ }
613
+ if (!activity ||
614
+ !session ||
615
+ !/^[0-9a-f]{64}$/.test(session) ||
616
+ nanos / 1000000n <
617
+ BigInt(Math.max(current.receipt_floor ?? 0, this.now() - RECEIPT_WINDOW)) ||
618
+ nanos / 1000n < 1n ||
619
+ nanos / 1000n > BigInt(Number.MAX_SAFE_INTEGER) ||
620
+ nanos > BigInt(this.now() + 300_000) * 1000000n) {
621
+ rejected++;
622
+ continue;
623
+ }
624
+ let usage;
625
+ try {
626
+ usage = nativeUsage(h, name, a);
627
+ }
628
+ catch {
629
+ rejected++;
630
+ continue;
631
+ }
632
+ const event = {
633
+ event_id: "",
634
+ source_id: source,
635
+ external_session_id: session,
636
+ sequence: Number(nanos / 1000n),
637
+ type: "session_observed",
638
+ occurred_at: new Date(Number(nanos / 1000000n)).toISOString(),
639
+ metadata: { harness: h, activity },
640
+ source_time: nanos.toString(),
641
+ ...(usage ? { usage } : {}),
642
+ ...(name === "codex.conversation_starts"
643
+ ? { initial_only: true }
644
+ : {}),
645
+ };
646
+ // Deterministic id comes solely from normalized allowlisted metadata, never discarded prompt/tool payloads.
647
+ event.event_id = hash(canonical({ name, ...event }));
648
+ events.push(event);
649
+ }
650
+ }
651
+ }
652
+ // Empty/fully rejected payload still checks the latest scoped credential, mode and selection revision under CAS.
653
+ await this.ingest(connectorId, credential, revision, events, "otlp");
654
+ return rejected
655
+ ? {
656
+ partialSuccess: {
657
+ rejectedLogRecords: String(rejected),
658
+ errorMessage: "Some records were not valid selected session metadata.",
659
+ },
660
+ }
661
+ : {};
662
+ }
663
+ /** Remove expired persisted metadata even when a source is idle or revoked. CAS retries start from the
664
+ * newest connector, so retention never restores a revoked credential or overwrites concurrent ingestion. */
665
+ async sweep() {
666
+ let changed = 0;
667
+ for (const scanned of await this.rows()) {
668
+ let settled = false;
669
+ for (let attempt = 0; attempt < 30; attempt++) {
670
+ const previous = attempt === 0 ? scanned : await this.row(scanned.id);
671
+ const next = structuredClone(previous);
672
+ if (!pruneConnector(next, this.now())) {
673
+ settled = true;
674
+ break;
675
+ }
676
+ next.updated_at = this.stamp();
677
+ if (await this.store.settings.replaceIf(key(scanned.id), previous, next)) {
678
+ changed++;
679
+ settled = true;
680
+ break;
681
+ }
682
+ }
683
+ if (!settled)
684
+ refuse(503, "connector_busy");
685
+ }
686
+ return { pruned_connectors: changed };
687
+ }
688
+ async list() {
689
+ return {
690
+ items: (await this.rows()).map((r) => this.summary(r)),
691
+ next_cursor: null,
692
+ };
693
+ }
694
+ async snapshot(days = 30, sessionId) {
695
+ if (!Number.isInteger(days) || days < 1 || days > 31)
696
+ refuse(422, "token_usage_period_invalid");
697
+ const rows = await this.rows(), sessions = [], usage = empty(), models = new Map(), daily = new Map();
698
+ let reports = 0;
699
+ const start = Date.parse(this.stamp().slice(0, 10)) - (days - 1) * DAY;
700
+ for (const row of rows) {
701
+ const summaries = new Map();
702
+ for (const session of Object.values(row.sessions)) {
703
+ if (sessionId && session.id !== sessionId)
704
+ continue;
705
+ const own = { usage: empty(), models: new Set() };
706
+ for (const [date, dailyUsage] of Object.entries(session.usage_by_day))
707
+ for (const u of Object.values(dailyUsage)) {
708
+ if (Date.parse(date) + DAY < this.now() - SESSION_WINDOW)
709
+ continue;
710
+ plus(own.usage, u);
711
+ own.models.add(u.model);
712
+ if (Date.parse(date) + DAY <= start)
713
+ continue;
714
+ reports++;
715
+ plus(usage, u, false);
716
+ const model = models.get(u.model) ?? empty();
717
+ plus(model, u, false);
718
+ models.set(u.model, model);
719
+ daily.set(date, Math.min(Number.MAX_SAFE_INTEGER, (daily.get(date) ?? 0) + u.input_tokens + u.output_tokens));
720
+ }
721
+ if (own.models.size)
722
+ summaries.set(session.id, own);
723
+ }
724
+ const connector = this.summary(row);
725
+ for (const s of Object.values(row.sessions)) {
726
+ if (sessionId && s.id !== sessionId)
727
+ continue;
728
+ if (Date.parse(s.received_at) < this.now() - SESSION_WINDOW)
729
+ continue;
730
+ const active = row.state === "active" &&
731
+ row.selections.some((v) => v.source_id === s.source_id &&
732
+ v.harness === s.harness &&
733
+ (v.mode !== "session" ||
734
+ v.external_session_id === s.external_session_id));
735
+ const stale = Math.min(Date.parse(s.received_at), Date.parse(s.occurred_at)) +
736
+ OFFLINE <=
737
+ this.now();
738
+ const terminal = ["finished", "failed", "stopped"].includes(s.activity);
739
+ const summary = summaries.get(s.id);
740
+ const { usage_by_day, ingestion_epoch, ...shown } = s;
741
+ sessions.push({
742
+ ...shown,
743
+ connector_id: row.id,
744
+ workspace_id: "local",
745
+ kind: "connected_session",
746
+ state: "active",
747
+ display_name: `${row.display_name} · ${s.harness === "claude" ? "Claude Code" : "Codex"}`,
748
+ reported_activity: s.activity,
749
+ activity: terminal
750
+ ? s.activity
751
+ : stale || !active || connector.connection_state !== "online"
752
+ ? "unknown"
753
+ : s.activity,
754
+ connection_state: connector.connection_state,
755
+ selection_active: active,
756
+ observation_only: true,
757
+ models: [...(summary?.models ?? [])],
758
+ usage: {
759
+ ...(summary?.usage ?? unavailable()),
760
+ status: summary ? "reported" : "unavailable",
761
+ },
762
+ });
763
+ }
764
+ }
765
+ sessions.sort((a, b) => b.received_at.localeCompare(a.received_at));
766
+ return {
767
+ connectors: rows.map((r) => this.summary(r)),
768
+ sessions,
769
+ usage: {
770
+ ...readableTotals(reports ? usage : unavailable()),
771
+ status: reports && !usage.overflow ? "partial" : "unavailable",
772
+ models: [...models].map(([model, counts]) => ({
773
+ model,
774
+ ...readableTotals(counts),
775
+ })),
776
+ daily: [...daily].sort().map(([date, total_tokens]) => ({
777
+ date,
778
+ total_tokens: usage.overflow ? null : total_tokens,
779
+ })),
780
+ coverage: "reported_tokens_only",
781
+ },
782
+ limits: {
783
+ max_receipts_per_connector: MAX_RECEIPTS,
784
+ max_sessions_per_connector: MAX_SESSIONS,
785
+ receipt_retention: "7 days; older event timestamps are refused",
786
+ receipt_window_seconds: RECEIPT_WINDOW / 1000,
787
+ session_retention_days: 90,
788
+ usage_retention_days: 90,
789
+ },
790
+ };
791
+ }
792
+ }
793
+ function attributes(input) {
794
+ if (!Array.isArray(input) || input.length > 128)
795
+ refuse(400, "connector_otlp_invalid");
796
+ const result = Object.create(null);
797
+ for (const item of input) {
798
+ const a = obj(item);
799
+ if (typeof a.key !== "string" || Object.hasOwn(result, a.key))
800
+ refuse(400, "connector_otlp_invalid");
801
+ result[a.key] = obj(a.value ?? {});
802
+ }
803
+ return result;
804
+ }
805
+ const stringValue = (v) => typeof (v?.stringValue ?? v?.string_value) === "string"
806
+ ? (v?.stringValue ?? v?.string_value)
807
+ : undefined;
808
+ function nativeActivity(h, name) {
809
+ if (!name)
810
+ return;
811
+ if (name.startsWith("agentrun.session.")) {
812
+ const state = name.slice("agentrun.session.".length);
813
+ return activities.has(state) ? state : undefined;
814
+ }
815
+ const events = nativeObservationProtocol(h)?.activityEvents;
816
+ return events && Object.hasOwn(events, name) ? events[name] : undefined;
817
+ }
818
+ function nativeUsage(h, name, a) {
819
+ const protocol = nativeObservationProtocol(h);
820
+ if (!protocol?.usageEvents.includes(name))
821
+ return;
822
+ if (!["agentrun.model", ...COUNTS.map((k) => "agentrun." + k)].some((k) => a[k] !== undefined))
823
+ return;
824
+ const model = stringValue(a["agentrun.model"]);
825
+ if (!model || !/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,127}$/.test(model))
826
+ throw Error();
827
+ const usage = { model };
828
+ for (const k of COUNTS) {
829
+ const v = a["agentrun." + k];
830
+ if (!v) {
831
+ if (protocol.requireCacheUsage || k === "input_tokens" || k === "output_tokens")
832
+ throw Error();
833
+ continue;
834
+ }
835
+ const raw = v.intValue ?? v.int_value;
836
+ if (typeof raw !== "string" && typeof raw !== "number")
837
+ throw Error();
838
+ if (typeof raw === "string" && !/^\d+$/.test(raw))
839
+ throw Error();
840
+ const n = Number(raw);
841
+ if (!safeInt(n))
842
+ throw Error();
843
+ usage[k] = n;
844
+ }
845
+ if ((usage.cache_read_tokens ?? 0) + (usage.cache_write_tokens ?? 0) >
846
+ usage.input_tokens ||
847
+ !Number.isSafeInteger(usage.input_tokens + usage.output_tokens))
848
+ throw Error();
849
+ return usage;
850
+ }
851
+ function readableTotals(total) {
852
+ return total.overflow
853
+ ? {
854
+ ...total,
855
+ input_tokens: null,
856
+ output_tokens: null,
857
+ cache_read_tokens: null,
858
+ cache_write_tokens: null,
859
+ total_tokens: null,
860
+ cache_hit_rate: null,
861
+ }
862
+ : total;
863
+ }
864
+ /** The floor advances whenever metadata is removed, even if the wall clock subsequently moves backwards.
865
+ * Keep usage that arrived after the last activity update until its own retention ends. Hidden stale activity
866
+ * must not erase a newer, already accepted usage receipt. No-op sweeps leave the settings row untouched. */
867
+ function pruneConnector(row, now, advanceFloor = false) {
868
+ let changed = false;
869
+ const floor = Math.max(row.receipt_floor ?? 0, now - RECEIPT_WINDOW);
870
+ for (const [eventId, receipt] of Object.entries(row.receipts)) {
871
+ if (Date.parse(receipt.occurred_at) < floor) {
872
+ delete row.receipts[eventId];
873
+ changed = true;
874
+ }
875
+ }
876
+ for (const [sessionId, session] of Object.entries(row.sessions)) {
877
+ for (const day of Object.keys(session.usage_by_day)) {
878
+ if (Date.parse(day) + DAY < now - SESSION_WINDOW) {
879
+ delete session.usage_by_day[day];
880
+ changed = true;
881
+ }
882
+ }
883
+ if (Date.parse(session.received_at) < now - SESSION_WINDOW &&
884
+ Object.keys(session.usage_by_day).length === 0) {
885
+ delete row.sessions[sessionId];
886
+ changed = true;
887
+ }
888
+ }
889
+ if (changed || advanceFloor)
890
+ row.receipt_floor = floor;
891
+ return changed;
892
+ }
893
+ /** Start with one awaited sweep, then run one at a time. Stopping drains the last sweep before store close. */
894
+ export async function maintainObservations(observer, options = {}) {
895
+ await observer.sweep();
896
+ let stopped = false;
897
+ let pending = Promise.resolve();
898
+ let timer;
899
+ const schedule = () => {
900
+ if (stopped)
901
+ return;
902
+ timer = setTimeout(() => {
903
+ pending = observer
904
+ .sweep()
905
+ .then(() => undefined)
906
+ .catch((error) => {
907
+ options.onError?.(error);
908
+ })
909
+ .finally(schedule);
910
+ }, options.intervalMs ?? 60_000);
911
+ timer.unref();
912
+ };
913
+ schedule();
914
+ return async () => {
915
+ stopped = true;
916
+ clearTimeout(timer);
917
+ await pending;
918
+ };
919
+ }