@parcha/agentrun-serve 0.1.0-beta.58 → 0.1.0-beta.60

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 (474) hide show
  1. package/CHANGELOG.md +402 -1
  2. package/README.md +516 -190
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agent-delete.d.ts +6 -9
  8. package/dist/agent-delete.js +5 -3
  9. package/dist/agent-package.js +11 -1
  10. package/dist/agents-store.js +1 -1
  11. package/dist/answer-text.d.ts +3 -0
  12. package/dist/answer-text.js +22 -0
  13. package/dist/api-only.d.ts +2 -2
  14. package/dist/api-only.js +3 -3
  15. package/dist/archil-routes.d.ts +4 -1
  16. package/dist/archil-routes.js +15 -12
  17. package/dist/archil-settings.d.ts +18 -8
  18. package/dist/archil-settings.js +35 -17
  19. package/dist/attach-conformance.js +5 -4
  20. package/dist/box-paths.d.ts +3 -2
  21. package/dist/box-paths.js +5 -4
  22. package/dist/browser-computer.d.ts +3 -8
  23. package/dist/browser-computer.js +12 -35
  24. package/dist/browser-cost.js +94 -20
  25. package/dist/capacity.d.ts +1 -1
  26. package/dist/capacity.js +3 -3
  27. package/dist/chatgpt-plan.d.ts +7 -0
  28. package/dist/chatgpt-plan.js +35 -11
  29. package/dist/claude-login-token.d.ts +20 -11
  30. package/dist/claude-login-token.js +175 -107
  31. package/dist/claude-login.d.ts +124 -33
  32. package/dist/claude-login.js +562 -85
  33. package/dist/claude-sign-in.d.ts +3 -0
  34. package/dist/claude-sign-in.js +10 -1
  35. package/dist/cli-learning/connections.js +1 -1
  36. package/dist/cli.js +323 -292
  37. package/dist/composio-made.d.ts +1 -6
  38. package/dist/composio-made.js +1 -6
  39. package/dist/composio-owners.d.ts +26 -0
  40. package/dist/composio-owners.js +36 -0
  41. package/dist/composio-preset.d.ts +56 -23
  42. package/dist/composio-preset.js +173 -77
  43. package/dist/composio-triggers.d.ts +4 -4
  44. package/dist/composio-triggers.js +6 -7
  45. package/dist/compute-cost.js +11 -2
  46. package/dist/computer-attach.d.ts +6 -3
  47. package/dist/computer-attach.js +41 -29
  48. package/dist/computer-held-routes.d.ts +1 -1
  49. package/dist/computer-held-routes.js +9 -4
  50. package/dist/computer-keys.d.ts +11 -1
  51. package/dist/computer-keys.js +26 -1
  52. package/dist/computer-record.js +3 -1
  53. package/dist/computer-view.d.ts +5 -3
  54. package/dist/computer-view.js +10 -6
  55. package/dist/computer-viewer.js +36 -7
  56. package/dist/computers.d.ts +2 -1
  57. package/dist/computers.js +6 -3
  58. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  59. package/dist/console/assets/backend-QnwGVBeU.js +166 -0
  60. package/dist/console/assets/index-DZi-muIj.js +629 -0
  61. package/dist/console/assets/share-pz61zIn9.js +6 -0
  62. package/dist/console/assets/styles-CcceGcu2.js +291 -0
  63. package/dist/console/assets/styles-fjQBFfMv.css +1 -0
  64. package/dist/console/index.html +4 -3
  65. package/dist/console/share.html +17 -0
  66. package/dist/decisions.d.ts +17 -7
  67. package/dist/decisions.js +41 -15
  68. package/dist/dial-relay.js +10 -4
  69. package/dist/docker-daemon.js +4 -5
  70. package/dist/docker-host-addresses.js +29 -11
  71. package/dist/email/account.d.ts +6 -0
  72. package/dist/email/account.js +6 -0
  73. package/dist/email/authentication.d.ts +21 -0
  74. package/dist/email/authentication.js +106 -0
  75. package/dist/email/email-faux.d.ts +11 -2
  76. package/dist/email/email-faux.js +21 -5
  77. package/dist/email/mail.d.ts +25 -0
  78. package/dist/email/mail.js +58 -2
  79. package/dist/email/names.js +2 -2
  80. package/dist/email/tools.d.ts +9 -4
  81. package/dist/email/tools.js +95 -13
  82. package/dist/env-switch.d.ts +12 -2
  83. package/dist/env-switch.js +23 -3
  84. package/dist/errors.d.ts +1 -0
  85. package/dist/errors.js +2 -0
  86. package/dist/factory-activity.d.ts +68 -0
  87. package/dist/factory-activity.js +153 -0
  88. package/dist/factory-runs.d.ts +11 -0
  89. package/dist/factory-runs.js +52 -0
  90. package/dist/fal-price.d.ts +11 -1
  91. package/dist/fal-price.js +33 -0
  92. package/dist/faux-computers.js +1 -1
  93. package/dist/filed-answer.d.ts +2 -2
  94. package/dist/filed-answer.js +2 -2
  95. package/dist/filed-tool.d.ts +32 -0
  96. package/dist/filed-tool.js +122 -0
  97. package/dist/graph-served.d.ts +10 -5
  98. package/dist/graph-served.js +40 -10
  99. package/dist/handed-values.js +1 -2
  100. package/dist/harness-check.d.ts +2 -1
  101. package/dist/harness-check.js +45 -12
  102. package/dist/harness-keys.d.ts +1 -2
  103. package/dist/harness-keys.js +10 -8
  104. package/dist/harness-opencode/facts.js +2 -0
  105. package/dist/harness-recipe-entry.d.ts +9 -3
  106. package/dist/harness-recipe-entry.js +18 -9
  107. package/dist/harness-recipe.d.ts +21 -0
  108. package/dist/harness-recipe.js +25 -3
  109. package/dist/harness-table.d.ts +12 -0
  110. package/dist/harness-table.js +21 -6
  111. package/dist/harness.js +6 -2
  112. package/dist/helper-env.d.ts +4 -1
  113. package/dist/helper-env.js +4 -1
  114. package/dist/host-check.d.ts +2 -3
  115. package/dist/host-check.js +13 -7
  116. package/dist/hosted-search.js +1 -1
  117. package/dist/import-worker.js +2 -2
  118. package/dist/import.d.ts +20 -8
  119. package/dist/import.js +448 -187
  120. package/dist/key-refusal.d.ts +14 -2
  121. package/dist/key-refusal.js +97 -33
  122. package/dist/learn/audit.d.ts +28 -27
  123. package/dist/learn/audit.js +87 -62
  124. package/dist/learn/check.js +1 -1
  125. package/dist/learn/commit.d.ts +35 -43
  126. package/dist/learn/commit.js +62 -270
  127. package/dist/learn/compile.d.ts +9 -6
  128. package/dist/learn/compile.js +51 -28
  129. package/dist/learn/corrections.js +1 -1
  130. package/dist/learn/delete.d.ts +5 -12
  131. package/dist/learn/delete.js +17 -30
  132. package/dist/learn/field-check.d.ts +111 -0
  133. package/dist/learn/field-check.js +174 -0
  134. package/dist/learn/forget-run.d.ts +16 -0
  135. package/dist/learn/forget-run.js +53 -0
  136. package/dist/learn/index.js +1 -1
  137. package/dist/learn/learning-of.d.ts +0 -4
  138. package/dist/learn/learning-of.js +0 -5
  139. package/dist/learn/ledger.d.ts +32 -29
  140. package/dist/learn/ledger.js +26 -19
  141. package/dist/learn/{folder.d.ts → legacy/folder.d.ts} +2 -1
  142. package/dist/learn/{folder.js → legacy/folder.js} +4 -7
  143. package/dist/learn/legacy/place.d.ts +16 -0
  144. package/dist/{workspace/learning-workspace.js → learn/legacy/place.js} +12 -42
  145. package/dist/learn/legacy/scrub.d.ts +28 -0
  146. package/dist/learn/legacy/scrub.js +258 -0
  147. package/dist/learn/promote.d.ts +119 -102
  148. package/dist/learn/promote.js +119 -262
  149. package/dist/learn/reset-ledger.d.ts +18 -0
  150. package/dist/learn/reset-ledger.js +14 -0
  151. package/dist/learn/rows.d.ts +186 -0
  152. package/dist/learn/rows.js +376 -0
  153. package/dist/learn/secrets.d.ts +4 -0
  154. package/dist/learn/secrets.js +12 -0
  155. package/dist/learn/workflow-draft.d.ts +4 -1
  156. package/dist/learn/workflow-draft.js +12 -2
  157. package/dist/learned-nodes.d.ts +8 -5
  158. package/dist/learned-nodes.js +8 -5
  159. package/dist/learned-workflow.d.ts +2 -1
  160. package/dist/learned-workflow.js +13 -10
  161. package/dist/learning-cost.d.ts +25 -8
  162. package/dist/learning-cost.js +23 -8
  163. package/dist/learning-reset.d.ts +1 -1
  164. package/dist/learning-reset.js +9 -11
  165. package/dist/learning-routes.d.ts +60 -81
  166. package/dist/learning-routes.js +187 -360
  167. package/dist/learning-setting.d.ts +6 -0
  168. package/dist/learning-setting.js +11 -1
  169. package/dist/learning-words.d.ts +2 -0
  170. package/dist/learning-words.js +2 -0
  171. package/dist/learning.d.ts +18 -24
  172. package/dist/learning.js +35 -66
  173. package/dist/listen-first.d.ts +5 -4
  174. package/dist/listen-first.js +4 -5
  175. package/dist/live-reach.d.ts +7 -0
  176. package/dist/live-reach.js +7 -0
  177. package/dist/mcp-api-only-origins.d.ts +15 -0
  178. package/dist/mcp-api-only-origins.js +40 -0
  179. package/dist/mcp-gateway.d.ts +22 -2
  180. package/dist/mcp-gateway.js +85 -11
  181. package/dist/mcp-oauth.d.ts +1 -1
  182. package/dist/mcp-oauth.js +3 -2
  183. package/dist/mcp-probe.d.ts +3 -0
  184. package/dist/mcp-probe.js +3 -0
  185. package/dist/mcp-resources.d.ts +1 -1
  186. package/dist/mcp-secret-writes.d.ts +24 -2
  187. package/dist/mcp-secret-writes.js +30 -2
  188. package/dist/mcp-servers-store.d.ts +52 -14
  189. package/dist/mcp-servers-store.js +165 -61
  190. package/dist/mcp-sources.d.ts +1 -2
  191. package/dist/mcp-sources.js +1 -2
  192. package/dist/mcp-store.d.ts +5 -5
  193. package/dist/mcp-store.js +3 -3
  194. package/dist/mcp.js +1 -1
  195. package/dist/model-gateway.d.ts +1 -1
  196. package/dist/model-gateway.js +20 -36
  197. package/dist/native/discovery.d.ts +6 -0
  198. package/dist/native/discovery.js +14 -1
  199. package/dist/native/remote.d.ts +5 -0
  200. package/dist/native/remote.js +16 -0
  201. package/dist/native/runtime.js +3 -2
  202. package/dist/observation/observer.d.ts +6 -6
  203. package/dist/ollama-provider.d.ts +23 -9
  204. package/dist/ollama-provider.js +49 -20
  205. package/dist/openapi.js +290 -79
  206. package/dist/otel/genai.d.ts +83 -7
  207. package/dist/otel/genai.js +69 -9
  208. package/dist/otel/tracer.d.ts +42 -13
  209. package/dist/otel/tracer.js +241 -56
  210. package/dist/page.d.ts +7 -1
  211. package/dist/page.js +76 -22
  212. package/dist/paid-calls.d.ts +6 -4
  213. package/dist/paid-calls.js +15 -7
  214. package/dist/place-offers.d.ts +58 -34
  215. package/dist/place-offers.js +96 -54
  216. package/dist/place.d.ts +41 -20
  217. package/dist/place.js +97 -47
  218. package/dist/print.js +1 -1
  219. package/dist/provider.d.ts +3 -2
  220. package/dist/provider.js +17 -8
  221. package/dist/purged-workflow.d.ts +0 -33
  222. package/dist/purged-workflow.js +3 -71
  223. package/dist/redact/match.d.ts +42 -9
  224. package/dist/redact/match.js +356 -54
  225. package/dist/run-census.d.ts +1 -1
  226. package/dist/run-census.js +4 -5
  227. package/dist/run-cut.js +4 -5
  228. package/dist/run-export-store.d.ts +15 -0
  229. package/dist/run-export-store.js +30 -0
  230. package/dist/run-export.d.ts +139 -0
  231. package/dist/run-export.js +379 -0
  232. package/dist/run-file-cut.d.ts +5 -0
  233. package/dist/run-file-cut.js +13 -0
  234. package/dist/run-launch.d.ts +3 -3
  235. package/dist/run-launch.js +16 -3
  236. package/dist/run-learning-served.d.ts +3 -3
  237. package/dist/run-learning-served.js +1 -1
  238. package/dist/run-listing.d.ts +1 -1
  239. package/dist/run-model-key.d.ts +15 -6
  240. package/dist/run-model-key.js +30 -31
  241. package/dist/run-reads-over-store.js +4 -4
  242. package/dist/run-secrets.js +3 -5
  243. package/dist/run-timeline-served.d.ts +1 -1
  244. package/dist/run-timeline-served.js +8 -5
  245. package/dist/runnable.js +26 -9
  246. package/dist/runner/adapter-loop.d.ts +35 -18
  247. package/dist/runner/adapter-loop.js +94 -47
  248. package/dist/runner/adapter-run-spec.d.ts +14 -1
  249. package/dist/runner/adapter-run-spec.js +73 -46
  250. package/dist/runner/adapters/pi.js +4 -2
  251. package/dist/runner/audit.d.ts +10 -9
  252. package/dist/runner/audit.js +64 -67
  253. package/dist/runner/beside.js +5 -6
  254. package/dist/runner/claim-secrets.d.ts +10 -3
  255. package/dist/runner/claim-secrets.js +29 -13
  256. package/dist/runner/cli-run-spec.d.ts +18 -0
  257. package/dist/runner/cli-run-spec.js +87 -58
  258. package/dist/runner/compare-end.d.ts +2 -3
  259. package/dist/runner/compare-end.js +30 -11
  260. package/dist/runner/conformance/harness.js +2 -3
  261. package/dist/runner/conformance/subject.d.ts +4 -1
  262. package/dist/runner/disk-free.d.ts +15 -4
  263. package/dist/runner/disk-free.js +25 -7
  264. package/dist/runner/feedback-round.d.ts +1 -1
  265. package/dist/runner/feedback-round.js +2 -2
  266. package/dist/runner/harness-loops.js +3 -4
  267. package/dist/runner/held.d.ts +5 -12
  268. package/dist/runner/held.js +0 -25
  269. package/dist/runner/journal-kinds.d.ts +8 -2
  270. package/dist/runner/journal-kinds.js +23 -5
  271. package/dist/runner/learned-first.d.ts +0 -2
  272. package/dist/runner/learned-first.js +23 -7
  273. package/dist/runner/learning-end.d.ts +14 -24
  274. package/dist/runner/learning-end.js +52 -94
  275. package/dist/runner/learning-seed.d.ts +13 -16
  276. package/dist/runner/learning-seed.js +13 -23
  277. package/dist/runner/live-ticker.js +7 -5
  278. package/dist/runner/loop-contract.d.ts +0 -2
  279. package/dist/runner/loop.d.ts +7 -0
  280. package/dist/runner/loop.js +1 -0
  281. package/dist/runner/main.js +13 -12
  282. package/dist/runner/mcp-claim.js +21 -5
  283. package/dist/runner/mcp-run.d.ts +4 -0
  284. package/dist/runner/mcp-run.js +2 -0
  285. package/dist/runner/meta-tools.js +3 -2
  286. package/dist/runner/metrics.d.ts +7 -0
  287. package/dist/runner/metrics.js +19 -0
  288. package/dist/runner/model-route.d.ts +10 -7
  289. package/dist/runner/model-route.js +79 -15
  290. package/dist/runner/native-loop.js +12 -11
  291. package/dist/runner/presence.d.ts +1 -4
  292. package/dist/runner/presence.js +6 -8
  293. package/dist/runner/promotion.d.ts +39 -36
  294. package/dist/runner/promotion.js +168 -112
  295. package/dist/runner/redact.d.ts +3 -1
  296. package/dist/runner/redact.js +5 -3
  297. package/dist/runner/reflect-hook.d.ts +2 -2
  298. package/dist/runner/reflect-hook.js +4 -1
  299. package/dist/runner/responses-fetch.d.ts +36 -0
  300. package/dist/runner/responses-fetch.js +511 -0
  301. package/dist/runner/run-child-host.d.ts +21 -14
  302. package/dist/runner/run-child-host.js +187 -141
  303. package/dist/runner/run-child.js +11 -4
  304. package/dist/runner/runner-check.js +5 -1
  305. package/dist/runner/runner.d.ts +3 -4
  306. package/dist/runner/runner.js +13 -9
  307. package/dist/runner/sdk-loop.js +10 -12
  308. package/dist/runner/spec-holds.d.ts +8 -1
  309. package/dist/runner/spec-holds.js +9 -4
  310. package/dist/runner/workflow-calls.d.ts +9 -0
  311. package/dist/runner/workflow-calls.js +150 -0
  312. package/dist/runner/workflow-first.d.ts +120 -32
  313. package/dist/runner/workflow-first.js +218 -94
  314. package/dist/runner/workflow-spec.js +1 -1
  315. package/dist/runs-over-store.js +8 -7
  316. package/dist/save-once.d.ts +14 -0
  317. package/dist/save-once.js +31 -0
  318. package/dist/scrub-command.d.ts +34 -31
  319. package/dist/scrub-command.js +116 -147
  320. package/dist/sdk/check.d.ts +1 -4
  321. package/dist/sdk/check.js +2 -3
  322. package/dist/sdk/runs.d.ts +26 -7
  323. package/dist/sdk/runs.js +194 -78
  324. package/dist/seal-key.js +4 -4
  325. package/dist/secret-cut.d.ts +3 -0
  326. package/dist/secret-cut.js +7 -1
  327. package/dist/secret-rules.d.ts +8 -1
  328. package/dist/secret-rules.js +482 -53
  329. package/dist/secrets.d.ts +55 -9
  330. package/dist/secrets.js +345 -21
  331. package/dist/server-fs.d.ts +1 -1
  332. package/dist/server-fs.js +1 -1
  333. package/dist/server-keys.d.ts +10 -3
  334. package/dist/server-keys.js +16 -3
  335. package/dist/server-secrets-store.js +2 -4
  336. package/dist/server.d.ts +30 -18
  337. package/dist/server.js +520 -238
  338. package/dist/share-context.d.ts +22 -0
  339. package/dist/share-context.js +76 -0
  340. package/dist/shell-lex.d.ts +105 -0
  341. package/dist/shell-lex.js +646 -0
  342. package/dist/sign-ins-store.d.ts +5 -7
  343. package/dist/sign-ins-store.js +12 -16
  344. package/dist/sign-ins.d.ts +7 -11
  345. package/dist/sign-ins.js +40 -41
  346. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  347. package/dist/source-sync/auxiliary.js +2 -2
  348. package/dist/start-switches.d.ts +6 -5
  349. package/dist/start-switches.js +8 -4
  350. package/dist/stats.d.ts +5 -1
  351. package/dist/stats.js +1 -1
  352. package/dist/store/agent-body.js +2 -2
  353. package/dist/store/dialect.d.ts +4 -0
  354. package/dist/store/dialect.js +1 -0
  355. package/dist/store/index.d.ts +2 -2
  356. package/dist/store/index.js +1 -1
  357. package/dist/store/mcp-record-keys.d.ts +10 -0
  358. package/dist/store/mcp-record-keys.js +13 -0
  359. package/dist/store/postgres/dialect.js +2 -0
  360. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  361. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  362. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  363. package/dist/store/postgres/migrations/0032_learning_rows.sql +65 -0
  364. package/dist/store/postgres/store.js +4 -0
  365. package/dist/store/schema.d.ts +60 -11
  366. package/dist/store/schema.js +147 -17
  367. package/dist/store/seal.d.ts +4 -1
  368. package/dist/store/sqlite/learning-rows.d.ts +23 -0
  369. package/dist/store/sqlite/learning-rows.js +559 -0
  370. package/dist/store/sqlite/run-launch.d.ts +3 -10
  371. package/dist/store/sqlite/run-launch.js +12 -23
  372. package/dist/store/sqlite/run-patch.d.ts +17 -10
  373. package/dist/store/sqlite/run-patch.js +50 -13
  374. package/dist/store/sqlite/store.d.ts +9 -0
  375. package/dist/store/sqlite/store.js +194 -46
  376. package/dist/store/store-schema.js +3 -4
  377. package/dist/store/store.d.ts +286 -38
  378. package/dist/store/store.js +27 -11
  379. package/dist/store-reads/analytics.d.ts +2 -1
  380. package/dist/store-reads/analytics.js +7 -5
  381. package/dist/store-reads/journal.d.ts +33 -3
  382. package/dist/store-reads/journal.js +99 -4
  383. package/dist/store-reads/learning.d.ts +50 -45
  384. package/dist/store-reads/learning.js +153 -116
  385. package/dist/store-reads/loop.js +1 -1
  386. package/dist/store-reads/stats.d.ts +2 -2
  387. package/dist/store-reads/stats.js +13 -7
  388. package/dist/store-view.d.ts +24 -2
  389. package/dist/store-view.js +49 -17
  390. package/dist/suggestions.d.ts +1 -1
  391. package/dist/suggestions.js +29 -13
  392. package/dist/template-eval.d.ts +72 -9
  393. package/dist/template-eval.js +358 -64
  394. package/dist/templates.d.ts +10 -2
  395. package/dist/templates.js +31 -4
  396. package/dist/timeline/labels.d.ts +1 -1
  397. package/dist/timeline/labels.js +4 -3
  398. package/dist/timeline/timeline.d.ts +23 -11
  399. package/dist/timeline/timeline.js +115 -31
  400. package/dist/timeline/web-calls.d.ts +8 -6
  401. package/dist/timeline/web-calls.js +10 -6
  402. package/dist/tool-gate.d.ts +13 -1
  403. package/dist/tool-gate.js +43 -3
  404. package/dist/tool-keys-store.js +2 -4
  405. package/dist/tool-keys.d.ts +11 -0
  406. package/dist/tool-keys.js +16 -0
  407. package/dist/tool-plane.d.ts +54 -13
  408. package/dist/tool-plane.js +103 -32
  409. package/dist/tools.d.ts +5 -1
  410. package/dist/tools.js +7 -7
  411. package/dist/trigger-email.js +12 -6
  412. package/dist/triggers.d.ts +15 -34
  413. package/dist/triggers.js +119 -126
  414. package/dist/validate.d.ts +8 -1
  415. package/dist/validate.js +163 -23
  416. package/dist/web-fake.d.ts +2 -1
  417. package/dist/web-fake.js +8 -6
  418. package/dist/web-fetch.d.ts +8 -6
  419. package/dist/web-fetch.js +13 -11
  420. package/dist/web-holds.d.ts +34 -0
  421. package/dist/web-holds.js +89 -0
  422. package/dist/web-run.d.ts +32 -5
  423. package/dist/web-run.js +76 -28
  424. package/dist/web-save.js +23 -12
  425. package/dist/web-search.js +14 -25
  426. package/dist/wires.d.ts +4 -3
  427. package/dist/wires.js +5 -4
  428. package/dist/workspace/archil-claim.d.ts +12 -5
  429. package/dist/workspace/archil-claim.js +45 -5
  430. package/dist/workspace/archil-exec.js +1 -1
  431. package/dist/workspace/archil.d.ts +1 -1
  432. package/dist/workspace/archil.js +1 -1
  433. package/dist/workspace/attach.js +52 -19
  434. package/dist/workspace/attached-computers.d.ts +6 -2
  435. package/dist/workspace/attached-computers.js +5 -4
  436. package/dist/workspace/computer-deps.d.ts +23 -6
  437. package/dist/workspace/computer-deps.js +38 -18
  438. package/dist/workspace/computer-for-claim.d.ts +21 -4
  439. package/dist/workspace/computer-for-claim.js +160 -54
  440. package/dist/workspace/computer-intervals.d.ts +2 -0
  441. package/dist/workspace/computer-intervals.js +1 -1
  442. package/dist/workspace/computer-janitor.d.ts +48 -14
  443. package/dist/workspace/computer-janitor.js +153 -44
  444. package/dist/workspace/computer-kept.d.ts +158 -32
  445. package/dist/workspace/computer-kept.js +288 -63
  446. package/dist/workspace/computer-providers.d.ts +19 -4
  447. package/dist/workspace/computer-providers.js +40 -6
  448. package/dist/workspace/index.d.ts +2 -3
  449. package/dist/workspace/index.js +2 -3
  450. package/dist/workspace/local.js +41 -1
  451. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  452. package/dist/workspace/mount-revoke-left.js +72 -0
  453. package/dist/workspace/paired-route.js +4 -5
  454. package/dist/workspace/paths.d.ts +0 -4
  455. package/dist/workspace/paths.js +0 -6
  456. package/dist/workspace/resolve-computer.d.ts +5 -2
  457. package/dist/workspace/resolve-computer.js +9 -3
  458. package/dist/workspace/run-end-computers.d.ts +11 -5
  459. package/dist/workspace/run-end-computers.js +153 -28
  460. package/dist/workspace/run-tools.d.ts +22 -3
  461. package/dist/workspace/run-tools.js +17 -5
  462. package/dist/workspace/run-workspace.d.ts +14 -1
  463. package/dist/workspace/run-workspace.js +34 -1
  464. package/dist/workspace/workspace.d.ts +7 -1
  465. package/dist/workspace/workspace.js +1 -1
  466. package/package.json +13 -14
  467. package/skills/agentrun-serve/SKILL.md +5 -2
  468. package/templates/README.md +22 -6
  469. package/templates/TOOLS.md +46 -0
  470. package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
  471. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  472. package/dist/console/assets/index-DPh29cyz.js +0 -747
  473. package/dist/workspace/learning-workspace.d.ts +0 -24
  474. /package/dist/learn/{learning.sh → legacy/learning.sh} +0 -0
@@ -1,166 +0,0 @@
1
- import{w as bt,d as qt,D as Yn}from"./index-DPh29cyz.js";const ye=t=>({type:"boolean",description:t}),Yt={type:"object",required:["name","pageCount","pages","text"],properties:{name:{type:"string"},pageCount:{type:"integer"},pages:{type:"array"},text:{type:"string"}}},zn={type:"object",required:["status","text"],properties:{status:{type:"integer"},url:{type:"string"},title:{type:"string"},text:{type:"string"}}},vt={type:"object"},Ke={type:"object",additionalProperties:!1,required:["altered","seal","signature","legible"],properties:{altered:ye("Does the page show signs of digital alteration: mismatched fonts, misaligned lines, pasted regions or an edited date?"),seal:ye("Is a state seal or a filing stamp visible on the page?"),signature:ye("Is the certificate signed by a state official?"),legible:ye("Is the entity's full legal name legible on the page?")}},mt={v:2,name:"coi-batch-review",schemas:{Input:{type:"object",required:["documents"],properties:{documents:{type:"array",items:{type:"string"},minItems:1,maxItems:50}}},DocChecks:Ke,Pages:Yt,Report:vt},input:{schemaId:"Input"},output:{schemaId:"Report",path:"report"},root:{node:"chain",steps:[{node:"map",label:"each-document",itemsPath:"documents",as:"rows",maxConcurrency:4,onItemFailure:"collect",failedAs:"failed",body:{node:"chain",steps:[{node:"call",label:"render-pages",via:"tool",tool:"pdf_pages",args:{path:"{item}",maxPages:2},out:"Pages",as:"pages",deadline_s:60},{node:"judge",label:"inspect-certificate",provider:"jev",state:{document:"{item}",page:"<page1>",text:"{pages.text}"},images:{"<page1>":"{pages.pages.0.image}"},out:"DocChecks",as:"checks"},{node:"code",label:"grade",code:"(s) => ({ document: s.item, verdict: s.checks.altered || !s.checks.seal || !s.checks.legible ? 'doubtful' : 'valid', checks: s.checks })",as:"row"}]}},{node:"code",label:"batch-report",code:"(s) => ({ valid: s.rows.filter((r) => r && r.verdict === 'valid').length, doubtful: s.rows.filter((r) => r && r.verdict === 'doubtful').map((r) => r.document), failed: s.failed })",as:"report"}]}},Ae={v:2,name:"kyb-onboarding",schemas:{Pages:Yt,Result:vt,Input:{type:"object",required:["company","state","registration_number","documents"],properties:{company:{type:"string"},state:{type:"string"},registration_number:{type:"string"},documents:{type:"array",items:{type:"string"}}}},Registry:{type:"object",additionalProperties:!1,required:["registered","active","name_matches"],properties:{registered:ye("Is a company with this exact registration number on file with the named state's business registry?"),active:ye("Is that registration currently active (in good standing, not dissolved, forfeited or revoked)?"),name_matches:ye("Does the registry's legal name match the applicant's name, ignoring punctuation and suffix style?")}},CertLook:{type:"object",additionalProperties:!1,required:["altered","seal","legible"],properties:{altered:Ke.properties.altered,seal:Ke.properties.seal,legible:Ke.properties.legible}},CrossCheck:{type:"object",additionalProperties:!1,required:["same_entity","same_state","dates_consistent"],properties:{same_entity:ye("Do the registry record and the certificate name the same legal entity?"),same_state:ye("Do they name the same state of incorporation?"),dates_consistent:ye("Is the certificate's filing date consistent with the registry's formation date (within 3 days)?")}}},input:{schemaId:"Input"},root:{node:"chain",steps:[{node:"call",label:"render-certificate",via:"tool",tool:"pdf_pages",args:{path:"{documents.0}",maxPages:1},out:"Pages",as:"cert",deadline_s:60},{node:"parallel",label:"checks",branches:[{node:"judge",label:"registry-lookup",provider:"parallel",model:"standard",state:{company:"{company}",state:"{state}",registration_number:"{registration_number}"},out:"Registry",as:"registry"},{node:"judge",label:"certificate-look",provider:"jev",state:{page:"<cert>",text:"{cert.text}"},images:{"<cert>":"{cert.pages.0.image}"},out:"CertLook",as:"look"}]},{node:"judge",label:"cross-check",provider:"jev",state:{applicant:{company:"{company}",state:"{state}"},registry:"{registry$answers}",certificate_text:"{cert.text}"},out:"CrossCheck",as:"cross"},{node:"route",label:"decide",provider:"jev",state:{registry:"{registry}",look:"{look}",cross:"{cross}"},instructions:"Decide the onboarding outcome for this business from the registry check, the certificate's look and the cross-check.",branches:{approve:{criteria:"Registered, active, the certificate looks genuine, and every cross-check agrees.",body:{node:"code",label:"record-approval",code:"(s) => ({ outcome: 'approved' })",as:"outcome"}},review:{criteria:"Mostly consistent, but one check is doubtful or the evidence disagrees on a detail.",body:{node:"code",label:"open-review-case",code:"(s) => ({ outcome: 'review', reasons: s.cross })",as:"outcome"}},reject:{criteria:"Not registered, dissolved, or the certificate is altered.",body:{node:"code",label:"record-rejection",code:"(s) => ({ outcome: 'rejected' })",as:"outcome"}}},unsure:{branch:"review",gte:.75}}]},output:{schemaId:"Result",path:"outcome"}},Jn={type:"object",additionalProperties:!1,required:["prohibited"],properties:{prohibited:ye("Does this merchant sell goods the card networks prohibit: weapons, controlled substances, counterfeit goods, or unlicensed nicotine products?")}},Ve=(t,n,o)=>({node:"judge",label:t,provider:n,...o?{model:o}:{},state:{merchant:"{merchant}",url:"{url}",page_text:"{page.text}"},out:"Prohibited",as:t.replace(/-/g,"_")}),Ze={v:2,name:"prohibited-goods-jury",schemas:{Page:zn,Result:vt,Input:{type:"object",required:["merchant","url"],properties:{merchant:{type:"string"},url:{type:"string"}}},Prohibited:Jn},input:{schemaId:"Input"},root:{node:"chain",steps:[{node:"call",label:"fetch-storefront",via:"tool",tool:"web_fetch",args:{url:"{url}"},out:"Page",as:"page",deadline_s:30},{node:"parallel",label:"jury",branches:[Ve("jev","jev"),Ve("pplx-decider","openrouter","perplexity/pplx-decider-v1.2"),Ve("liquid-d1","openrouter","liquid/d1"),Ve("clef","openrouter","cloudflare/clef")]},{node:"code",label:"aggregate",code:"(s) => { const p = [s.jev$answers, s.pplx_decider$answers, s.liquid_d1$answers, s.clef$answers].map((a) => a.answers.prohibited.noul); const mean = p.reduce((x, y) => x + y, 0) / p.length; const spread = Math.max(...p) - Math.min(...p); return { mean, spread, outcome: spread > 0.3 ? 'disagree' : 'agree' }; }",as:"agreement"},{node:"route",label:"agreement",valuePath:"agreement.outcome",branches:{agree:{body:{node:"code",label:"auto-decide",code:"(s) => ({ decision: s.agreement.mean >= 0.5 ? 'decline' : 'approve' })",as:"decision"}},disagree:{body:{node:"code",label:"human-review",code:"(s) => ({ decision: 'review', spread: s.agreement.spread })",as:"decision"}}}}]},output:{schemaId:"Result",path:"decision"}},re=6e4,ie=60*re,U=24*ie,ae={default:"anthropic/claude-sonnet-5-5",fast:"openai/gpt-6-luna",strong:"anthropic/claude-opus-5-5",codex:"openai/gpt-6.1-sol"},Vn={v:2,name:"ticket-triage",schemas:{Ticket:{type:"object",required:["subject","body"],properties:{subject:{type:"string"},body:{type:"string"}}},Triage:{type:"object",required:["queue","urgency"],properties:{queue:{type:"string"},urgency:{type:"integer"}}}},input:{schemaId:"Ticket"},output:{schemaId:"Triage",path:"triage"},root:{node:"chain",steps:[{node:"call",label:"read the playbook",tool:"read",args:{path:"playbooks/triage.md"},as:"playbook"},{node:"pick",label:"which queue",from:"playbook.queues",instructions:"Which queue does this ticket belong to, by what the buyer or seller asks for?",as:"queue",none:"hand back"},{node:"code",label:"score the urgency",as:"triage"}]}},Qn=`# ticket-triage
2
-
3
- Files a ticket under its queue (billing, shipping, account, merchant, abuse) and scores its urgency from the playbook: a chargeback, a locked account or a safety problem is 4 or more.
4
-
5
- Drafted from Support triage's runs. It is being checked against past tickets before it answers one alone; the first reply stays with the agent.
6
- `,Zn=[{id:"refund-desk",name:"Refund desk",kind:"agentic",harness:"pi",model:ae.default,learning:!0,maxCostUsd:.5,madeDaysAgo:41,description:"Decides a buyer's refund request against the refund policy and the order's record, then writes to the buyer.",instructions:`You decide refund requests for Larkspur's marketplace.
7
-
8
- 1. Read policies/refunds.md before every decision.
9
- 2. Look the order up: when it was delivered, what was paid, what the carrier recorded.
10
- 3. Decide: full refund, partial refund, return first, or decline. Quote the policy line you applied.
11
- 4. Write the decision to decisions/<request id>.md.
12
- 5. Email the buyer the decision in plain words. Never promise a date the policy does not give.`,tools:["read","write","web_fetch","email_send","ask_person"],notes:[null,"Quote the policy line in every decision","Cap each run at $0.50"]},{id:"support-triage",name:"Support triage",kind:"agentic",harness:"pi",model:ae.fast,madeDaysAgo:58,description:"Reads each new support ticket, files it under a queue with an urgency, and drafts the first reply.",instructions:`Triage one support ticket.
13
-
14
- Pick the queue (billing, shipping, account, merchant, abuse), score urgency 1 to 5, and draft a first reply of at most four sentences. A ticket that mentions a chargeback, a locked account or a safety problem is urgency 4 or more.`,tools:["read","write","email_draft"],notes:[null,"Chargebacks are urgency 4 or more"],learning:!0,learned:{corrections:`# Corrections
15
-
16
- - A ticket that names a chargeback is urgency 4 or more, whatever its tone.
17
- - "Where is my parcel" under four days since dispatch is urgency 1.
18
- - Never quote a payout date in the first reply.
19
- `,checking:{name:"ticket-triage",description:"Files a ticket under its queue and scores its urgency from the playbook.",readme:Qn,workflow:Vn}}},{id:"kyb-check",name:"KYB check",kind:"workflow",harness:"pi",model:ae.default,workflow:Ae,madeDaysAgo:33,description:"Checks a new merchant's certificate of incorporation against the state registry, and routes the unsure ones to a person.",tools:[],notes:[null,"Route unsure registry matches to review"]},{id:"certificate-review",name:"Certificate batch review",kind:"workflow",harness:"pi",model:ae.default,workflow:mt,madeDaysAgo:27,description:"Reads a batch of certificates of incorporation, four at a time: seal, signature, legibility and signs of alteration.",tools:[],notes:[null]},{id:"prohibited-goods-jury",name:"Prohibited goods jury",kind:"workflow",harness:"pi",model:ae.default,workflow:Ze,madeDaysAgo:19,description:"Asks four decision models whether a merchant's storefront sells prohibited goods, and escalates when they disagree.",tools:[],notes:[null,"Four jurors in place of two"]},{id:"weekly-risk-brief",name:"Weekly risk brief",kind:"agentic",harness:"pi",model:ae.strong,madeDaysAgo:36,description:"Once a week: what changed in card-network and marketplace rules, and what Larkspur should do about it.",instructions:`Write the weekly risk brief for Larkspur's risk team.
20
-
21
- Search for rule changes from the card networks and consumer regulators in the last seven days. Read the primary source, never a summary of it. Write brief.md: at most five items, each with what changed, who it touches, the date it takes effect, and the source. Save the sources you read to sources.csv. Ask when two primary sources disagree.`,tools:["web_search","web_fetch","read","write","ask_person"],notes:[null,"At most five items","Ask when primary sources disagree"]},{id:"pr-reviewer",name:"PR reviewer",kind:"agentic",harness:"codex",model:ae.codex,maxCostUsd:1.5,madeDaysAgo:22,description:"Reviews each pull request on the payments service for correctness, and posts one review.",instructions:`Review the pull request named in the input on its read-only checkout.
22
-
23
- Read the diff, then the code around each change. Try to break each changed function. Report only what you can quote a line for, ranked P0 to P2. Post one review comment.`,tools:["read","bash","web_fetch"],notes:[null,"Rank findings P0 to P2"],learning:!0,learned:{corrections:`# Corrections
24
-
25
- - A migration that backfills must carry the tenant column: check it first.
26
- - Do not report style the linter already enforces.
27
- `}},{id:"architect",name:"Architect",kind:"agentic",harness:"claude-code",model:ae.strong,madeDaysAgo:16,description:"Reads a design proposal against the payments service's code and says what it would break, before anyone builds it.",instructions:"You are the payments service's architect. For a proposal, name the modules it touches, the invariants it puts at risk (idempotency, ledger balance, tenant isolation), and the smallest change that gets the same result.",tools:[],notes:[null],native:{runtime:"claude-code",project:"larkspur/payments-service",selector:{kind:"agent",name:"architect"},version:"2.1.330",skills:["adr-writer","ledger-invariants"],mcp:["github"]}},{id:"code-reviewer",name:"Code reviewer",kind:"agentic",harness:"codex",model:ae.codex,madeDaysAgo:11,description:"Reviews the working tree before a commit: correctness first, with the line behind each finding.",instructions:"Review the staged changes. Report only what you can quote a line for.",tools:[],notes:[null],native:{runtime:"codex",project:"larkspur/payments-service",selector:{kind:"project"},version:"0.164.0",skills:["review"],mcp:[]}}];function Xn(t){let n=t>>>0;return()=>{n=n+1831565813>>>0;let o=Math.imul(n^n>>>15,1|n);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}const Se=(t,n)=>n[Math.floor(t()*n.length)],X=(t,n,o)=>n+t()*(o-n),Ee=t=>t.toFixed(2),er=`# Refund policy (buyers)
28
-
29
- - Refund window: 30 days from delivery.
30
- - Damaged on arrival, with a photo: full refund. No return needed for orders under $250.
31
- - Damaged on arrival, $250 or more: send a prepaid return label first; refund when the carrier scans it.
32
- - Changed mind: return first, refund less the original shipping.
33
- - Not delivered: full refund once the carrier's record shows no delivery scan for 7 days.
34
- - Outside the window: decline, and offer the merchant's own warranty contact.
35
- `,Xe=[{buyer:"Mara Ellison",email:"mara.ellison@mail.example",order:"LK-77120",item:"countertop blender",amount:184,said:"The jar arrived cracked. Photo attached.",deliveredDaysAgo:6,decision:"Full refund, no return",line:"Damaged on arrival, with a photo: full refund. No return needed for orders under $250.",refund:184},{buyer:"Teodor Vance",email:"t.vance@mail.example",order:"LK-76988",item:"standing desk frame",amount:412.5,said:"One leg is bent and will not extend.",deliveredDaysAgo:3,decision:"Return label first, then full refund",line:"Damaged on arrival, $250 or more: send a prepaid return label first; refund when the carrier scans it.",refund:412.5},{buyer:"Priya Raman",email:"priya.raman@mail.example",order:"LK-77342",item:"wool throw",amount:68,said:"The colour is not what I expected. I would like to send it back.",deliveredDaysAgo:11,decision:"Return first, refund less shipping",line:"Changed mind: return first, refund less the original shipping.",refund:61.05},{buyer:"Jonas Okoro",email:"jonas.okoro@mail.example",order:"LK-75510",item:"espresso grinder",amount:229,said:"It stopped working after two months.",deliveredDaysAgo:64,decision:"Declined, outside the window",line:"Outside the window: decline, and offer the merchant's own warranty contact.",refund:null},{buyer:"Annika Lindholm",email:"annika.l@mail.example",order:"LK-77411",item:"ceramic planter set",amount:54,said:"The parcel never came. Tracking has not moved in ten days.",deliveredDaysAgo:-1,decision:"Full refund, not delivered",line:"Not delivered: full refund once the carrier's record shows no delivery scan for 7 days.",refund:54},{buyer:"Rafael Montes",email:"r.montes@mail.example",order:"LK-77203",item:"trail running shoes",amount:139,said:"Wrong size sent. I ordered a 10 and got an 8.",deliveredDaysAgo:4,decision:"Full refund, no return",line:"Damaged on arrival, with a photo: full refund. No return needed for orders under $250.",refund:139},{buyer:"Hye-jin Park",email:"hyejin.park@mail.example",order:"LK-77067",item:"cast iron skillet",amount:47.5,said:"The handle has a hairline crack. Photo attached.",deliveredDaysAgo:2,decision:"Full refund, no return",line:"Damaged on arrival, with a photo: full refund. No return needed for orders under $250.",refund:47.5},{buyer:"Calum Reyes",email:"calum.reyes@mail.example",order:"LK-76820",item:"bookshelf speaker pair",amount:318,said:"One speaker buzzes at any volume.",deliveredDaysAgo:9,decision:"Return label first, then full refund",line:"Damaged on arrival, $250 or more: send a prepaid return label first; refund when the carrier scans it.",refund:318}],tr=t=>JSON.stringify({order:t.order,item:t.item,paid_usd:t.amount,carrier:"Northline Parcel",delivered:t.deliveredDaysAgo<0?null:`${t.deliveredDaysAgo} days ago`,last_scan:t.deliveredDaysAgo<0?"Departed sort facility, 10 days ago":"Delivered, signed at door",photo_attached:/photo/i.test(t.said)}),zt=t=>({to:t.email,subject:`Your refund request for order ${t.order}`,body:t.refund===null?`Hi ${t.buyer.split(" ")[0]}, thank you for writing. Order ${t.order} was delivered ${t.deliveredDaysAgo} days ago, which is outside our 30-day refund window, so we can't refund it. The merchant's warranty may still cover it; their contact is on your order page.`:`Hi ${t.buyer.split(" ")[0]}, we're sorry about the ${t.item}. ${t.decision.startsWith("Return")?"We've sent a prepaid return label to this address; your refund":"Your refund"} of $${Ee(t.refund)} goes back to your original payment method${t.decision.startsWith("Return")?" once the carrier scans the parcel":""}.`}),It=(t,n)=>`# ${n}: ${t.decision}
36
-
37
- - Buyer: ${t.buyer}
38
- - Order: ${t.order} (${t.item}), $${Ee(t.amount)}
39
- - Buyer said: "${t.said}"
40
- - Order record: ${t.deliveredDaysAgo<0?"no delivery scan for 10 days":`delivered ${t.deliveredDaysAgo} days ago`}
41
- - Policy line applied: "${t.line}"
42
- - Refund: ${t.refund===null?"none":`$${Ee(t.refund)}`}
43
- `;function Jt(t,n){return[{k:"user",text:`Refund request ${n}: ${t.buyer} asks for $${Ee(t.amount)} back on order ${t.order} (${t.item}). "${t.said}"`},{k:"think",text:"I need the refund policy and this order's delivery record before I decide anything."},{k:"tool",tool:"read",label:"Read policies/refunds.md",input:"policies/refunds.md",result:er,ms:300},{k:"tool",tool:"web_fetch",label:`Fetched orders.larkspur.example/orders/${t.order}`,input:`https://orders.larkspur.example/orders/${t.order}`,result:tr(t),ms:1400},{k:"think",text:`${t.deliveredDaysAgo<0?"There is no delivery scan, and the last movement was ten days ago":`It was delivered ${t.deliveredDaysAgo} days ago`}. The line that applies: "${t.line}"`},{k:"say",text:`Decision: ${t.decision}. Writing it down, then telling the buyer.`},{k:"tool",tool:"write",label:`Wrote decisions/${n}.md`,input:`decisions/${n}.md`,result:`Successfully wrote decisions/${n}.md`,ms:250,saved:`decisions/${n}.md`},{k:"approval",tool:"email_send",label:`Send email to ${t.email}`,args:zt(t),because:"email_send is set to ask: this agent emails buyers only with your OK",result:`Sent to ${t.email}.`,denied:"The owner declined this call. The email was not sent.",price:"not metered"},{k:"final",text:`${t.decision} for ${t.buyer} on order ${t.order}${t.refund===null?"":`: $${Ee(t.refund)}`}. The buyer has the decision by email, and the note is in decisions/${n}.md.`,declined:`${t.decision} for ${t.buyer} on order ${t.order}. You declined the email, so the buyer has not been told. The note is in decisions/${n}.md.`}]}function Vt(t,n){return[{k:"user",text:`Refund request ${n}: ${t.buyer} asks for $${Ee(t.amount)} back on order ${t.order} (${t.item}). "${t.said}"`},{k:"tool",tool:"learned_workflow",label:"Ran the learned workflow refund-decision",input:"refund-decision",ms:2600,saved:`decisions/${n}.md`,result:JSON.stringify({decision:t.decision,policy_line:t.line,refund_usd:t.refund,note:`decisions/${n}.md`}),nodes:[{label:"read the policy",kind:"call",status:"ok",duration_ms:12},{label:"look the order up",kind:"call",status:"ok",duration_ms:940},{label:"which policy line applies",kind:"pick",status:"ok",duration_ms:610,model:"jev",tier:"fast"},{label:"work out the refund",kind:"code",status:"ok",duration_ms:3},{label:"write the decision note",kind:"call",status:"ok",duration_ms:18},{label:"draft the email",kind:"extract",status:"ok",duration_ms:980,model:ae.fast.split("/")[1],tier:"fast"}]},{k:"approval",tool:"email_send",label:`Send email to ${t.email}`,args:zt(t),because:"email_send is set to ask: this agent emails buyers only with your OK",result:`Sent to ${t.email}.`,denied:"The owner declined this call. The email was not sent.",price:"not metered"},{k:"final",text:`${t.decision} for ${t.buyer} on order ${t.order}${t.refund===null?"":`: $${Ee(t.refund)}`}. The buyer has the decision by email, and the note is in decisions/${n}.md.`,declined:`${t.decision} for ${t.buyer} on order ${t.order}. You declined the email, so the buyer has not been told. The note is in decisions/${n}.md.`}]}const Qe={v:2,name:"refund-decision",schemas:{Request:{type:"object",required:["order","said"],properties:{order:{type:"string"},said:{type:"string"}}},Decision:{type:"object",required:["decision","policy_line","refund_usd"],properties:{decision:{type:"string"},policy_line:{type:"string"},refund_usd:{type:["number","null"]}}}},input:{schemaId:"Request"},output:{schemaId:"Decision",path:"decision"},root:{node:"chain",steps:[{node:"call",label:"read the policy",tool:"read",args:{path:"policies/refunds.md"},as:"policy"},{node:"call",label:"look the order up",tool:"web_fetch",args:{url:"https://orders.larkspur.example/orders/${input.order}"},as:"order"},{node:"pick",label:"which policy line applies",from:"policy.lines",instructions:"Which line of the refund policy covers what the buyer said, given the order's record?",as:"line",none:"hand back"},{node:"code",label:"work out the refund",as:"decision"},{node:"call",label:"write the decision note",tool:"write",as:"note"},{node:"extract",label:"draft the email",instructions:"Tell the buyer the decision in plain words. Promise no date the policy does not give.",out:"Decision",as:"email",tier:"fast"}]}},et=[{subject:"Charged twice for one order",body:"My card shows two charges of $62.40 for order LK-77290. Please fix this.",queue:"billing",urgency:3,reply:"Thanks for flagging this. One of the two charges is a pending authorisation that drops off within three business days; if it settles, we refund it the same day."},{subject:"Chargeback notice on my shop",body:"I got a chargeback notice for $480 and my payout is on hold. I shipped this order with tracking.",queue:"merchant",urgency:4,reply:"We've opened the dispute for you. Upload the tracking record and the delivery confirmation from your orders page, and your payout is released as soon as the network accepts them."},{subject:"Can't log in after phone change",body:"I changed my number and the code goes to the old one. Locked out since yesterday.",queue:"account",urgency:4,reply:"We can move your sign-in to the new number after a quick identity check. Reply with the last four digits of the card on your account and the postcode of your delivery address."},{subject:"Where is my parcel?",body:"Order LK-77018 says out for delivery for four days now.",queue:"shipping",urgency:2,reply:"The carrier's last scan was at the local depot four days ago. We've asked them to trace it; if it has not moved in three more days we refund you in full."},{subject:"Listing looks like a counterfeit",body:"This shop sells 'designer' bags at $30. Pretty sure they are fake.",queue:"abuse",urgency:4,reply:"Thank you for reporting this. Our trust team is reviewing the shop today, and the listing is hidden while they do."},{subject:"Invoice for my accountant",body:"Can I get a VAT invoice for order LK-76455?",queue:"billing",urgency:1,reply:"Of course. Your VAT invoice is on the order's page under Documents, and we've emailed you a copy as well."},{subject:"Payout schedule question",body:"When do weekly payouts land? New seller here.",queue:"merchant",urgency:1,reply:"Welcome! Weekly payouts leave every Tuesday for sales cleared up to the Sunday before, and land in one to two business days."},{subject:"Item smells of smoke",body:"The jacket I bought reeks of cigarette smoke. Listed as new.",queue:"shipping",urgency:2,reply:"That's not what 'new' means, and we're sorry. You can open a refund request from the order's page; with a short note like this one it is approved without a return."}];function Qt(t,n){return[{k:"user",text:`Ticket #${n}: ${t.subject}
44
-
45
- ${t.body}`},{k:"tool",tool:"read",label:"Read playbooks/queues.md",input:"playbooks/queues.md",result:`billing: charges, invoices, refunds already decided
46
- shipping: where is it, wrong or damaged item
47
- account: sign-in, profile, deletion
48
- merchant: payouts, chargebacks, listings
49
- abuse: counterfeit, fraud, safety
50
-
51
- Urgency 4 or more: a chargeback, a locked account, a safety problem.`,ms:200},{k:"say",text:`Queue: ${t.queue}. Urgency: ${t.urgency} of 5.`},{k:"tool",tool:"email_draft",label:"Saved a draft reply",input:t.subject,result:`Draft saved: "Re: ${t.subject}"`,ms:500},{k:"final",text:`Filed under ${t.queue}, urgency ${t.urgency}. Draft reply: "${t.reply}"`}]}const yt=`# Weekly risk brief
52
-
53
- Five changes that touch Larkspur this week.
54
-
55
- ## 1. Dispute response window shortens to 9 days
56
- - **What changed:** the card network's acquirer bulletin cuts the time to answer a first chargeback from 20 days to 9.
57
- - **Who it touches:** every merchant with an open dispute; our dispute desk's queue.
58
- - **Takes effect:** the first of next quarter.
59
- - **What to do:** move the reminder email from day 10 to day 3, and auto-attach tracking records.
60
- - **Source:** cardnetwork.example/bulletins/2026-41
61
-
62
- ## 2. Marketplace seller identity checks: annual re-verification
63
- - **What changed:** the consumer regulator's final rule asks marketplaces to re-verify high-volume sellers once a year.
64
- - **Who it touches:** about 1,900 of our merchants (over 200 sales a year).
65
- - **Takes effect:** in six months.
66
- - **What to do:** schedule the KYB check agent to re-run each merchant on the anniversary of onboarding.
67
- - **Source:** regulator.example/rules/marketplace-sellers-final
68
-
69
- ## 3. Bear spray added to the restricted-shipping list in two more states
70
- - **What changed:** two states now bar mail-order sale of deterrent sprays over 4 oz.
71
- - **Who it touches:** 14 outdoor-gear merchants.
72
- - **Takes effect:** already in force.
73
- - **What to do:** add both states to the prohibited goods jury's rules; re-run the 14 storefronts.
74
- - **Source:** statecode.example/title-12/ch-7
75
-
76
- ## 4. Refund timing disclosure
77
- - **What changed:** guidance says a refund email must not name a date unless the policy guarantees it.
78
- - **Who it touches:** the Refund desk agent's emails.
79
- - **Takes effect:** guidance, in force now.
80
- - **What to do:** nothing new. The agent's instructions already say "never promise a date the policy does not give".
81
- - **Source:** regulator.example/guidance/refund-communications
82
-
83
- ## 5. Fraud score threshold for manual review
84
- - **What changed:** the network recommends manual review above a fraud score of 72, down from 80.
85
- - **Who it touches:** payout holds; about 3% more orders a week would be held.
86
- - **Takes effect:** recommendation only.
87
- - **What to do:** decide at Thursday's risk review; no change this week.
88
- - **Source:** cardnetwork.example/bulletins/2026-39
89
- `,wt=`url,title,read_at,used_in
90
- cardnetwork.example/bulletins/2026-41,Dispute timeframes update,08:02,1
91
- regulator.example/rules/marketplace-sellers-final,Marketplace seller verification: final rule,08:03,2
92
- statecode.example/title-12/ch-7,Deterrent sprays: mail-order sales,08:05,3
93
- regulator.example/guidance/refund-communications,Refund communications guidance,08:06,4
94
- cardnetwork.example/bulletins/2026-39,Fraud score guidance,08:07,5
95
- `,nr=[{k:"user",text:"Write this week's risk brief."},{k:"think",text:"I'll look for rule changes from the card networks and the consumer regulator in the last seven days, and read each primary source myself."},{k:"tool",tool:"web_search",label:'Searched the web for "card network acquirer bulletin dispute timeframe change"',input:"card network acquirer bulletin dispute timeframe change",result:JSON.stringify({results:[{url:"https://cardnetwork.example/bulletins/2026-41",title:"Dispute timeframes update"},{url:"https://paymentsweekly.example/news/dispute-window",title:"Networks shorten dispute windows"}]}),ms:1500},{k:"tool",tool:"web_fetch",label:"Fetched cardnetwork.example/bulletins/2026-41",input:"https://cardnetwork.example/bulletins/2026-41",result:"Bulletin 2026-41. Effective the first day of next quarter, acquirers must respond to a first chargeback within 9 calendar days (previously 20)…",ms:1900},{k:"tool",tool:"web_search",label:'Searched the web for "marketplace seller verification final rule"',input:"marketplace seller verification final rule",result:JSON.stringify({results:[{url:"https://regulator.example/rules/marketplace-sellers-final",title:"Marketplace seller verification: final rule"}]}),ms:1300},{k:"tool",tool:"web_fetch",label:"Fetched regulator.example/rules/marketplace-sellers-final",input:"https://regulator.example/rules/marketplace-sellers-final",result:"Final rule. Online marketplaces must re-verify the identity of each high-volume third-party seller at least annually…",ms:2100},{k:"tool",tool:"web_fetch",label:"Fetched paymentsweekly.example/news/dispute-window",input:"https://paymentsweekly.example/news/dispute-window",result:"…sources say the new 9-day window applies from the first of the month after next, a month later than the bulletin's date…",ms:1700}],rr="The network's bulletin says the 9-day dispute window starts on the first of next quarter; a trade article says a month later. Which date should the brief give?",sr=[{k:"think",text:"The bulletin is the primary source, so its date goes in, with the source beside it."},{k:"tool",tool:"web_fetch",label:"Fetched statecode.example/title-12/ch-7",input:"https://statecode.example/title-12/ch-7",result:"Chapter 7. Deterrent sprays exceeding 4 ounces may not be sold by mail order to an address in this state…",ms:1600},{k:"tool",tool:"write",label:"Wrote brief.md",input:"brief.md",result:"Successfully wrote brief.md",ms:300,saved:"brief.md"},{k:"tool",tool:"write",label:"Wrote sources.csv",input:"sources.csv",result:"Successfully wrote sources.csv",ms:200,saved:"sources.csv"},{k:"final",text:"This week's brief is in brief.md: five items, led by the dispute response window shortening to 9 days from next quarter. The sources I read are in sources.csv."}],kt=()=>[...nr,{k:"ask",question:rr},...sr],Nt=[{n:2184,title:"Retry payout webhooks with backoff",verdict:"1 P1, 1 P2",findings:"P1 payouts/retry.ts:48: the backoff doubles from 0, so every retry fires at once. P2 the new test never advances its fake clock."},{n:2191,title:"Add idempotency keys to refund endpoint",verdict:"No findings",findings:"The key is checked before the ledger write, and a replay returns the first answer. I tried a concurrent pair and a key reused with another body; both hold."},{n:2197,title:"Migrate dispute table to partitioned storage",verdict:"1 P0",findings:"P0 migrations/0412.sql:31: the backfill copies rows without the tenant column, so every dispute lands in the default partition."},{n:2203,title:"Round currency amounts at the ledger boundary",verdict:"1 P2",findings:"P2 ledger/round.ts:12: half-even rounding is right for USD, but JPY has no minor unit and still gets two decimal places."}];function ar(t){return[{k:"user",text:`Review pull request #${t.n}: ${t.title}`},{k:"tool",tool:"bash",label:`Ran git diff origin/main...pr-${t.n} --stat`,input:`git diff origin/main...pr-${t.n} --stat`,result:" 6 files changed, 214 insertions(+), 38 deletions(-)",ms:700},{k:"tool",tool:"bash",label:`Ran git diff origin/main...pr-${t.n}`,input:`git diff origin/main...pr-${t.n}`,result:`diff --git a/payouts/retry.ts b/payouts/retry.ts
96
- …`,ms:900},{k:"think",text:"I'll read the code around each change, then try to break each changed function with an input the tests do not cover."},{k:"tool",tool:"bash",label:"Ran npm test -- --run changed",input:"npm test -- --run changed",result:`Test Files 4 passed (4)
97
- Tests 31 passed (31)`,ms:4200},{k:"final",text:`PR #${t.n} (${t.title}): ${t.verdict}. ${t.findings}`}]}const or=[{k:"user",text:"Review pull request #2210: Rewrite settlement batching (4,100 changed lines)"},{k:"tool",tool:"bash",label:"Ran git diff origin/main...pr-2210 --stat",input:"git diff origin/main...pr-2210 --stat",result:" 58 files changed, 2903 insertions(+), 1197 deletions(-)",ms:800},{k:"think",text:"This is a large change. I'll take the settlement core first, then the callers."},{k:"tool",tool:"bash",label:"Ran git diff origin/main...pr-2210 -- settlement/",input:"git diff origin/main...pr-2210 -- settlement/",result:`diff --git a/settlement/batch.ts b/settlement/batch.ts
98
- …`,ms:1300},{k:"tool",tool:"bash",label:"Ran npm test -- --run settlement",input:"npm test -- --run settlement",result:`Test Files 11 passed (11)
99
- Tests 142 passed (142)`,ms:6100},{k:"error",text:"The run reached its spend cap of $1.50 before it finished. Nothing was posted to the pull request."}],ir=[{ask:"Proposal: move refunds to an async queue so the API answers in under 100 ms.",says:"It touches refunds/api.ts, ledger/post.ts and the webhook sender. At risk: idempotency (a retried request would enqueue twice) and the ledger's balance between enqueue and post. Smallest change: keep the ledger write in the request, and queue only the processor call and the email."},{ask:"Proposal: one database per tenant for the dispute tables.",says:"It touches every dispute query and the nightly settlement job. At risk: cross-tenant reports, which join disputes to payouts. Smallest change: partition the two largest tables by tenant and leave the rest; that gets the isolation without 400 connection pools."},{ask:"Proposal: replace the cron-based payout batcher with event-driven payouts.",says:"It touches payouts/batch.ts and the bank file writer. At risk: the bank's cut-off, which the batcher meets by construction. Smallest change: keep the batch at the cut-off and send events for status only."}];function lr(t){return[{k:"user",text:t.ask},{k:"tool",tool:"Grep",label:"Searched the code for the modules the proposal names",input:"refund|ledger|payout",result:`refunds/api.ts
100
- ledger/post.ts
101
- payouts/batch.ts
102
- webhooks/send.ts`,ms:800},{k:"tool",tool:"Read",label:"Read docs/adr/0007-ledger-invariants.md",input:"docs/adr/0007-ledger-invariants.md",result:"Every money movement is one ledger transaction, written before the caller is answered…",ms:400},{k:"think",text:"The proposal's speed-up comes from one slow call. The invariants only need the ledger write to stay where it is."},{k:"final",text:t.says}]}function dr(t){return[{k:"user",text:`Review my staged changes: ${t.title}`},{k:"tool",tool:"shell",label:"Ran git diff --staged",input:"git diff --staged",result:`diff --git a/ledger/round.ts b/ledger/round.ts
103
- …`,ms:500},{k:"tool",tool:"shell",label:"Ran npm test -- --run changed",input:"npm test -- --run changed",result:"Test Files 3 passed (3)",ms:3100},{k:"final",text:`${t.verdict}. ${t.findings}`}]}const Zt={kind:"review",node:"route",reason:"The certificate's filing date and the registry's formation date do not agree, so the route was unsure and sent the merchant to a person."},Xt={kind:"review",node:"route",reason:"The jurors did not agree on whether the storefront sells restricted goods."},en={kind:"review",node:"report",reason:"One certificate's check was interrupted, so its outcome is unknown and a person reads it."},tn=12;function pt(){const t=Xe[0];return[{id:"demo-run-refund-approval",agent:"refund-desk",title:"Refund request R-48213: Mara Ellison",startAgo:14*re,input:{content:`Refund request R-48213: ${t.buyer}`},beats:Vt(t,"R-48213"),usd:.0214,path:"workflow",trigger:"trg-demo-helpdesk-refunds",hero:!0,files:{"decisions/R-48213.md":It(t,"R-48213")}},{id:"demo-run-brief-question",agent:"weekly-risk-brief",title:"Write this week's risk brief",startAgo:47*re,input:{content:"Write this week's risk brief."},beats:kt(),usd:.412,effort:"high",trigger:"trg-demo-weekly-brief",hero:!0,files:{"brief.md":yt,"sources.csv":wt}},{id:"demo-run-certificates-live",agent:"certificate-review",title:"Certificates: 20 new merchants",startAgo:6e3,input:{documents:["bramblewood-freight.pdf","corvane-analytics.pdf","…18 more"]},graph:"batch",usd:.0931,review:en,hero:!0},{id:"demo-run-triage-live",agent:"support-triage",title:`Ticket #5512: ${et[1].subject}`,startAgo:1500,input:{content:et[1].subject},beats:Qt(et[1],5512).map(n=>({...n,wait:(n.wait??0)+2600})),usd:.0094,trigger:"trg-demo-helpdesk-tickets",hero:!0},{id:"demo-run-review-capped",agent:"pr-reviewer",title:"Review PR #2210: Rewrite settlement batching",startAgo:3*ie+12*re,input:{content:"Review pull request #2210"},beats:or,usd:1.5,fails:{code:"spend_cap_reached",message:"The run reached its spend cap of $1.50 before it finished."},afterCap:"Reviewed PR #2210. The settlement core is sound and its 142 tests pass. Two things to fix before merge: batch.ts retries a failed settlement without its idempotency key, and the new cut-off check reads the server's clock, not the bank's. Posted 2 review comments.",trigger:"trg-demo-pull-requests",hero:!0},{id:"demo-run-kyb-review",agent:"kyb-check",title:"KYB: Corvane Analytics Inc.",startAgo:2*ie+40*re,input:{merchant:"Corvane Analytics Inc.",document:"corvane-analytics.pdf"},graph:"kyb",usd:.0473,review:Zt,hero:!0},{id:"demo-run-jury",agent:"prohibited-goods-jury",title:"Storefront: Saltmarsh Outdoor Gear Co.",startAgo:5*ie+5*re,input:{merchant:"Saltmarsh Outdoor Gear Co.",url:"https://saltmarsh-outdoor.example"},graph:"jury",usd:.0188,review:Xt,hero:!0},{id:"demo-run-brief-done",agent:"weekly-risk-brief",title:"Write this week's risk brief",startAgo:7*U+47*re,input:{content:"Write this week's risk brief."},beats:kt(),usd:.438,effort:"high",answered:[{afterMs:9*re,text:"Use the bulletin's date. It is the primary source."}],trigger:"trg-demo-weekly-brief",files:{"brief.md":yt,"sources.csv":wt},hero:!0},{id:"demo-run-refund-by-agent",agent:"refund-desk",title:"Refund request R-47391: Teodor Vance",startAgo:19*U+3*ie,input:{content:"Refund request R-47391: Teodor Vance"},beats:Jt(Xe[1],"R-47391"),usd:.2082,path:"agent",answered:[{afterMs:6*re,decision:"allow"}],files:{"decisions/R-47391.md":It(Xe[1],"R-47391")},hero:!0}]}function Mt(t,n=30){const o=Xn(4757),i=[];let g=4100,d=46800,h=0;const y=()=>`demo-run-${String(++h).padStart(4,"0")}`;for(let u=n;u>=0;u--){const D=O=>{const C=new Date(O).getUTCDay();return C>=1&&C<=5},R=D(t-u*U),x=(R?1:.35)*(u===0?.3:1),w=()=>u*U-Math.floor(X(o,u===0?.5*ie:0,u===0?7*ie:23*ie))+(u===0?8*ie:0);for(let O=0;O<Math.round(X(o,14,24)*x);O++){const C=Se(o,et);i.push({id:y(),agent:"support-triage",title:`Ticket #${++g}: ${C.subject}`,startAgo:w(),input:{content:C.subject},beats:Qt(C,g),usd:X(o,.006,.013),trigger:"trg-demo-helpdesk-tickets"})}for(let O=0;O<Math.round(X(o,5,10)*x);O++){const C=Se(o,Xe),f=`R-${++d}`,q=u<tn?o()<.08?"handed_back":"workflow":"agent";i.push({id:y(),agent:"refund-desk",title:`Refund request ${f}: ${C.buyer}`,startAgo:w(),input:{content:`Refund request ${f}: ${C.buyer}`},beats:q==="workflow"?Vt(C,f):Jt(C,f),usd:q==="workflow"?X(o,.017,.027):q==="handed_back"?X(o,.12,.16):X(o,.17,.24),path:q,answered:[{afterMs:X(o,1,14)*re,decision:o()<.04?"deny":"allow"}],trigger:"trg-demo-helpdesk-refunds"})}for(let O=0;O<Math.round(X(o,3,6)*x);O++){const C=o()<.12,f=Se(o,Pt);i.push({id:y(),agent:"kyb-check",title:`KYB: ${f}`,startAgo:w(),input:{merchant:f},graph:"kyb",usd:X(o,.016,.018),...C?{review:Zt}:{}})}if(o()<.4*x){const O=Se(o,Pt);i.push({id:y(),agent:"prohibited-goods-jury",title:`Storefront: ${O}`,startAgo:w(),input:{merchant:O},graph:"jury",usd:X(o,.015,.022),review:Xt})}if(u>0&&D(t-u*U+9*ie)&&i.push({id:y(),agent:"certificate-review",title:`Certificates: ${Math.round(X(o,8,20))} new merchants`,startAgo:u*U-9*ie,input:{documents:["…"]},graph:"batch",usd:0,review:en,trigger:"trg-demo-weekday-certificates"}),R&&u>0)for(let O=0;O<Math.round(X(o,2,5));O++){const C=Se(o,Nt),f=o()<.05;i.push({id:y(),agent:"pr-reviewer",title:`Review PR #${C.n-u*7-O}: ${C.title}`,startAgo:w(),input:{content:`Review pull request #${C.n}`},beats:ar(C),usd:X(o,.31,.92),trigger:"trg-demo-pull-requests",...f?{fails:{code:"run_failed",message:"The checkout of the pull request's branch failed: the branch was deleted."}}:{}})}if(R&&u<16&&o()<.45){const O=Se(o,ir);i.push({id:y(),agent:"architect",title:`Design review: ${O.ask.slice(10).replace(/\.$/,"")}`,startAgo:w(),input:{content:O.ask},beats:lr(O),usd:X(o,.22,.41)})}if(R&&u<11)for(let O=0;O<Math.round(X(o,0,3));O++){const C=Se(o,Nt);i.push({id:y(),agent:"code-reviewer",title:`Review staged changes: ${C.title}`,startAgo:w(),input:{content:C.title},beats:dr(C),usd:X(o,.09,.2)})}u%7===0&&u>7&&i.push({id:y(),agent:"weekly-risk-brief",title:"Write this week's risk brief",startAgo:u*U+47*re,input:{content:"Write this week's risk brief."},beats:kt(),usd:X(o,.38,.47),effort:"high",answered:[{afterMs:X(o,4,40)*re,text:"Use the primary source's date."}],trigger:"trg-demo-weekly-brief",files:{"brief.md":yt,"sources.csv":wt}})}return i}const Pt=["Bramblewood Freight LLC","Corvane Analytics Inc.","Duskridge Holdings Ltd.","Ellery & Thorn Supply Co.","Fenwhistle Robotics Inc.","Glasswing Ceramics LLC","Harrowgate Logistics Corp.","Saltmarsh Outdoor Gear Co.","Tidewater Print Works","Quillfeather Stationery Ltd."],Lt=`# Corrections
104
-
105
- - Quote the policy line you applied, word for word, in the decision note.
106
- - "Wrong item sent" counts as damaged on arrival: full refund, no return under $250.
107
- - Never name a refund date in the email. Say "to your original payment method".
108
- - When the carrier's record has no delivery scan, check the last movement's age before deciding.
109
- `,ur=`# refund-decision
110
-
111
- Decides a buyer's refund request the way the agent did in its first 140 runs: read the policy, look the order up, pick
112
- the policy line that applies, work the refund out in code, write the note, and draft the email.
113
-
114
- Hands back to the agent when no policy line fits what the buyer said.
115
- `,Ne="larkspur/marketplace",_t=`https://github.example/${Ne}`,tt="4f1c2a9d0b7e",ft=t=>new Date(t).toISOString(),De=(t,n)=>`${_t}/blob/${tt}/${t}#L${n}`,Ie=[{id:"sug_demo_dispute_evidence",key:"dispute-evidence",impact:"high",title:"Gather a chargeback's evidence",summary:"Collect the order, delivery scans and messages a chargeback dispute needs, and say which are missing.",why:"disputes/submit.ts builds each dispute's evidence by hand from four services, and the comment above it says half the disputes lost last quarter were missing a delivery scan.",evidence:[{path:"disputes/submit.ts",line:42,quote:"// TODO: evidence is assembled by support by hand; missing scans lose disputes",url:De("disputes/submit.ts",42)},{path:"disputes/submit.ts",line:57,quote:"const evidence = await collectEvidenceManually(dispute.id);",url:De("disputes/submit.ts",57)}],agent:{name:"Dispute evidence",description:"Gathers the evidence a chargeback dispute needs and lists what is missing.",inputs:[{name:"dispute_id",type:"string",description:"The dispute to gather evidence for.",required:!0}],output:[{name:"missing",type:"string_list",description:"Evidence the dispute still needs."},{name:"ready",type:"boolean",description:"Whether the dispute can be submitted."}],tools:["web_fetch"],tier:"balanced",instructions:"Read the dispute, fetch the order, its delivery scans and the buyer's messages, and list what the card network asks for that is still missing."},integration:{language:"typescript",path:"agents/dispute-evidence.ts",call_site:{path:"disputes/submit.ts",line:57,note:"Replace the hand-built evidence with the agent's answer.",url:De("disputes/submit.ts",57)}},files:[{path:"agents/dispute-evidence.ts",content:`import { runAgent } from "@parcha/agentrun";
116
-
117
- export async function disputeEvidence(disputeId: string) {
118
- return runAgent("dispute-evidence", { dispute_id: disputeId });
119
- }
120
- `}]},{id:"sug_demo_listing_review",key:"listing-review",impact:"medium",title:"Review a new listing against the prohibited-goods policy",summary:"Read a new listing's title, photos' alt text and description, and flag the ones the policy forbids.",why:"listings/moderation.ts sends every new listing to a review queue that a person clears by hand; most are fine.",evidence:[{path:"listings/moderation.ts",line:18,quote:"await reviewQueue.push(listing); // every listing, by hand",url:De("listings/moderation.ts",18)}],agent:{name:"Listing review",description:"Flags a new listing the prohibited-goods policy forbids, with the line it breaks.",inputs:[{name:"listing_url",type:"string",description:"The listing to review.",required:!0}],output:[{name:"verdict",type:"string",description:"allowed, forbidden or unsure.",enum:["allowed","forbidden","unsure"]}],tools:["web_fetch"],tier:"fast"},integration:{language:"typescript",path:"agents/listing-review.ts",call_site:{path:"listings/moderation.ts",line:18,note:"Queue only the listings the agent marks forbidden or unsure.",url:De("listings/moderation.ts",18)}},files:[{path:"agents/listing-review.ts",content:`import { runAgent } from "@parcha/agentrun";
121
-
122
- export async function reviewListing(url: string) {
123
- return runAgent("listing-review", { listing_url: url });
124
- }
125
- `}]},{id:"sug_demo_payout_notes",key:"payout-notes",impact:"low",title:"Explain a held payout to the seller",summary:"Write the seller a short note on why a payout is held and what clears it.",why:'payouts/hold.ts sets a hold reason code, and support answers each "where is my payout" ticket by looking it up.',evidence:[{path:"payouts/hold.ts",line:33,quote:"hold.reason = HoldReason.RiskReview; // seller sees nothing",url:De("payouts/hold.ts",33)}],agent:{name:"Payout notes",description:"Writes a seller a plain note on why a payout is held and what clears it.",inputs:[{name:"payout_id",type:"string",description:"The held payout.",required:!0}],output:[{name:"note",type:"string",description:"The note to the seller."}],tools:[],tier:"fast"},integration:{language:"typescript",path:"agents/payout-notes.ts",call_site:{path:"payouts/hold.ts",line:33,note:"Send the agent's note with the hold.",url:De("payouts/hold.ts",33)}},files:[{path:"agents/payout-notes.ts",content:`import { runAgent } from "@parcha/agentrun";
126
-
127
- export async function payoutNote(payoutId: string) {
128
- return runAgent("payout-notes", { payout_id: payoutId });
129
- }
130
- `}]}];function cr({opened:t,makeAgent:n,clock:o,holdScan:i,readRun:g}){const d=new Map,h=Ie.map(S=>({path:S.evidence[0].path,line:S.evidence[0].line,quote:S.evidence[0].quote,title:S.title})),y=(S,j)=>i({repo:Ne,commit:tt,start:S,ms:j,found:h});let D={run_id:y(t-2*864e5,4*6e4).run_id,agent_id:"suggestion-scanner",started_at:ft(t-2*864e5),status:"running",ended_at:null,app:"larkspur-agentrun",commit:tt,found:null,dropped:[],already_decided:0,error:null},R=2240;const x=()=>{var j;if(D.status!=="running")return D;const S=g(D.run_id);return S!=null&&S.ended_at&&(S.status==="completed"&&((j=S.result)!=null&&j.final_answer)?D={...D,status:"completed",ended_at:S.ended_at,found:Ie.length,already_decided:[...d.values()].filter(P=>P.status!=="open").length}:D={...D,status:S.status==="cancelled"?"cancelled":"failed",ended_at:S.ended_at,found:0,error:S.status==="cancelled"?null:"The scan ended without an answer to read."}),D},w=S=>{const{files:j,...P}=S,F=d.get(S.id),_=x();return{...P,repo:Ne,status:(F==null?void 0:F.status)??"open",scan:{run_id:_.run_id,commit:tt,at:_.ended_at??_.started_at},decided_at:F!=null&&F.decidedAt?ft(F.decidedAt):null,created:(F==null?void 0:F.created)??null}};return{list:()=>{const S=Ie.map(w),j=P=>S.filter(F=>F.status===P).length;return{github:{connected:!0,app:"larkspur-agentrun",installations:[{account:"larkspur"}],install_url:null},repositories:[{repo:Ne,scan:x(),counts:{open:j("open"),created:j("created"),discarded:j("discarded")}}],suggestions:S}},detail:S=>{const j=Ie.find(P=>P.id===S);return j?{...w(j),files:j.files,problems:[],github:{ready:!0,reason:null,message:null,missing:[],install_url:null,permissions_url:null,installation_url:`${_t}/settings/installations`}}:null},decide:(S,j)=>{const P=Ie.find(F=>F.id===S);return P?(d.set(S,{status:j,decidedAt:j==="open"?null:o(),created:null}),w(P)):null},create:(S,j)=>{const P=Ie.find(v=>v.id===S);if(!P)return null;const F=d.get(S);if((F==null?void 0:F.status)==="created")return w(P);const _=n({version:1,name:(j==null?void 0:j.trim())||P.agent.name,description:P.agent.description,instructions:P.agent.instructions??P.summary,tools:P.agent.tools,skills:[]});return R+=1,d.set(S,{status:"created",decidedAt:o(),created:{agent_id:_.agent_id,template_id:`suggested-${P.key}`,branch:`agentrun/${P.key}`,pull_request:{number:R,url:`${_t}/pull/${R}`},pull_error:null}}),w(P)},rescan:S=>{if(S!==Ne)return null;const j=x().status==="running";if(!j){const P=y(o(),6e3);D={...D,run_id:P.run_id,started_at:ft(o()),status:"running",ended_at:null,found:null,error:null}}return{repo:S,run_id:D.run_id,agent_id:D.agent_id,status:"running",already_running:j}},repositories:()=>({repositories:[{full_name:Ne,private:!0,account:"larkspur",installation:41207,default_branch:"main",description:"Larkspur's marketplace: listings, orders, payouts and disputes."}],truncated:!1,unread:[]})}}const $t=[["Bramblewood Freight LLC","Delaware","6012477","2019-03-14","Ines Calloway"],["Corvane Analytics Inc.","Delaware","7340291","2021-08-02","Ines Calloway"],["Duskridge Holdings Ltd.","Nevada","E0583322017-4","2017-11-20","Marcus Teague"],["Ellery & Thorn Supply Co.","Wyoming","2020-000918273","2020-01-09","Dana Whitlock"],["Fenwhistle Robotics Inc.","Delaware","5523108","2015-06-30","Ines Calloway"],["Glasswing Ceramics LLC","Oregon","1588420-97","2018-04-11","Paul Okafor"],["Harrowgate Logistics Corp.","Texas","0803119462","2016-09-27","Rosa Lindqvist"],["Ivorybrook Dental Group PLLC","New York","5932174","2021-02-18","Thomas Achebe"],["Juniper Kettle Foods Inc.","California","C4419027","2019-12-05","Mei Harrington"],["Kestrelmoor Energy LLC","Colorado","20201774650","2020-07-21","Gil Ferreira"],["Lanternfield Studios Inc.","Delaware","6630085","2022-05-03","Ines Calloway"],["Marrowby Textiles Ltd.","North Carolina","1830442","2014-10-14","Ada Nwosu"],["Northpine Brewing Co.","Washington","604 118 772","2013-03-29","Lena Sorensen"],["Oakhollow Medical Supply LLC","Florida","L19000227781","2019-08-16","Victor Mendes"],["Pellucid Water Systems Inc.","Arizona","23300912","2023-01-23","Helen Marsh"],["Quillon Security Group LLC","Virginia","S8820145","2018-11-02","Jonah Pryce"],["Rookery Lane Bakeries Inc.","Massachusetts","001492275","2012-04-17","Clara Beaumont"],["Saltmarsh Outdoor Gear Co.","Maine","20170833DC","2017-06-08","Owen Tate"],["Tidewell Marine Services LLC","Louisiana","42188115K","2016-02-25","Yvette Robichaux"],["Umberfold Paper Works Inc.","Wisconsin","U071244","2011-09-12","Karl Ostrowski"]].map(([t,n,o,i,g])=>({name:t,state:n,number:o,filed:i,officer:g,file:`coi-${t.split(/[^A-Za-z]/)[0].toLowerCase()}.pdf`})),xe=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ft=t=>new Date(`${t}T12:00:00Z`).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"});function pr(t,{altered:n=!1,noSeal:o=!1,faint:i=!1}={}){const g=i?"#9a958a":"#2b2a27",d=[`I, ${t.officer}, Secretary of State of the State of ${t.state},`,"do hereby certify that the attached is a true and correct copy",`of the Certificate of Incorporation of "${t.name.toUpperCase()}",`,`filed in this office on the date below, under file number ${t.number}.`],h=`<svg xmlns="http://www.w3.org/2000/svg" width="850" height="1100" viewBox="0 0 850 1100">
131
- <rect width="850" height="1100" fill="#fbf9f3"/>
132
- <rect x="38" y="38" width="774" height="1024" fill="none" stroke="#7a6a48" stroke-width="3"/>
133
- <rect x="50" y="50" width="750" height="1000" fill="none" stroke="#7a6a48" stroke-width="1"/>
134
- <text x="425" y="150" font-family="Georgia, serif" font-size="30" text-anchor="middle" fill="${g}" letter-spacing="3">STATE OF ${xe(t.state.toUpperCase())}</text>
135
- <text x="425" y="195" font-family="Georgia, serif" font-size="20" text-anchor="middle" fill="${g}">OFFICE OF THE SECRETARY OF STATE</text>
136
- <line x1="200" y1="225" x2="650" y2="225" stroke="#7a6a48"/>
137
- <text x="425" y="300" font-family="Georgia, serif" font-size="36" font-style="italic" text-anchor="middle" fill="${g}">Certificate of Incorporation</text>
138
- <text x="425" y="380" font-family="Georgia, serif" font-size="28" font-weight="bold" text-anchor="middle" fill="${g}">${xe(t.name)}</text>
139
- ${d.map((y,u)=>`<text x="110" y="${470+u*38}" font-family="Georgia, serif" font-size="19" fill="${g}">${xe(y)}</text>`).join(`
140
- `)}
141
- <text x="110" y="660" font-family="Georgia, serif" font-size="19" fill="${g}">Filed:</text>
142
- ${n?`<rect x="176" y="640" width="260" height="30" fill="#fdfdfd"/><text x="182" y="663" font-family="Arial, sans-serif" font-size="18" fill="#1d1d1d">${xe(Ft(t.filed))}</text>`:`<text x="180" y="660" font-family="Georgia, serif" font-size="19" fill="${g}">${xe(Ft(t.filed))}</text>`}
143
- <text x="110" y="700" font-family="Georgia, serif" font-size="19" fill="${g}">File number: ${xe(t.number)}</text>
144
- ${o?"":`<g transform="translate(220 860)"><circle r="92" fill="none" stroke="#a3342c" stroke-width="4"/><circle r="74" fill="none" stroke="#a3342c" stroke-width="1.5"/><text y="-30" font-family="Georgia, serif" font-size="15" text-anchor="middle" fill="#a3342c">GREAT SEAL</text><text y="6" font-family="Georgia, serif" font-size="22" text-anchor="middle" fill="#a3342c" font-weight="bold">${xe(t.state.toUpperCase().slice(0,12))}</text><text y="38" font-family="Georgia, serif" font-size="14" text-anchor="middle" fill="#a3342c">FILED</text></g>`}
145
- <path d="M 520 880 C 545 840, 560 905, 585 860 S 625 850, 640 880 S 690 860, 720 872" fill="none" stroke="#1f2b5c" stroke-width="2.4"/>
146
- <line x1="500" y1="905" x2="740" y2="905" stroke="${g}"/>
147
- <text x="620" y="930" font-family="Georgia, serif" font-size="16" text-anchor="middle" fill="${g}">${xe(t.officer)}, Secretary of State</text>
148
- </svg>`;return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(h)}`}const je=(t,n)=>new Date(Date.parse(t)+n).toISOString(),nn=t=>t.replace(/\.pdf$/,""),st=t=>`pages/${nn(t.file)}/1.png`,rn=(t,n)=>`/v2/runs/${t}/files/${n}`,me=t=>({type:"noul",noul:t}),Be=t=>Object.fromEntries(Object.entries(t.properties).map(([n,o])=>[n,{type:"noul",instructions:o.description}])),He=t=>`STATE OF ${t.state.toUpperCase()}
149
- OFFICE OF THE SECRETARY OF STATE
150
- Certificate of Incorporation
151
- ${t.name}
152
- I, ${t.officer}, Secretary of State of the State of ${t.state}, do hereby certify that the attached is a true and correct copy of the Certificate of Incorporation of "${t.name.toUpperCase()}", filed in this office on the date below, under file number ${t.number}.
153
- Filed: ${t.filed}
154
- File number: ${t.number}`,sn={};for(const[t,n]of $t.entries())sn[st(n)]=pr(n,{altered:t===5,noSeal:t===12,faint:t===15});const an="run_01JD7K2X9QH4M8B6TPC3ZV5W1R",Te="2026-10-30T15:02:11.000Z",Re="/root/steps/0",on=`${Re}/body/steps/0`,ln=`${Re}/body/steps/1`,fr=`${Re}/body/steps/2`,gr="/root/steps/1",at={3:"render_failed",7:"rate_limited",9:"interrupted"},hr={5:{altered:.86},12:{seal:.07},15:{legible:.58,signature:.71}},Oe=(t,n)=>(t*7919+n*104729)%1e3/1e3,Ce=(()=>{const t=[0,0,0,0];return $t.map((n,o)=>{const i=t.indexOf(Math.min(...t)),g=t[i]+15,d=g+700+Math.round(Oe(o,1)*1100),h=d+30,y=at[o]==="render_failed"?d:h+1300+Math.round(Oe(o,2)*1700),u=y+12;return t[i]=u,{i:o,c:n,start:g,renderEnd:d,judgeStart:h,judgeEnd:y,end:u}})})(),Me=Math.max(...Ce.map(t=>t.end))+60;function mr(t){const n=at[t.i];if(n==="render_failed")return null;const o={altered:.03+Oe(t.i,3)*.05,seal:.93+Oe(t.i,4)*.06,signature:.88+Oe(t.i,5)*.1,legible:.95+Oe(t.i,6)*.045,...hr[t.i]},i=!n,g=st(t.c);return{id:`dec_${nn(t.c.file)}_inspect`,node:ln,executionPath:`${Re}/items/${t.i}/body/steps/1`,item:t.i,kind:"judge",provider:"jev",model:"jev-latest",status:i?"answered":n==="interrupted"?"cancelled":"failed",questions:Be(Ke),answers:i?Object.fromEntries(Object.entries(o).map(([d,h])=>[d,me(Number(h.toFixed(3)))])):{},rule:i?{kind:"judge"}:null,action:i?{altered:o.altered>=.5,seal:o.seal>=.5,signature:o.signature>=.5,legible:o.legible>=.5}:null,cost_usd:n==="rate_limited"?0:n==="interrupted"?null:Number((.0036+Oe(t.i,7)*.0011).toFixed(5)),cost_basis:n==="interrupted"?"unknown":"provider",latency_ms:t.judgeEnd-t.judgeStart,state:{document:t.c.file,page:"<page1>",text:He(t.c)},state_truncated:!1,images:[{token:"<page1>",ref:g,url:rn(an,g)}],...n==="rate_limited"?{error:"rate_limited: 429 Too Many Requests; Retry-After 30 s is past the node's deadline"}:{},...n==="interrupted"?{error:"outcome_unknown: the connection closed after the request was sent; not asked again"}:{}}}function yr(t,n){if(n<t.start)return null;const o=n>=t.renderEnd,i=at[t.i]==="render_failed",g=st(t.c);return{node:on,executionPath:`${Re}/items/${t.i}/body/steps/0`,item:t.i,tool:"pdf_pages",status:o?i?"failed":"done":"working",input:{path:t.c.file,maxPages:2},output:o?i?{error:{code:"exit",message:"pdftoppm exited 1: Syntax Error: Couldn't find trailer dictionary"}}:{name:t.c.file,pageCount:1,pages:[{page:1,image:g}],text:He(t.c)}:null,startedAt:je(Te,t.start),...o?{endedAt:je(Te,t.renderEnd)}:{}}}function dn(t,{paused:n=!1}={}){const o=Ce.map(w=>{const O=at[w.i],C=t<w.start?"pending":t<w.end?"working":O==="interrupted"?"needs_review":O?"failed":"done";return{index:w.i,status:C,executionPath:`${Re}/items/${w.i}`,label:w.c.file}}),i=Ce.map(w=>yr(w,t)).filter(w=>!!w),g=Ce.filter(w=>t>=w.judgeEnd).map(mr).filter(w=>!!w),d=Ce.every(w=>t>=w.end),h=t>=Me,y=w=>t>=w?je(Te,w):void 0,u=w=>Ce.some(w),D=w=>({status:d?"done":u(O=>t>=w(O))?"working":"pending",startedAt:y(Math.min(...Ce.map(w)))}),R={"/root":{status:h?"done":"working",startedAt:Te,...h?{endedAt:je(Te,Me)}:{}},[Re]:{status:d?"done":"working",startedAt:Te,items:o},[`${Re}/body`]:{status:d?"done":"working"},[on]:D(w=>w.start),[ln]:D(w=>w.judgeStart),[fr]:D(w=>w.judgeEnd),[gr]:{status:h?"done":d?"working":"pending"}},x=g.map(w=>w.cost_usd);return{run:{id:an,agent:"agt_coi_batch",revision:"rev_3",status:h?"completed":"working",paused:n&&!h,startedAt:Te,endedAt:h?je(Te,Me):null},workflow:mt,graph:bt(mt),nodes:R,decisions:g,effects:i,totals:{cost_usd:x.some(w=>w===null)?null:x.reduce((w,O)=>w+(O??0),0),decisions:g.length,effects:i.length,elapsed_ms:Math.min(t,Me)}}}const Wt="run_01JD7M4F2C8N1S5VXK7QDR3E9A",wr="2026-10-30T15:20:42.000Z",ge=$t[1];function nt(){const t=st(ge),n=d=>je(wr,d),o=[{id:"dec_kyb_registry",node:"/root/steps/1/branches/0",executionPath:"/root/steps/1/branches/0",item:null,kind:"judge",provider:"parallel",model:"standard",status:"answered",questions:Be(Ae.schemas.Registry),answers:{registered:me(.97),active:me(.94),name_matches:me(.91)},rule:{kind:"judge"},action:{registered:!0,active:!0,name_matches:!0},cost_usd:.01,cost_basis:"provider",latency_ms:21430,evidence:[{url:"https://corp.delaware.example/entity/7340291",title:"Division of Corporations: Entity Details, CORVANE ANALYTICS, INC.",scope:"registered",excerpts:["File Number: 7340291. Incorporation Date / Formation Date: 08/05/2021. Entity Kind: Corporation. Entity Type: General. Residency: Domestic. State: DELAWARE.","Registered Agent: Harbor Agents Inc., 1209 Orange Grove Rd, Wilmington, DE 19801."]},{url:"https://corp.delaware.example/entity/7340291/status",title:"Status: Good Standing, as of 10/28/2026",scope:"active",excerpts:["Status: Good Standing. Franchise tax filed for 2025. No forfeiture or voidance recorded."]},{url:"https://www.corvane-analytics.example/about",title:"About Corvane Analytics",scope:"name_matches",excerpts:["Corvane Analytics, Inc. is a Delaware corporation headquartered in Austin, Texas, building demand-forecasting software for regional grocers."]}],state:{company:ge.name,state:ge.state,registration_number:ge.number},state_truncated:!1,images:[]},{id:"dec_kyb_look",node:"/root/steps/1/branches/1",executionPath:"/root/steps/1/branches/1",item:null,kind:"judge",provider:"jev",model:"jev-latest",status:"answered",questions:Be(Ae.schemas.CertLook),answers:{altered:me(.07),seal:me(.96),legible:me(.98)},rule:{kind:"judge"},action:{altered:!1,seal:!0,legible:!0},cost_usd:.0042,cost_basis:"provider",latency_ms:2310,state:{page:"<cert>",text:He(ge)},state_truncated:!1,images:[{token:"<cert>",ref:t,url:rn(Wt,t)}]},{id:"dec_kyb_cross",node:"/root/steps/2",executionPath:"/root/steps/2",item:null,kind:"judge",provider:"jev",model:"jev-latest",status:"answered",questions:Be(Ae.schemas.CrossCheck),answers:{same_entity:me(.95),same_state:me(.98),dates_consistent:me(.38)},rule:{kind:"judge"},action:{same_entity:!0,same_state:!0,dates_consistent:!1},cost_usd:.0016,cost_basis:"provider",latency_ms:910,state:{applicant:{company:ge.name,state:ge.state},registry:{answers:{registered:.97,active:.94,name_matches:.91},formation_date:"2021-08-05"},certificate_text:He(ge)},state_truncated:!1,images:[]},{id:"dec_kyb_route",node:"/root/steps/3",executionPath:"/root/steps/3",item:null,kind:"route",provider:"jev",model:"jev-latest",status:"answered",questions:{branch:{type:"choice",instructions:Ae.root.steps[3].instructions,criteria:Object.fromEntries(Object.entries(Ae.root.steps[3].branches).map(([d,h])=>[d,h.criteria]))}},answers:{branch:{type:"choice",choice:"approve",probabilities:{approve:.61,review:.33,reject:.06},confidence:.61}},rule:{kind:"route",branches:["approve","review","reject"],unsure:{gte:.75,branch:"review"}},action:{branch:"approve",taken:"review",unsure:!0},cost_usd:.0012,cost_basis:"provider",latency_ms:740,state:{registry:{registered:!0,active:!0,name_matches:!0},look:{altered:!1,seal:!0,legible:!0},cross:{same_entity:!0,same_state:!0,dates_consistent:!1}},state_truncated:!1,images:[]}],i=[{node:"/root/steps/0",executionPath:"/root/steps/0",item:null,tool:"pdf_pages",status:"done",input:{path:ge.file,maxPages:1},output:{name:ge.file,pageCount:1,pages:[{page:1,image:t}],text:He(ge)},startedAt:n(40),endedAt:n(1220)}],g={"/root":{status:"done",startedAt:n(0),endedAt:n(24980)},"/root/steps/0":{status:"done",startedAt:n(40),endedAt:n(1220)},"/root/steps/1":{status:"done",startedAt:n(1240),endedAt:n(22690)},"/root/steps/1/branches/0":{status:"done",startedAt:n(1250),endedAt:n(22680)},"/root/steps/1/branches/1":{status:"done",startedAt:n(1250),endedAt:n(3560)},"/root/steps/2":{status:"done",startedAt:n(22700),endedAt:n(23610)},"/root/steps/3":{status:"done",startedAt:n(23620),endedAt:n(24960),branch:"review"},"/root/steps/3/branches/approve/body":{status:"not_run"},"/root/steps/3/branches/review/body":{status:"done",startedAt:n(24365),endedAt:n(24960)},"/root/steps/3/branches/reject/body":{status:"not_run"}};return{run:{id:Wt,agent:"agt_kyb",revision:"rev_7",status:"completed",paused:!1,startedAt:n(0),endedAt:n(24980)},workflow:Ae,graph:bt(Ae),nodes:g,decisions:o,effects:i,totals:{cost_usd:o.reduce((d,h)=>d+(h.cost_usd??0),0),decisions:o.length,effects:i.length,elapsed_ms:24980}}}const kr="run_01JD7P0B6W3T9Y2HQX4N8KM5CF",_r="2026-10-30T15:31:07.000Z",Ut="Saltmarsh Outdoor Gear Co. sells camping, fishing and hunting supplies: fixed-blade hunting knives (4 to 7 inch), bear deterrent spray (EPA registered, 9.2 oz), folding saws, fire starters, and a 'trail kit' bundle. Shipping to all 50 states; bear spray not shipped to CA, NY or HI. Age verification at checkout for knives and sprays.";function xt(){const t=d=>je(_r,d),n=(d,h,y,u,D,R,x,w)=>({id:`dec_jury_${h}`,node:`/root/steps/1/branches/${d}`,executionPath:`/root/steps/1/branches/${d}`,item:null,kind:"judge",provider:y,model:u,status:"answered",questions:Be(Ze.schemas.Prohibited),answers:{prohibited:me(D)},rule:{kind:"judge"},action:{prohibited:D>=.5},cost_usd:R,cost_basis:"provider",latency_ms:x,...w?{evidence:w}:{},state:{merchant:"Saltmarsh Outdoor Gear Co.",url:"https://saltmarsh-outdoor.example",page_text:Ut},state_truncated:!1,images:[]}),o=[n(0,"jev","jev","jev-latest",.62,.0011,640),n(1,"pplx-decider","openrouter","perplexity/pplx-decider-v1.2",.21,.006,3120,[{url:"https://saltmarsh-outdoor.example/shipping",title:"Shipping and restricted items",scope:"prohibited",excerpts:["Bear deterrent spray is not shipped to California, New York or Hawaii. Knives ship with adult signature required."]},{url:"https://network-rules.example/prohibited-merchandise",title:"Card network rules: prohibited and restricted merchandise",scope:"prohibited",excerpts:["Sporting knives and EPA-registered animal deterrents are restricted, not prohibited, when sold with age verification."]}]),n(2,"liquid-d1","openrouter","liquid/d1",.74,9e-4,410),n(3,"clef","openrouter","cloudflare/clef",.35,4e-4,380)],i=[{node:"/root/steps/0",executionPath:"/root/steps/0",item:null,tool:"web_fetch",status:"done",input:{url:"https://saltmarsh-outdoor.example"},output:{status:200,url:"https://saltmarsh-outdoor.example/",title:"Saltmarsh Outdoor Gear: camp, fish, hunt",text:Ut},startedAt:t(30),endedAt:t(880)}],g={"/root":{status:"done",startedAt:t(0),endedAt:t(4110)},"/root/steps/0":{status:"done",startedAt:t(30),endedAt:t(880)},"/root/steps/1":{status:"done",startedAt:t(900),endedAt:t(4030)},...Object.fromEntries([640,3120,410,380].map((d,h)=>[`/root/steps/1/branches/${h}`,{status:"done",startedAt:t(905),endedAt:t(905+d)}])),"/root/steps/2":{status:"done",startedAt:t(4040),endedAt:t(4046)},"/root/steps/3":{status:"done",startedAt:t(4050),endedAt:t(4100),branch:"disagree"},"/root/steps/3/branches/agree/body":{status:"not_run"},"/root/steps/3/branches/disagree/body":{status:"done",startedAt:t(4052),endedAt:t(4100)}};return{run:{id:kr,agent:"agt_jury",revision:"rev_2",status:"completed",paused:!1,startedAt:t(0),endedAt:t(4110)},workflow:Ze,graph:bt(Ze),nodes:g,decisions:o,effects:i,totals:{cost_usd:o.reduce((d,h)=>d+(h.cost_usd??0),0),decisions:o.length,effects:i.length,elapsed_ms:4110}}}const pe=6e4,Gt={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6,jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function Ue(t,n,o){const i=new Set,g=d=>d.toLowerCase()in Gt?Gt[d.toLowerCase()]:/^\d+$/.test(d)?Number(d):NaN;for(const d of t.split(",")){const[h,y]=d.split("/"),u=y===void 0?1:Number(y);if(!Number.isInteger(u)||u<1)return null;let[D,R]=[n,o];if(h!=="*"){const[x,w]=h.split("-");D=g(x),R=w===void 0?y===void 0?D:o:g(w)}if(!Number.isInteger(D)||!Number.isInteger(R)||D<n||R>o||D>R)return null;for(let x=D;x<=R;x+=u)i.add(x)}return i}function br(t){const n={hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric"};let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:t,...n})}catch{o=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",...n})}const i=new Map;return g=>{const d=Math.floor(g/(60*pe));let h=i.get(d);if(h===void 0){const y=Object.fromEntries(o.formatToParts(g).map(u=>[u.type,u.value]));h=Date.UTC(Number(y.year),Number(y.month)-1,Number(y.day),Number(y.hour)%24,Number(y.minute))-Math.floor(g/pe)*pe,i.set(d,h)}return g+h}}function vr(t,n,o){const i=t.trim().split(/\s+/);if(i.length!==5)return null;const[g,d,h,y,u]=[Ue(i[0],0,59),Ue(i[1],0,23),Ue(i[2],1,31),Ue(i[3],1,12),Ue(i[4],0,7)];if(!g||!d||!h||!y||!u)return null;u.has(7)&&u.add(0);const D=i[2]==="*",R=i[4]==="*",x=q=>D||R?h.has(q.getUTCDate())&&u.has(q.getUTCDay()):h.has(q.getUTCDate())||u.has(q.getUTCDay()),w=q=>{const b=new Date(q);return y.has(b.getUTCMonth()+1)&&x(b)&&d.has(b.getUTCHours())&&g.has(b.getUTCMinutes())},O=br(n);let C=(Math.floor(o/pe)+1)*pe,f=null;const c=o+366*24*60*pe;for(;C<=c;){const q=O(C);if(f!==null){const P=O(f)+(C-f);for(let F=P;F<q;F+=pe)if(w(F))return C}f=C;const b=new Date(q);if(!y.has(b.getUTCMonth()+1)||!x(b)){C+=((23-b.getUTCHours())*60+(60-b.getUTCMinutes()))*pe;continue}if(!d.has(b.getUTCHours())){C+=(60-b.getUTCMinutes())*pe;continue}if(!g.has(b.getUTCMinutes())){C+=pe;continue}const S=C-120*pe,j=O(S)-S-(q-C);if(j>0&&O(C-j)===q){C+=pe;continue}return C}return null}function $r(t,n,o){if("cron"in t)return vr(t.cron,t.timezone??"UTC",n);if("at"in t){const i=Date.parse(t.at);return Number.isFinite(i)&&i>n?i:null}if("every_s"in t&&t.every_s>0){const i=t.start_at?Date.parse(t.start_at):o,g=t.every_s*1e3;return Number.isFinite(i)?i>n?i:i+(Math.floor((n-i)/g)+1)*g:null}return null}const un={user:0,think:1400,say:900,tool:1100,ask:1200,approval:1300,final:1600,error:900,learning:700},Ye=t=>new Date(t).toISOString(),he=(t,n)=>t.length>n?`${t.slice(0,n-1)}…`:t;function cn(t,n,o,i,g,d={}){return{id:t,timestamp:Ye(n),created_at:Ye(n),kind:i,summary:g,agent_label:null,tool_name:null,tool_use_id:null,tool_status:null,tool_input_preview:null,tool_result_preview:null,tool_result_size_bytes:null,text:null,seq:o,conversation_id:1,...d}}const pn=(t,n)=>{const o=t[n];if(o.k==="user"||o.k==="learning")return!1;const i=t[n-1];return!i||i.k==="user"||i.k==="tool"||i.k==="ask"||i.k==="approval"},rt=t=>t.filter((n,o)=>pn(t,o)).length;function Ge(t,{start:n,now:o,answers:i=[],stopAt:g}){const d=[],h=g===void 0?o:Math.min(o,g),y=(f,c,q,b,S)=>{d.push(cn(f,c,d.length,q,b,S))};let u=n,D=0,R=0,x=null,w=!1,O=!1,C=0;for(const[f,c]of t.entries()){const q=u+(c.wait??un[c.k]);if(q>h)break;u=q,pn(t,f)&&(R+=1);const b=`1:${f+1}`;if(c.k==="user")y(b,u,"user_message",`You: ${he(c.text,160)}`,{text:c.text});else if(c.k==="think")y(b,u,"thinking",`Thinking: ${he(c.text,80)}`,{text:c.text});else if(c.k==="say")y(b,u,"text_block",he(c.text,160),{text:c.text});else if(c.k==="final"){const S=O&&c.declined?c.declined:c.text;y(b,u,"final_answer",he(S,160),{text:S})}else if(c.k==="error")y(b,u,"error",he(c.text,160),{text:c.text}),w=!0;else if(c.k==="learning")y("learning",u,"learning",c.detail,{agent_label:"learning",text:c.detail,learning:{state:c.state,reason:c.reason,detail:c.detail}});else if(c.k==="tool"){const S=`toolu_demo_${f+1}`;y(`${b}:0`,u,"tool_use",c.label,{tool_name:c.tool,tool_use_id:S,tool_input_preview:c.input??null,round:f+1});const j=u+(c.ms??900);if(j>h)return C=f,{rows:d,pending:null,done:!1,lastAt:u,requests:R,requestsInAll:rt(t),failed:w};u=j,y(`${b}:r`,u,"tool_result",`${c.label}${c.failed?` failed: ${he(c.result,120)}`:": ok"}`,{tool_name:c.tool,tool_use_id:S,tool_status:c.failed?"failed":"success",tool_result_preview:he(c.result,500),tool_result_size_bytes:c.result.length,round:f+1,...c.nodes?{learned_nodes:c.nodes}:{}}),c.saved&&y(`${b}:saved:0`,u,"phase",`Saved ${c.saved}`,{path:c.saved})}else if(c.k==="ask"){const S=`toolu_demo_${f+1}`;y(`${b}:0`,u,"tool_use",`Asked you: ${c.question}`,{tool_name:"ask_person",tool_use_id:S,round:f+1}),y(`${b}:r`,u,"tool_result",`Asked you: ${c.question}: ok`,{tool_name:"ask_person",tool_use_id:S,tool_status:"success",tool_result_preview:`Asked the person: ${c.question}. Waiting for their answer.`,tool_result_size_bytes:c.question.length+46,round:f+1}),y(`${b}:waiting`,u,"waiting",`Waiting for you: ${c.question}`,{text:c.question,round:f+1});const j=i[D++];if(!j||j.at>h){x=g===void 0?{kind:"question",question:c.question,asked_at:Ye(u)}:null,C=f;break}u=j.at,y(`${b}:answer`,u,"user_message",`You: ${he(j.text??"",160)}`,{text:j.text??""})}else{const S=`toolu_demo_${f+1}`,j=JSON.stringify(c.args);y(`${b}:0`,u,"tool_use",c.label,{tool_name:c.tool,tool_use_id:S,tool_input_preview:he(j,500),round:f+1});const P=i[D++],F=!P||P.at>h;if(y(`approval:${S}`,u,"tool_approval_requested",`${F?"Waiting for your approval":"Asked your approval"}: ${c.tool} ${he(j,400)}`,{text:j,tool_name:c.tool,tool_use_id:S,tool_input_preview:he(j,500)}),F){x=g===void 0?{kind:"approval",id:`apr_demo_${f+1}`,tool:c.tool,call_id:S,args_preview:j,summary:c.label,asks_because:c.because,requested_at:Ye(u),...c.price===void 0?{}:{price:c.price}}:null,C=f;break}u=P.at+800;const _=P.decision!=="deny";_||(O=!0),y(`${b}:r`,u,"tool_result",`${c.label}${_?": ok":" refused"}`,{tool_name:c.tool,tool_use_id:S,tool_status:_?"success":"failed",tool_result_preview:_?c.result:c.denied,tool_result_size_bytes:(_?c.result:c.denied).length,round:f+1,..._?{}:{refused:!0}}),y(`approval:${S}:after:outcome`,u,"phase",_?`You allowed ${c.tool}. It ran.`:`You declined ${c.tool}. It did not run.`,{origin:"server",text:_?c.result:c.denied})}C=f+1}return{rows:d,pending:x,done:C===t.length,lastAt:u,requests:R,requestsInAll:rt(t),failed:w}}function xr(t,n=0){let o=0;for(const i of t)o+=(i.wait??un[i.k])+(i.k==="tool"?i.ms??900:i.k==="ask"?n:i.k==="approval"?n+800:0);return o}function At(t,n){const o=Math.max(t,4e-4)*24e4;return{input:Math.round(o*.22),output:Math.round(o*.06),cache_read:Math.round(o*.58),cache_write:Math.round(o*.14),requests:n,unmetered:0}}function Ar(t,n,o,i,g){return cn("1:usage",t,n,"usage",`Cost: $${o.toFixed(4)} over ${i} model request${i===1?"":"s"}`,{usage:{usd:o,requests:i}})}function Tr(t,n,o,i,g){const d=[],h=At(i,g),y=x=>Math.round(x/Math.max(g,1)),u=new Map(n.filter(x=>x.kind==="tool_result").map(x=>[x.tool_use_id,x]));let D=0,R=!1;for(const x of n){if(x.kind==="user_message"||x.kind==="tool_result"){R=!1;continue}if(["thinking","text_block","tool_use","final_answer"].includes(x.kind)&&!R){R=!0,D+=1;const O=Date.parse(x.timestamp);d.push({id:`m:${D}`,kind:"model",parent_id:null,name:o.split("/").pop()??o,agent_label:null,started_at:Ye(O-1200),ended_at:x.timestamp,status:"ok",stop_reason:x.kind==="final_answer"?"stop":"tool_use",tokens:{input:y(h.input),cache_read:y(h.cache_read),cache_write:y(h.cache_write),output:y(h.output)},usd:i/Math.max(g,1),decision:!1,charged:!0,not_metered:!1,tool_use_id:null,input_preview:null,result_preview:null,result_size_bytes:null})}if(x.kind!=="tool_use")continue;const w=u.get(x.tool_use_id);d.push({id:`t:${x.id}`,kind:"tool",parent_id:`m:${D}`,name:x.tool_name??"tool",agent_label:null,started_at:x.timestamp,ended_at:(w==null?void 0:w.timestamp)??null,status:w?w.refused?"refused":w.tool_status==="failed"?"failed":"ok":"running",stop_reason:null,tokens:null,usd:null,decision:!1,charged:!1,not_metered:!0,tool_use_id:x.tool_use_id,input_preview:x.tool_input_preview,result_preview:(w==null?void 0:w.tool_result_preview)??null,result_size_bytes:(w==null?void 0:w.tool_result_size_bytes)??null})}return{run_id:t,model_requests:"priced",spans:d,dropped:0}}function Rr(t,n){const o=t.cost.usd??0,i=t.cost.tokens??At(o,1),[g,d]=n.includes("/")?[n.split("/")[0],n.split("/").slice(1).join("/")]:[null,n];return{run_id:t.run_id,ended_at:t.ended_at,currency:"USD",total:{usd:o},lines:[{meter:"tokens",model:d,provider:g,charged_by:null,quantity:i.input+i.output+i.cache_read+i.cache_write,unit:"token",basis:"estimate",attempt:1,billable:!0,usd:o,requests:i.requests??1,tokens:{input:i.input,output:i.output,cache_read:i.cache_read,cache_write:i.cache_write},unmetered_requests:0}],browser_sessions:[],computer_intervals:[],infra_usd:0,reason:t.ended_at?null:"running"}}const E=t=>new Date(t).toISOString(),Sr=t=>E(t).slice(0,10);function W(t,n=40){let o="";for(let i=0,g=2166136261;o.length<n;i++){for(const d of`${t}:${i}`)g=Math.imul(g^d.charCodeAt(0),16777619);o+=(g>>>0).toString(16).padStart(8,"0")}return o.slice(0,n)}const Dr={kyb:nt().totals.cost_usd??0,jury:xt().totals.cost_usd??0,batch:dn(Me+1).totals.cost_usd??0},gt={kyb:nt().totals.elapsed_ms??0,jury:xt().totals.elapsed_ms??0,batch:Me},we="refund-desk",V="refund-decision",ke=W("refund-decision:champion",64),de="partial-refund-shipping",Kt=3e3;function Bt(t,n,o){return n===o?t:JSON.parse(JSON.stringify(t).split(n).join(o).split(n.toUpperCase()).join(o.toUpperCase()))}function Cr(t,n){const o=n-Date.parse(t.run.startedAt),i=JSON.stringify(t).replace(/"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)"/g,(g,d)=>`"${E(Date.parse(d)+o)}"`);return JSON.parse(i)}function Or(t){const n=JSON.parse(JSON.stringify(t));for(const i of n.decisions)i.id==="dec_kyb_cross"&&(i.answers={...i.answers,dates_consistent:{type:"noul",noul:.96}},i.action={same_entity:!0,same_state:!0,dates_consistent:!0}),i.id==="dec_kyb_route"&&(i.answers={branch:{type:"choice",choice:"approve",probabilities:{approve:.93,review:.06,reject:.01},confidence:.93}},i.action={branch:"approve",taken:"approve"});const o=n.nodes["/root/steps/3/branches/review/body"];return n.nodes["/root/steps/3/branches/approve/body"]={...o},n.nodes["/root/steps/3/branches/review/body"]={status:"not_run"},n.nodes["/root/steps/3"]={...n.nodes["/root/steps/3"],branch:"approve"},n}function fn({opened:t=Date.now(),clock:n=()=>Date.now()}={}){const o=structuredClone(Zn),i=new Map(o.map(e=>[e.id,e])),g=new Map,d=(e,s=t-e.startAgo)=>{const r=i.get(e.agent),a=e.beats?[...e.beats,...r.learning?[{k:"learning",state:e.id==="demo-run-refund-by-agent"?"merged":"dropped",reason:e.id==="demo-run-refund-by-agent"?null:"empty",detail:e.id==="demo-run-refund-by-agent"?"Kept one correction from this run: quote the policy line in the note.":"Nothing new to keep from this run."}]:[]]:null,l=[];for(const m of e.answered??[]){const A=Ge(a??[],{start:s,now:Number.MAX_SAFE_INTEGER,answers:l});if(!A.pending)break;l.push({at:A.lastAt+m.afterMs,...m.text===void 0?{}:{text:m.text},...m.decision?{decision:m.decision}:{}})}const p={story:e,start:s,beats:a,answers:l};return g.set(e.id,p),p};for(const e of[...Mt(t),...pt()])d(e);const h=e=>e.current??e.notes.length,y=(e,s=h(e))=>W(`${e.id}:rev:${s}`,64),u=(e,s)=>(e.pausedAt??s)-(e.pausedMs??0),D=(e,s)=>{const r=e.story.graph;if(!r)return null;const a=i.get(e.story.agent),l=typeof e.story.input.merchant=="string"?e.story.input.merchant:null,p=e.stoppedAt!==void 0&&e.stoppedAt<e.start+gt[r],m=p?e.stoppedAt:u(e,s),A=r==="batch"?dn(Math.max(0,m-e.start)):r==="kyb"?e.story.review?nt():Or(nt()):xt(),M=r==="kyb"&&l?Bt(A,"Corvane Analytics Inc.",l):r==="jury"&&l?Bt(A,"Saltmarsh Outdoor Gear Co.",l):A,N=Cr(M,e.start);return{...N,run:{...N.run,id:e.story.id,agent:a.id,revision:y(a),paused:e.pausedAt!==void 0&&!p&&m<e.start+gt[r],...p?{status:e.cancelled?"cancelled":"stopped",endedAt:E(e.stopAt)}:{}},read_at:E(s)}},R=(e,s=n())=>{var se,le,Fe,qe,Et;if(e.settled)return e.archivedAt?{...e.settled,archived_at:E(e.archivedAt)}:e.settled;const{story:r}=e,a=i.get(r.agent);let l="working",p="working",m=null,A=null,M=r.graph?Dr[r.graph]:r.usd;const N=M;let Y=1,te=null,K=!1;if(e.beats){const B=Ge(e.beats,{start:e.start,now:s,answers:e.answers,stopAt:e.stopAt});Y=Math.max(B.requests,1),K=B.failed||B.done&&!!r.fails,e.stopAt!==void 0&&!B.done?(l=e.cancelled?"cancelled":"completed",p="idle",m=e.stopAt):B.pending?(l="input_required",p="waiting",A=B.pending):B.done&&(l=K?"failed":"completed",p="idle",m=B.lastAt),B.done||(M=N*(B.requests/Math.max(B.requestsInAll,1))),te=((se=B.rows.findLast($e=>$e.kind==="final_answer"))==null?void 0:se.text)??null}else{const B=gt[r.graph];Y=r.graph==="batch"?20:4,e.stoppedAt!==void 0&&e.stoppedAt<e.start+B?(l=e.cancelled?"cancelled":"completed",p="idle",m=e.stopAt,M=N*((e.stoppedAt-e.start)/B)):u(e,s)>=e.start+B?(l="completed",p="idle",m=e.start+B+(e.pausedMs??0)):M=N*Math.max(0,(u(e,s)-e.start)/B)}const J=(e.later??[]).filter(B=>B.kind!=="steer");if(J.length){const B=J.at(-1),$e=Ge(B.beats,{start:B.start,now:s,stopAt:B.stopAt});M+=J.reduce((We,Je)=>We+Je.usd*(Je===B&&!$e.done?$e.requests/Math.max($e.requestsInAll,1):1),0),Y+=J.reduce((We,Je)=>We+rt(Je.beats),0),K=!1,A=null,$e.done?(l="completed",p="idle",m=$e.lastAt):B.stopAt!==void 0?(l=B.cancelled?"cancelled":"completed",p="idle",m=B.stopAt):(l="working",p="working",m=null),te=((le=$e.rows.findLast(We=>We.kind==="final_answer"))==null?void 0:le.text)??te}const ne=m!==null,k=!!a.learning&&ne&&l==="completed",I=r.id==="demo-run-refund-by-agent",$=k&&((Fe=e.grade)==null?void 0:Fe.feedback)==="correction"?Date.parse(e.grade.graded_at):null,Q=$!==null&&s<$+Kt,z=e.gradeLabel?`Kept a correction from your grade: ${e.gradeLabel}`:"Kept a correction from your grade.",oe={run_id:r.id,agent_id:a.id,agent_version:h(a),revision:y(a),kind:a.kind,sha:null,status:l,state:p,title:r.title,...r.effort?{effort:r.effort}:{},input:r.input,file_ids:((qe=e.files)==null?void 0:qe.map(B=>B.id))??[],place:{mode:"runner"},claim:null,created_at:E(e.start),updated_at:E(m??Math.min(s,e.start+60*re)),ended_at:ne?E(m):null,result:l==="completed"?{output:r.output??null,final_answer:te}:null,error:l==="failed"&&r.fails&&!J.length?{code:r.fails.code,message:r.fails.message,retryable:!1}:null,review:ne&&l==="completed"&&r.review?{...r.review,at:E(m)}:null,pending:A,cost:{usd:Number(M.toFixed(6)),basis:"estimate",charge_state:null,cap_usd:e.cap??a.maxCostUsd??null,tokens:At(M,Y),tools_usd:0,learning_usd:k?I?.0312:.0021:0,all_in_usd:Number((M+(k?I?.0312:.0021:0)).toFixed(6))},stopped_for:((Et=r.fails)==null?void 0:Et.code)==="spend_cap_reached"&&l==="failed"&&!J.length?"budget":null,budget_refused_calls:0,audit_of:null,path:r.path??(a.kind==="agentic"?"agent":null),workflow:r.path&&r.path!=="agent"?{name:V,digest:ke,repick:null}:null,approvals:"ask",archived_at:e.archivedAt?E(e.archivedAt):null,imported_from:null,trigger:r.trigger?{id:r.trigger,firing_key:`${r.trigger}:${r.id}`}:null,labels:{},learning:$!==null?Q?{state:"reflecting",reason:null,detail:"Reading your grade into its corrections.",at:E($)}:{state:"merged",reason:null,detail:z,at:E($+Kt)}:k?{state:I?"merged":"dropped",reason:I?null:"empty",detail:I?"Kept one correction from this run: quote the policy line in the note.":"Nothing new to keep from this run.",at:E(m+4e3)}:null,recordings:[],poll_after_ms:ne?0:1e3,last_progress_at:ne?null:E(Math.min(s,e.start+60*re))};return ne&&!Q&&(e.settled={...oe,archived_at:null}),oe},x=()=>[...g.values()],w=(e=n())=>x().filter(s=>s.start<=e).sort((s,r)=>r.start-s.start),O=(e,s=n())=>{if(!e.beats)return[];const r=Ge(e.beats,{start:e.start,now:s,answers:e.answers,stopAt:e.stopAt}),a=[...r.rows];let l=r.requests;for(const[m,A]of(e.later??[]).entries()){const M=Ge(A.beats,{start:A.start,now:s,stopAt:A.stopAt});l+=M.requests,a.push(...M.rows.map(N=>({...N,id:`${m+2}:${N.id}`,conversation_id:m+2})))}a.sort((m,A)=>Date.parse(m.timestamp)-Date.parse(A.timestamp));const p=R(e,s);return p.ended_at&&l&&a.push(Ar(Date.parse(p.ended_at),a.length,p.cost.usd??0,l)),a.map((m,A)=>({...m,seq:A}))},C={read:"Read files in the run's folder",write:"Write files in the run's folder",web_fetch:"Read a public web page",web_search:"Search the web",email_send:"Send an email",email_draft:"Save an email draft",ask_person:"Lets the agent stop and ask you a question",bash:"Run shell commands in the sandbox"},f=e=>e.native?{runtime:e.native.runtime,project:e.native.project,selector:e.native.selector,machine_id:"mch_demo_laptop",version:e.native.version,model:e.model,fingerprint:W(`${e.id}:setup`,64),configuration:[{path:e.native.runtime==="codex"?"AGENTS.md":"CLAUDE.md",sha256:W(`${e.id}:config`,64)}],skills:e.native.skills,mcp_servers:e.native.mcp,state:"ready",issues:[],capabilities:{launch:!0,learning:!1,workflows:!1,approval:"native",usage:!0},connected:!e.native.disconnected,verified_at:E(e.native.verifiedAt??t-2*ie)}:void 0,c=(e,s=h(e))=>{if(e.saved)return{...e.saved[s-1],id:e.id,version:s,name:e.name};const r=f(e);return{id:e.id,version:s,name:e.name,description:e.description,...e.kind==="workflow"?{workflow:e.workflow}:{instructions:e.instructions,...e.learning?{learning:!0}:{},approvals:"ask",model:e.model},harness:e.harness,...e.maxCostUsd&&s===e.notes.length?{max_cost_usd:e.maxCostUsd}:{},skills:[],tools:e.tools,...r?{native:r}:{}}},q=(e,s=n())=>{const r=x().filter(l=>l.story.agent===e.id&&l.start<=s),a=t-e.madeDaysAgo*U;return{agent_id:e.id,definition:c(e),kind:e.kind,mcp_pin:null,revision:y(e),revisions:e.notes.length,source:null,template:null,skills:[],sign_ins:[],runs:{count:r.length,live:r.filter(l=>!R(l,s).ended_at).length},own_computer:null,region:"local",home_etag:`"${y(e)}"`,archived_at:e.archivedAt?E(e.archivedAt):null,...e.learning?{learning:{pending:e.id===we&&!Z?1:0}}:{},...e.native?{native_status:f(e)}:{},created_at:E(a),updated_at:E(a+(e.notes.length-1)*6*U),tools:e.tools.map(l=>{const p=l==="email_send";return{name:l,blurb:C[l]??l,permission:p?"ask":"allow",permission_from:"default",default_permission:p?"ask":"allow",permissions:["allow","ask","deny"]}}),run_blockers:null}},b=e=>{const s=t-e.madeDaysAgo*U;return e.notes.map((r,a)=>({revision:y(e,a+1),version:a+1,parent:a?y(e,a):null,kind:e.kind,current:a+1===h(e),note:r,created_at:E(s+a*6*U),definition:c(e,a+1)})).reverse()},S=({from:e,agent:s,now:r=n()})=>{const a=w(r).filter(k=>!k.archivedAt).map(k=>({h:k,run:R(k,r)})),l=a.filter(({h:k})=>(!s||k.story.agent===s)&&(e===void 0||k.start>=e)),p=()=>({runs:0,completed:0,needs_review:0,failed:0,runs_with_metrics:0,runs_with_token_metrics:0,tokens:0,cost_usd:0,unknown_cost_runs:0}),m={...p(),input:0,cache_read:0,cache_write:0,output:0,requests:0,unmetered:0},A={day:new Map,harness:new Map,tools:new Map};let M=0,N=0,Y=0,te=0;const K=(k,I,$)=>{k.runs+=1,I.status==="completed"&&(k.completed+=1),I.status==="failed"&&(k.failed+=1),I.review&&(k.needs_review+=1),k.runs_with_metrics+=1,k.runs_with_token_metrics+=1,k.tokens+=$,k.cost_usd+=I.cost.usd??0};for(const{h:k,run:I}of l){const $=I.cost.tokens,Q=$.input+$.output+$.cache_read+$.cache_write;K(m,I,Q),m.input+=$.input,m.output+=$.output,m.cache_read+=$.cache_read,m.cache_write+=$.cache_write,m.requests+=$.requests??0;const z=Sr(k.start);A.day.has(z)||A.day.set(z,{...p(),day:z}),K(A.day.get(z),I,Q);const se=`${i.get(k.story.agent).harness}\0${k.story.effort??""}`;A.harness.has(se)||A.harness.set(se,p()),K(A.harness.get(se),I,Q),I.ended_at?(N+=1,M+=Date.parse(I.ended_at)-k.start):(Y+=1,te+=r-k.start);for(const le of k.beats??[]){if(le.k!=="tool"&&le.k!=="approval"&&le.k!=="ask")continue;const Fe=le.k==="ask"?"ask_person":le.tool,qe=A.tools.get(Fe)??{calls:0,errors:0};qe.calls+=1,le.k==="tool"&&le.failed&&(qe.errors+=1),A.tools.set(Fe,qe)}}const J=k=>({...k,cost_usd:Number(k.cost_usd.toFixed(4))}),ne=[...A.day.values()].sort((k,I)=>k.day.localeCompare(I.day)).map(J);return{agents:o.length,runs:{total:a.length,active:a.filter(k=>!k.run.ended_at&&k.run.status!=="input_required").length,needs_input:a.filter(k=>k.run.status==="input_required").length,failed:a.filter(k=>k.run.status==="failed").length,needs_review:a.filter(k=>k.run.review).length,status_unknown:0},per_agent:[...i.values()].filter(k=>o.includes(k)||a.some(I=>I.run.agent_id===k.id)).map(k=>({agent_id:k.id,name:k.name,runs:a.filter(I=>I.run.agent_id===k.id).length})),cost:{usd:Number(a.reduce((k,I)=>k+(I.run.cost.usd??0),0).toFixed(4)),basis:"estimate",unknown_runs:0},archived:{agents:0,runs:x().filter(k=>k.archivedAt).length},analytics:{filter:{from:e===void 0?null:E(e),to:null,agent:s??null},totals:J(m),time:{ended_runs:N,wall_ms:M,active_runs:Y,active_ms:te},by_harness_effort:[...A.harness.entries()].map(([k,I])=>({...J(I),harness:k.split("\0")[0],effort:k.split("\0")[1]||null})),by_day:ne,by_source:[{...J({...m}),source:"live"}].map(({input:k,cache_read:I,cache_write:$,output:Q,requests:z,unmetered:oe,...se})=>se),tools:[...A.tools.entries()].map(([k,I])=>({tool:k,label:C[k]??(k==="learned_workflow"?"Run a learned workflow":k),...I})).sort((k,I)=>I.calls-k.calls),usage:{tokens:m.tokens,input:m.input,output:m.output,cache_read:m.cache_read,cache_write:m.cache_write,known_runs:m.runs,unknown_runs:0,observed_sessions:0,unknown_sessions:0,partial_days:0,retention_limited:!1,by_day:ne.map(k=>({day:k.day,tokens:k.tokens})),by_harness:[...new Set(o.map(k=>k.harness))].map(k=>({harness:k,tokens:[...A.harness.entries()].filter(([I])=>I.startsWith(`${k}\0`)).reduce((I,[,$])=>I+$.tokens,0)})).filter(k=>k.tokens>0)}}}},j=(e,s)=>{const r=new Date(e);return`${r.getUTCMinutes()} ${r.getUTCHours()} * * ${s}`},P=t-47*re;let F=t+9*ie;for(;![1,2,3,4,5].includes(new Date(F).getUTCDay());)F+=U;const _=[{id:"trg-demo-helpdesk-tickets",name:"New support ticket",agent:"support-triage",source:{kind:"webhook",signature:"standard"},input:{content:"${body.subject}\n\n${body.text}"},madeDaysAgo:57},{id:"trg-demo-helpdesk-refunds",name:"Refund request filed",agent:"refund-desk",source:{kind:"webhook",signature:"standard",accept:[{event:"refund.requested"}]},input:{content:"Refund request ${body.id}: ${body.buyer} asks for $${body.amount} back on order ${body.order}."},madeDaysAgo:40},{id:"trg-demo-weekly-brief",name:"Weekly risk brief",agent:"weekly-risk-brief",source:{kind:"schedule",cron:j(P,String(new Date(P).getUTCDay())),timezone:"UTC"},input:{content:"Write this week's risk brief."},madeDaysAgo:36,nextIn:7*U-47*re},{id:"trg-demo-weekday-certificates",name:"Certificates, every weekday",agent:"certificate-review",source:{kind:"schedule",cron:j(F,"1-5"),timezone:"UTC"},input:{documents:"${inbox.certificates}"},madeDaysAgo:27,nextIn:F-t},{id:"trg-demo-pull-requests",name:"Pull request opened",agent:"pr-reviewer",source:{kind:"webhook",signature:"github",accept:[{event:"pull_request",actions:["opened","synchronize"]}]},input:{content:"Review pull request #${body.number}: ${body.pull_request.title}"},madeDaysAgo:22}],v=new Map(_.map(e=>[e.id,!0])),G=(e,s=n())=>{const r=_.find(p=>p.id===e),a=(r==null?void 0:r.source.kind)==="schedule"?"schedule":"webhook";return w(s).filter(p=>p.story.trigger===e).slice(0,25).map(p=>({key:`${e}:${p.story.id}`,by:p.story.id.startsWith("demo-run-now-")?"manual":a,nominal_at:E(p.start),status:"started",at:E(p.start),run_id:p.story.id,reason:null,error:null}))},H=(e,s)=>e.source.kind!=="schedule"?null:(e.nextAt===void 0&&e.nextIn!==void 0&&(e.nextAt=t+e.nextIn),(e.nextAt===void 0||e.nextAt!==null&&e.nextAt<=s)&&(e.nextAt=$r(e.source,s,t-e.madeDaysAgo*U)),e.nextAt),L=(e,s=n())=>{var p;const r=G(e.id,s),a=t-e.madeDaysAgo*U,l=H(e,s);return{id:e.id,name:e.name,enabled:v.get(e.id)??!0,source:e.source,target:e.target??{kind:"start_run",agent_id:e.agent,input:e.input},catchup_window_s:e.catchup??3600,max_active_runs:e.maxActive??null,failures_in_a_row:0,disabled:null,next_at:l!==null&&(v.get(e.id)??!0)?E(l):null,last_run_id:((p=r[0])==null?void 0:p.run_id)??null,created_at:E(a),updated_at:E(a),last_firing:r[0]??null,...e.source.kind==="webhook"?{hook_url:`https://agentrun.larkspur.example/v2/hooks/${e.id}`,secret:{name:`trigger:${e.id}`,set:!0,source:"saved",changed_at:E(e.secretAt??a)}}:{}}};let Z=!1;const ue=new Map,be=e=>{var s,r;return ue.get(e)??(e===we?Lt:((r=(s=i.get(e))==null?void 0:s.learned)==null?void 0:r.corrections)??"")},ve=new Map,Pe=(e,s)=>{const r=ve.get(`${e}/${s.name}`);return r?{...s,status:r,etag:`"${W(`${e}:${s.name}:${r}`,16)}"`}:s},Le=(e=n())=>x().filter(s=>s.story.agent==="refund-desk"&&s.start<=e).sort((s,r)=>s.start-r.start),fe=t-tn*U,ot=(e,s=n())=>{var Y,te,K,J,ne,k,I;const r=i.get(e),a={location:"server",ready:!0,model:ae.default,needs:null,reason:null};if(!r.learning)return{agent:e,main:null,corrections:"",workflows:[],log:{items:[],total:0,next_cursor:null},counts:{merged:0,dropped:{},in_progress:0},impact:null,learning_model:a};if(e!==we){const $=x().filter(se=>se.story.agent===e&&se.start<=s),Q=(be(e).match(/^- /gm)??[]).length,z=(Y=r.learned)==null?void 0:Y.checking,oe=z?[{by:{run:((te=$.at(-1))==null?void 0:te.story.id)??""},commit:W(`${e}:learn:1`),at:E(t-3*U),reason:`Drafted ${z.name}`,files:[`workflows/${z.name}/workflow.json`]}]:[];return{agent:e,main:r.learned?W(`${e}:learn:1`):null,corrections:be(e),workflows:(z?[{name:z.name,file:`workflows/${z.name}/workflow.json`,readme:`workflows/${z.name}/README.md`,description:z.description,status:"checking",run:((K=$.at(-1))==null?void 0:K.story.id)??null,bytes:JSON.stringify(z.workflow,null,2).length,etag:`"${W(`${e}:etag`,16)}"`,last_change:{kind:"approved",by:"person",at:E(t-3*U)}}]:[]).map(se=>Pe(e,se)),log:{items:oe,total:oe.length,next_cursor:null},counts:{merged:Q,dropped:{empty:Math.max($.length-Q,0)},in_progress:z?1:0},impact:null,learning_model:a}}const l=Le(s),p=((J=l.find($=>$.start>=fe))==null?void 0:J.story.id)??null,m=[{by:{run:((ne=l.at(-9))==null?void 0:ne.story.id)??""},commit:W("learn:5"),at:E(t-2*U),reason:`Drafted ${de}: refunds that keep back the original shipping`,files:[`workflows/${de}/workflow.json`,`workflows/${de}/README.md`]},{by:{user:!0},commit:W("learn:4"),at:E(t-9*U),reason:"Edited corrections.md",files:["corrections.md"]},{by:{run:p??""},commit:W("learn:3"),at:E(fe),reason:`Promoted ${V}: it agreed with the agent on all 22 past runs it answered alone`,files:[`workflows/${V}/workflow.json`]},{by:{run:"demo-run-refund-by-agent"},commit:W("learn:2"),at:E(t-19*U),reason:"Kept a correction: quote the policy line in the note",files:["corrections.md"]},{by:{run:((k=l[3])==null?void 0:k.story.id)??""},commit:W("learn:1"),at:E(t-29*U),reason:`Drafted ${V}`,files:[`workflows/${V}/workflow.json`,`workflows/${V}/README.md`]}],A=l.filter($=>$.start<fe),M=l.filter($=>$.start>=fe),N=$=>{const Q=$.map(z=>xr(z.beats??[])/1e3).sort((z,oe)=>z-oe);return Q.length?Math.round(Q[Math.floor(Q.length/2)]):0};return{agent:e,main:W("learn:5"),corrections:be(e),workflows:[{name:V,file:`workflows/${V}/workflow.json`,readme:`workflows/${V}/README.md`,description:"Decides a refund request: policy line, refund amount, note and email draft.",status:"serving",run:p,bytes:JSON.stringify(Qe).length,etag:`"${W("etag:serving",16)}"`,last_change:{kind:"approved",by:"person",at:E(fe)}},{name:de,file:`workflows/${de}/workflow.json`,readme:`workflows/${de}/README.md`,description:"Works out a changed-mind refund less the original shipping.",status:Z?"checking":"pending",run:((I=l.at(-9))==null?void 0:I.story.id)??null,bytes:1412,etag:`"${W(`etag:pending:${Z}`,16)}"`,last_change:Z?{kind:"approved",by:"person",at:E(s)}:{kind:"learned",by:"run",at:E(t-2*U)}}].map($=>Pe(e,$)),log:{items:m,total:m.length,next_cursor:null},counts:{merged:5,dropped:{empty:Math.max(l.length-9,0),checker:4},in_progress:0},impact:A.length&&M.length?{before:{runs:A.length,median_duration_s:N(A)},after:{runs:M.length,median_duration_s:N(M)}}:null,learning_model:a}},gn=(e,s,r)=>{var p;const a=ot(e).workflows.find(m=>m.readme===s);if(!a)return!1;const l=`${e}/${a.name}`;if(r==="approve")return a.status!=="pending"?!1:(e===we&&a.name===de?(Z=!0,ve.delete(l)):ve.set(l,"checking"),!0);if(r==="retire")return a.status==="retired"?!1:(Tt.set(l,a.status),ve.set(l,"retired"),!0);if(r==="restore"){if(a.status!=="retired")return!1;ve.delete(l);const m=Tt.get(l);return m&&m!==((p=ot(e).workflows.find(A=>A.readme===s))==null?void 0:p.status)&&ve.set(l,m),!0}return!1},Tt=new Map,ze=e=>e.length?Number((e.reduce((s,r)=>s+r,0)/e.length).toFixed(4)):0,hn=(e,s=n())=>{var I;const r={agent:e,runs:[],total_runs:0,unknown_cost_runs:0,unknown_path_runs:0,workflows:[],summary:{takeover:null,before:null,after:null,after_state:"no_served_runs",times_cheaper:null,hand_backs:null,withheld:null,replay:null},bill:{learning_usd:0,points:[],break_even:null,gap_usd:null,withheld:0,booked_usd:0,revisions:[],unattributed_usd:null,holds:[]}};if(e!==we)return r;const l=Le(s).map($=>({h:$,run:R($,s)})).filter($=>$.run.status==="completed").map(({h:$,run:Q},z)=>{const oe=$.story.path??"agent",se=Q.cost.usd??0,le=Q.cost.learning_usd??0;return{n:z+1,run_id:Q.run_id,started_at:Q.created_at,path:oe,workflow:oe==="agent"?null:V,digest:oe==="agent"?null:ke,took_over:oe==="workflow",audited:!1,cost_usd:se,cost_upper_bound:!1,learning_usd:le,total_usd:Number((se+le).toFixed(6))}}),p=l.find($=>$.path==="workflow")??null,m=l.filter($=>!p||$.n<p.n),A=l.filter($=>$.path==="workflow"),M=l.filter($=>p&&$.n>=p.n&&$.path!=="workflow"),N=ze(m.map($=>$.cost_usd)),Y=ze(l.filter($=>p&&$.n>=p.n).map($=>$.cost_usd)),te=Number(l.reduce(($,Q)=>$+Q.learning_usd,0).toFixed(4));let K=0,J=0,ne=null;const k=l.map($=>(K+=$.total_usd,J+=$.path==="agent"?$.cost_usd:N,!ne&&p&&$.n>p.n&&K<J&&(ne={n:$.n,run_id:$.run_id}),{n:$.n,run_id:$.run_id,actual_usd:Number(K.toFixed(4)),agent_usd:Number(J.toFixed(4))}));return{agent:e,runs:l,total_runs:l.length,unknown_cost_runs:0,unknown_path_runs:0,workflows:p?[{workflow:V,digest:ke,state:"serving",served:{runs:A.length,mean_usd:ze(A.map($=>$.cost_usd))},by_hand:M.length?{runs:M.length,mean_usd:ze(M.map($=>$.cost_usd))}:null,unknown_cost_runs:0}]:[],summary:{takeover:p?{n:p.n,run_id:p.run_id}:null,before:m.length?{runs:m.length,mean_usd:N}:null,after:p?{runs:l.length-m.length,mean_usd:Y}:null,after_state:p?"priced":"no_served_runs",times_cheaper:p&&Y?Number((N/Y).toFixed(1)):null,hand_backs:p?{ran:A.length+M.length,back:M.length,cut:0}:null,withheld:null,replay:p?{n:24,workflow_pct:100,agent_pct:100,cleared:!0,agreed:22,alone:22,agree_min:.95}:null},bill:{learning_usd:te,points:k,break_even:ne,gap_usd:k.length?Number((k.at(-1).agent_usd-k.at(-1).actual_usd).toFixed(4)):null,withheld:0,booked_usd:((I=k.at(-1))==null?void 0:I.actual_usd)??0,revisions:p?[{workflow:V,digest:ke,compile_usd:.184,check_usd:.412,spend_usd:.596,k:24,served:A.length,attributed_usd:.596,unattributed_usd:0,state:"serving"}]:[],unattributed_usd:0,holds:[]}}},it={compile_after:20,agree_min:.95,alone_min:.8,attempt:1,n:24,agreed:22,alone:22,cost_usd:.412,outcomes:{answered:22,handed_back:2,failed:0,skipped_write:0}},mn=e=>{if(e!==we)return{agent:e,promotions:[],serving:[]};const s=Qe.root.steps.map((r,a)=>({path:`/root/steps/${a}`,kind:r.node,label:r.label,tier:r.node==="pick"||r.node==="extract"?"fast":null,checks:[]}));return{agent:e,promotions:[{workflow:V,digest:W("refund-decision:draft-1",64),at:E(t-22*U),decided:"hold",reason:"It answered 19 of 24 past runs alone and agreed with the agent on 16 of them; 95% is needed.",check:{...it,agreed:16,alone:19,outcomes:{answered:19,handed_back:2,failed:3,skipped_write:0}}},{workflow:V,digest:ke,at:E(fe),decided:"promote",reason:"It answered 22 of 24 past runs alone, and agreed with the agent on all 22.",check:it,commit:W("learn:3")}],serving:[{workflow:V,digest:ke,replaying:null,state:"serving",check:{n:24,agreed:22,alone:22,attempt:1},audit:{window:20,disagree:3,rows:14,disagreed:0},audits_off:null,not_auditable:0,champion:{digest:ke,commit:W("learn:3"),nodes:s,check:it}}]}},yn=(e,s=n())=>{var a,l,p;if(e!==we)return{agent:e,completed_runs:0,compiles:[]};const r=Le(s);return{agent:e,completed_runs:r.filter(m=>R(m,s).status==="completed").length,compiles:[{run_id:((a=r.at(-9))==null?void 0:a.story.id)??"",round:3,at:E(t-2*U),workflow:de,attempts:[{ok:!0,errors:[]}],digest:W(`${de}:draft`,64),promoted:null,draft_errors:[],withheld:!1},{run_id:((l=r.find(m=>m.start>=fe-U))==null?void 0:l.story.id)??"",round:2,at:E(fe-2*ie),workflow:V,attempts:[{ok:!1,errors:["/root/steps/3: the code node reads `line.refund`, which no earlier node writes"]},{ok:!0,errors:[]}],digest:ke,promoted:!0,draft_errors:[],withheld:!1},{run_id:((p=r[3])==null?void 0:p.story.id)??"",round:1,at:E(t-22*U),workflow:V,attempts:[{ok:!0,errors:[]}],digest:W("refund-decision:draft-1",64),promoted:!1,draft_errors:[],withheld:!1}]}},wn=(e,s=n())=>{if(e!==we)return{agent:e,audits:[]};const r=Le(s).filter(a=>a.story.path==="workflow"&&R(a,s).status==="completed");return{agent:e,audits:r.filter((a,l)=>l%5===2).slice(-14).map(a=>({run:a.story.id,shadow_run:null,workflow:V,digest:ke,promoted_at:E(fe),source:"shadow",agreed:!0,served_cost:Number(a.story.usd.toFixed(4)),shadow_cost:.19,at:E(a.start+3*re)}))}},kn=e=>{var a,l;const s=JSON.stringify(Qe,null,2);if(e!==V)return{name:e,revisions:[],total:0,truncated:!1};const r=Le();return{name:e,total:2,truncated:!1,revisions:[{commit:W("learn:1"),at:E(t-29*U),by:{run:((a=r[3])==null?void 0:a.story.id)??""},reason:`Drafted ${V}`,text:s.replace('"work out the refund"','"work out the refund (draft)"'),digest:W("refund-decision:draft-1",64)},{commit:W("learn:3"),at:E(fe),by:{run:((l=r.find(p=>p.start>=fe-U))==null?void 0:l.story.id)??""},reason:"Wrote the refund in code, from the picked line",text:s,digest:ke}]}},_n=(e,s)=>{var p,m;if(s==="corrections.md"&&(e===we||(p=i.get(e))!=null&&p.learned))return be(e);if(e===we)return bn[s]??null;const r=(m=i.get(e))==null?void 0:m.learned;if(!r)return null;const a=r.checking;return{...a?{[`workflows/${a.name}/README.md`]:a.readme,[`workflows/${a.name}/workflow.json`]:JSON.stringify(a.workflow,null,2)}:{}}[s]??null},bn={"corrections.md":Lt,[`workflows/${V}/README.md`]:ur,[`workflows/${V}/workflow.json`]:JSON.stringify(Qe,null,2),[`workflows/${de}/README.md`]:`# ${de}
155
-
156
- Works out a changed-mind refund: the amount paid less the original shipping, once the carrier has scanned the return.
157
-
158
- Drafted from 11 runs where the agent did this by hand. It waits for your OK before it is checked against past runs.
159
- `,[`workflows/${de}/workflow.json`]:JSON.stringify({v:2,name:de,root:{node:"chain",steps:[{node:"call",label:"look the order up",tool:"web_fetch",as:"order"},{node:"code",label:"paid less original shipping",as:"refund"}]}},null,2)},vn=(e,s=n())=>{const r=R(e,s);if(!r.learning)return null;const a=r.learning.state==="merged",l=e.grade?{...e.grade,feedback_status:e.grade.feedback?r.learning.state==="reflecting"?"running":"ended":null}:void 0;return{...l?{graded:l}:{},run:r.run_id,state:r.learning.state,reason:r.learning.reason,detail:r.learning.detail,at:r.learning.at,seed:W("learn:1"),merged:a?W("learn:2"):null,workflows:[],corrections:a?1:0,problems:[],compiled:null,draft_errors:[],used:{workflows:e.story.path&&e.story.path!=="agent"?[{name:V,calls:1,failed:0}]:[]}}},Rt="inputs/message.md",$n=(e,s=n())=>{const r=typeof e.story.input.content=="string"?e.story.input.content:null,a=new Set(O(e,s).map(m=>m.path).filter(m=>!!m)),l=Object.fromEntries(Object.entries(e.story.files??{}).filter(([m])=>a.has(m))),p=Object.fromEntries((e.files??[]).map(m=>[`inputs/${m.path}`,m.text]));return{...r?{[Rt]:r}:{},...p,...l}},xn=e=>{const s=new Set([Rt.slice(7)]),r=(a,l)=>{if(l===1)return a;const p=a.lastIndexOf(".");return p>0?`${a.slice(0,p)}-${l}${a.slice(p)}`:`${a}-${l}`};return e.map(a=>{let l=1;for(;s.has(r(a.path,l));)l++;return s.add(r(a.path,l)),{...a,path:r(a.path,l)}})};let An=0;const St=(e,s,r="person",a,l=[])=>{var te;const p=i.get(e);if(!p)return null;const m=typeof s.content=="string"&&s.content.trim()?s.content.trim():null,A=pt().find(K=>K.agent===e&&K.beats)??Mt(t).findLast(K=>K.agent===e&&K.beats)??pt().find(K=>K.agent===e)??{id:"",agent:e,title:p.name,startAgo:0,input:{},beats:Tn(m),usd:.004},M=(te=A.beats)==null?void 0:te.map((K,J)=>J===0&&K.k==="user"?{...K,wait:0,text:m??K.text}:K),N={...A,id:`demo-run-now-${++An}`,title:m?m.split(`
160
- `)[0].slice(0,80):A.title,startAgo:0,input:Object.keys(s).length?s:A.input,...M?{beats:M}:{},answered:[],hero:void 0,trigger:r==="trigger"?a:void 0},Y=d(N,n());return l.length&&(Y.files=xn(l)),R(Y)},lt=e=>{const s=typeof e.name=="string"&&e.name.trim()?e.name.trim():"New agent",r=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"agent";let a=r;for(let p=2;i.has(a);p++)a=`${r}-${p}`;const l={id:a,name:s,description:typeof e.description=="string"?e.description:"",kind:e.workflow?"workflow":"agentic",harness:typeof e.harness=="string"?e.harness:"pi",model:typeof e.model=="string"?e.model:ae.default,tools:Array.isArray(e.tools)?e.tools:[],learning:!!e.learning,madeDaysAgo:(t-n())/U,notes:[null],saved:[{skills:[],tools:[],...e}]};return o.push(l),i.set(a,l),q(l)},Dt=(e,s,r)=>{const a=i.get(e);return a?(a.saved??(a.saved=a.notes.map((l,p)=>c(a,p+1))),a.saved.push({...a.saved[h(a)-1],...s}),a.notes=[...a.notes,r],a.current=void 0,typeof s.description=="string"&&(a.description=s.description),typeof s.model=="string"&&(a.model=s.model),typeof s.harness=="string"&&(a.harness=s.harness),a.learning=!!a.saved.at(-1).learning,q(a)):null},Tn=e=>[{k:"user",text:e??"Run the agent."},{k:"think",text:"Demo mode calls no model, so this run is a stand-in for what the agent would do."},{k:"final",text:"This is a sample answer. Demo mode calls no model and starts nothing on your server. Turn demo mode off in Settings → Demo to run this agent for real."}],dt={id:"suggestion-scanner",name:"Suggestion scanner",description:"Reads a connected repository for work an agent could take, and suggests an agent for each.",kind:"agentic",harness:"pi",model:ae.default,tools:["read","bash"],instructions:"Read the repository for work people do by hand that an agent could take, and suggest an agent for each, with the lines that show it.",madeDaysAgo:30,notes:[null]};i.set(dt.id,dt);let Rn=0;const Sn=({repo:e,commit:s,start:r,ms:a,found:l})=>{const p=Math.round(a/5),m=`Scan ${e} at ${s.slice(0,7)} for work an agent could take.`,A=[{k:"user",text:m,wait:0},{k:"think",text:"Looking for work people do by hand: TODOs that say so, review queues, tickets answered by looking something up.",wait:p},{k:"tool",tool:"bash",label:'Ran rg -n "by hand|seller sees nothing|TODO" --type ts',input:'rg -n "by hand|seller sees nothing|TODO" --type ts',result:l.map(N=>`${N.path}:${N.line}: ${N.quote}`).join(`
161
- `),wait:p,ms:Math.round(p/2)},...l.map(N=>({k:"tool",tool:"read",label:`Read ${N.path}`,input:N.path,result:`${N.line}: ${N.quote}`,wait:Math.round(p/(2*l.length)),ms:Math.round(p/(2*l.length))})),{k:"final",text:`Found ${l.length} suggestions in ${e}:
162
- ${l.map(N=>`- ${N.title} (${N.path}:${N.line})`).join(`
163
- `)}`,wait:p}],M=`demo-run-scan-${++Rn}`;return d({id:M,agent:dt.id,title:`Scan ${e}`,startAgo:0,input:{content:m},beats:A,usd:.0412},r),{run_id:M}},ut=(e,s)=>{(e.later??(e.later=[])).push({...s,start:n()}),delete e.settled},Dn=(e,s)=>{var p,m,A;const r=g.get(e);if(!r)return null;const a=R(r);if(((p=a.pending)==null?void 0:p.kind)==="question")return ct(e,{text:s}),"answer";if(((m=a.pending)==null?void 0:m.kind)==="approval"&&ct(e,{decision:"deny"}),!a.ended_at)return ut(r,{kind:"steer",beats:[{k:"user",text:s,wait:0}],usd:0}),"steer";const l=(A=a.result)==null?void 0:A.final_answer;return ut(r,{kind:"follow_up",usd:.0062,beats:[{k:"user",text:s,wait:0},{k:"think",text:"Reading the follow-up against what this run found and answered."},{k:"final",text:l?`On your follow-up: what this run found still holds, so its answer stands. ${l}`:"On your follow-up: nothing this run found changes, so there is nothing more to do."}]}),"follow_up"},Cn=(e,s)=>{var m,A;const r=g.get(e);if(!r)return null;const a=R(r),l=!!a.learning,p=s.correct?"":(s.label??"").trim();return r.grade={run_id:e,correct:s.correct,source:s.source??"feedback",graded_at:E(n()),path:a.path==="handed_back"||a.path==="workflow"?a.path:"agent",workflow:((m=a.workflow)==null?void 0:m.name)??null,workflow_digest:((A=a.workflow)==null?void 0:A.digest)??null,feedback:!s.correct&&l?"correction":null,...s.expected?{expected:s.expected}:{}},r.gradeLabel=p||void 0,!s.correct&&l&&p&&ue.set(r.story.agent,`${be(r.story.agent).trimEnd()}
164
- - ${p}
165
- `),delete r.settled,r.grade},On=(e,s)=>{const r=g.get(e);if(!r)return null;r.cap=s;const l=R(r).stopped_for==="budget";l&&ut(r,{kind:"resume",usd:.38,beats:[{k:"say",text:`The spend cap is now $${s.toFixed(2)}. Picking up where the run stopped.`,wait:300},{k:"tool",tool:"bash",label:"Ran git diff origin/main...pr-2210 -- payouts/ api/",input:"git diff origin/main...pr-2210 -- payouts/ api/",result:`diff --git a/payouts/cutoff.ts b/payouts/cutoff.ts
166
- …`,ms:1400},{k:"final",text:r.story.afterCap??"Finished with the higher cap."}]}),delete r.settled;const p=R(r);return{run_id:e,max_cost_usd:s,resumed:l,status:p.status,state:p.state}},jn=(e,s)=>{const r=g.get(e);return!r||!r.story.graph?null:(s&&r.pausedAt===void 0&&!R(r).ended_at&&(r.pausedAt=n()),!s&&r.pausedAt!==void 0&&(r.pausedMs=(r.pausedMs??0)+n()-r.pausedAt,delete r.pausedAt),{run_id:e,paused:r.pausedAt!==void 0,status:R(r).status})},En=(e,s)=>{const r=i.get(e);return r?(r.archivedAt=s?n():void 0,q(r)):null},qn=(e,s)=>{const r=i.get(e),a=r?r.notes.findIndex((l,p)=>y(r,p+1)===s)+1:0;return!r||!a?null:(r.current=a===r.notes.length?void 0:a,q(r))},In=(e,s)=>{var r;return(r=i.get(e))!=null&&r.learning?(ue.set(e,s),s):null},Nn=e=>{const s=`trg-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"trigger"}`;let r=s;for(let a=2;_.some(l=>l.id===r);a++)r=`${s}-${a}`;return r},Ct=e=>`whsec_demo_${W(`${e}:${n()}`,32)}`,Mn=e=>{var m,A;const s=e.target,r=s.kind==="start_run"?s.agent_id:(m=g.get(s.run_id))==null?void 0:m.story.agent;if(!r||!i.has(r))return null;const a=((A=e.name)==null?void 0:A.trim())||`${i.get(r).name} trigger`,l=Nn(a);_.push({id:l,name:a,agent:r,source:e.source,input:s.kind==="start_run"?s.input??{}:{},madeDaysAgo:(t-n())/U,target:s,catchup:e.catchup_window_s,maxActive:e.max_active_runs??null,secretAt:n()}),v.set(l,e.enabled??!0);const p=L(_.at(-1));return p.source.kind==="webhook"?{...p,signing_secret:Ct(l)}:p},Pn=(e,s)=>{const r=_.find(a=>a.id===e);return r?(s.name!==void 0&&(r.name=s.name),s.enabled!==void 0&&v.set(e,s.enabled),s.source&&(r.source=s.source,r.nextIn=void 0,r.nextAt=void 0),s.target&&(r.target=s.target,r.target.kind==="start_run"&&(r.agent=r.target.agent_id,r.input=r.target.input)),s.catchup_window_s!==void 0&&(r.catchup=s.catchup_window_s),s.max_active_runs!==void 0&&(r.maxActive=s.max_active_runs),L(r)):null},Ln=e=>Object.fromEntries(Object.entries(e).filter(([,s])=>!(typeof s=="string"&&s.includes("${")))),Fn=e=>{const s=_.findIndex(r=>r.id===e);return s<0?!1:(_.splice(s,1),v.delete(e),!0)},Wn=e=>{const s=_.find(r=>r.id===e);return!s||s.source.kind!=="webhook"?null:(s.secretAt=n(),{secret:{name:`trigger:${e}`,set:!0,source:"console",changed_at:E(s.secretAt)},signing_secret:Ct(e)})},Un=(e,s)=>{var N,Y,te,K,J;const r=(Y=(N=e.model)==null?void 0:N.choices)==null?void 0:Y.find(ne=>{var k;return ne.id===((k=s.overrides)==null?void 0:k.choice)}),a=((te=s.overrides)==null?void 0:te.model)??(r==null?void 0:r.model),l=(K=s.overrides)==null?void 0:K.approvals,p={version:1,name:e.display_name??e.name,description:e.description,instructions:e.description,harness:(r==null?void 0:r.harness)??((J=e.harness)==null?void 0:J[0])??"pi",tools:e.tools??[],skills:e.skills,...e.learning?{learning:!0}:{},...a?{model:a}:{},...l?{approvals:l}:{}},m=s.agent_id&&i.has(s.agent_id)?s.agent_id:null,A={template:e.id,version:e.version,servers:{},triggers:[],warnings:[]};if(s.dry_run)return{...A,agent_id:m??"",revision_id:null,revision_version:m?i.get(m).notes.length+1:1,agent_change:m?"updated":"made"};const M=m?Dt(m,p,`Applied template ${e.id}`):lt(p);return{...A,agent_id:M.agent_id,revision_id:M.revision,revision_version:M.revisions,agent_change:m?"updated":"made"}},Ot="mch_demo_laptop",jt=(e,s,r)=>({runtime:e,project:s,selector:r,machine_id:Ot,version:e==="codex"?"0.164.0":"2.1.330",model:e==="codex"?"openai/gpt-6.1-sol":ae.default,fingerprint:W(`${e}:${s}:setup`,64),configuration:[{path:e==="codex"?"AGENTS.md":"CLAUDE.md",sha256:W(`${e}:${s}:config`,64)}],skills:[],mcp_servers:[],state:"ready",issues:[],capabilities:{launch:!0,learning:!1,workflows:!1,approval:"native",usage:!0}}),Gn=(e,s)=>({machine_id:Ot,targets:(s?[s]:["claude-code","codex"]).map(r=>jt(r,e,{kind:"project"}))}),Kn=e=>{var N;const s=((N=e.selector)==null?void 0:N.kind)==="agent"&&e.selector.name?{kind:"agent",name:e.selector.name}:{kind:"project"},r=o.find(Y=>Y.native&&Y.native.runtime===e.runtime&&Y.native.project===e.project&&JSON.stringify(Y.native.selector)===JSON.stringify(s));if(r!=null&&r.native)return r.native.disconnected=void 0,r.native.verifiedAt=n(),{agent:q(r),native:f(r)};const l=`${e.project.split(/[\\/]/).filter(Boolean).at(-1)??"project"} (${e.runtime==="codex"?"Codex":"Claude Code"})`,p=jt(e.runtime,e.project,s),m=lt({name:l,description:`The ${e.runtime==="codex"?"Codex":"Claude Code"} setup in ${e.project}, run as it is set up there.`,harness:e.runtime,model:p.model,tools:[]}),A=i.get(m.agent_id);A.native={runtime:e.runtime,project:e.project,selector:s,version:p.version,skills:[],mcp:[]},A.saved=void 0,A.instructions=void 0;const M=q(A);return A.native.verifiedAt=n(),{agent:M,native:f(A)}},Bn=e=>{const s=i.get(e);return s!=null&&s.native?(s.native.disconnected=!0,f(s)):null},Hn=e=>{const s=i.get(e);return s!=null&&s.native?(s.native.verifiedAt=n(),f(s)):null},ct=(e,s)=>{const r=g.get(e);return!r||!R(r).pending?!1:(r.answers.push({at:n(),...s}),!0)};return{opened:t,clock:n,agents:()=>o.map(e=>q(e)),agent:e=>i.has(e)?q(i.get(e)):null,revisions:e=>i.has(e)?b(i.get(e)):null,modelOf:e=>{var s;return((s=i.get(e))==null?void 0:s.model)??ae.default},runs:({agent:e,status:s,archived:r}={})=>w().filter(a=>(!e||a.story.agent===e)&&!!a.archivedAt==!!r).map(a=>R(a)).filter(a=>!s||a.status===s),run:e=>g.has(e)?R(g.get(e)):null,rows:e=>g.has(e)?O(g.get(e)):null,graph:e=>g.has(e)?D(g.get(e),n()):null,trace:e=>{const s=g.get(e);if(!s)return null;const r=R(s);return Tr(e,O(s),i.get(s.story.agent).model,r.cost.usd??0,Math.max(rt(s.beats??[]),1))},usage:e=>{const s=g.get(e);return s?Rr(R(s),i.get(s.story.agent).model):null},files:e=>g.has(e)?$n(g.get(e)):null,runLearning:e=>g.has(e)?vn(g.get(e)):void 0,stats:S,triggers:()=>_.map(e=>L(e)),trigger:e=>{const s=_.find(r=>r.id===e);return s?L(s):null},firings:e=>G(e),setTriggerEnabled:(e,s)=>v.has(e)?(v.set(e,s),L(_.find(r=>r.id===e))):null,fire:e=>{const s=_.find(a=>a.id===e),r=s&&St(s.agent,Ln(s.input),"trigger",e);return r?{key:`${e}:${r.run_id}`,by:"manual",nominal_at:r.created_at,status:"started",at:r.created_at,run_id:r.run_id,reason:null,error:null}:null},learning:e=>i.has(e)?ot(e):null,createAgent:lt,saveDefinition:Dt,learningCost:hn,promotions:mn,loop:yn,audits:wn,workflowRevisions:kn,learningFile:_n,workflowAction:gn,holdScan:Sn,applyTemplate:Un,discoverNative:Gn,connectNative:Kn,disconnectNative:Bn,verifyNative:Hn,start:St,answer:ct,stop:(e,s)=>{const r=g.get(e);if(!r||R(r).ended_at)return!1;const a=(r.later??[]).filter(p=>p.kind!=="steer").at(-1),l=n();return a?(a.stopAt=l,a.cancelled=s):(r.stopAt=l,r.cancelled=s),!a&&r.story.graph&&(r.stoppedAt=u(r,l),r.pausedAt!==void 0&&(r.pausedMs=(r.pausedMs??0)+l-r.pausedAt,delete r.pausedAt)),delete r.settled,!0},archive:(e,s)=>{const r=g.get(e);return r?(r.archivedAt=s?n():void 0,R(r)):null},message:Dn,grade:Cn,raiseCap:On,setPaused:jn,archiveAgent:En,setCurrent:qn,writeCorrections:In,createTrigger:Mn,updateTrigger:Pn,deleteTrigger:Fn,rotateTriggerSecret:Wn,page:e=>sn[e]??null}}const T=(t,n=200,o={})=>new Response(t===void 0?null:JSON.stringify(t),{status:n,headers:{"content-type":"application/json",...o}}),_e=(t,n,o,i)=>T({error:{code:n,message:o,retryable:!1,request_id:"req_demo",...i?{details:i}:{}}},t),ee=t=>_e(404,"not_found",`no ${t}`),ce=()=>_e(403,"demo_mode",Yn);function ht(t,n,o=50){const i=Math.min(Math.max(Number(n.get("limit"))||o,1),200),g=Math.max(Number(n.get("cursor"))||0,0);return{items:t.slice(g,g+i),next_cursor:g+i<t.length?String(g+i):null}}const Ht=(t,n)=>new Promise(o=>{const i=setTimeout(o,t);n==null||n.addEventListener("abort",()=>{clearTimeout(i),o()},{once:!0})});function jr(t){const{secrets:n,switches:o,home:i,runner_refused:g,...d}=t,h=x=>Array.isArray(x)?x:[],y=({reason:x,needs:w,...O})=>({...O,available:!0}),u={default:"anthropic/claude-sonnet-5-5",fast:"openai/gpt-6-luna",strong:"anthropic/claude-opus-5-5"},D=d.features??{},R=d.workflows??{};return{...d,harnesses:h(d.harnesses).map(x=>({...y(x),default_model:x.id==="codex"?"openai/gpt-6.1-sol":u.default})),models:{...d.models,source:"providers",route_prefix:null,...u,ready:!0,needs:null,priced:!0},learning_model:{location:"server",ready:!0,model:u.default,needs:null,reason:null},learning:{...d.learning,pending:!0,approve:!0},tools:h(d.tools).map(x=>{const{why:w,resolves:O,...C}=y(x);return C}),workflows:{...R,...R.decisions?{decisions:{...R.decisions,providers:h(R.decisions.providers).map(y)}}:{}},features:{...D,learning:"on",triggers:{...D.triggers,routes:!0,public_url:!0}}}}function Er({real:t,world:n=fn()}){let o=null;const i=cr({opened:n.opened,clock:n.clock,makeAgent:d=>n.createAgent(d),holdScan:n.holdScan,readRun:d=>n.run(d)}),g=async(d,h,y,u,D,R)=>{var S,j,P,F;if(h.startsWith("/auth/"))return t(R,D);if(d==="GET"&&h==="/capabilities"){const _=await t(R,D);return _.ok?T(jr(await _.json())):_}const x=async()=>{if(o)return o;const _=await t("/v2/templates",{credentials:"same-origin"});return _.ok?(o=((await _.json()).templates??[]).filter(v=>v.bundled===!0),o):[]};if(d==="GET"&&h==="/templates"){const _=await t(R,D);if(!_.ok)return _;const v=await _.json();return o=(v.templates??[]).filter(G=>G.bundled===!0),T({...v,templates:o})}if(d==="GET"&&h==="/marketplace/templates"){const _=await t(R,D);if(!_.ok)return _;const v=await _.json(),G=new Set((await x()).map(H=>H.id));return T({...v,templates:v.templates.map(({here:H,...L})=>H&&G.has(H)?{...L,here:H}:L)})}const w=h.match(/^\/templates\/([^/]+)(\/apply)?$/);if(w){const _=(await x()).find(v=>v.id===decodeURIComponent(w[1]));return _?d==="GET"&&!w[2]?T({template:_}):d==="POST"&&w[2]?T(n.applyTemplate(_,u)):ce():ee(`template ${decodeURIComponent(w[1])}`)}const O=h.split("/").filter(Boolean).map(decodeURIComponent),[C,f,c,...q]=O,b=d==="GET";if(C==="agents"){if(!f){if(d==="POST"&&u.definition&&typeof u.definition=="object")return T(n.createAgent(u.definition),201);if(!b)return ce();const v=n.agents().filter(H=>!!H.archived_at==(y.get("archived")==="true")),G=ht(v,y,100);return T({agents:G.items,next_cursor:G.next_cursor})}const _=n.agent(f);if(!_)return ee(`agent ${f}`);if(!c)return b?T(_,200,{etag:_.home_etag}):ce();if(c==="definition"&&d==="PUT"&&u.definition&&typeof u.definition=="object"){const v=n.saveDefinition(f,u.definition,typeof u.note=="string"?u.note:null);return T(v,200,{etag:v.home_etag})}if(c==="native"&&b)return T({native:_.definition.native??null});if(c==="native"&&d==="POST"&&(q[0]==="verify"||q[0]==="disconnect")){const v=q[0]==="disconnect"?n.disconnectNative(f):n.verifyNative(f);return v?T({native:v}):ee(`native connection for agent ${f}`)}if((c==="archive"||c==="unarchive")&&d==="POST")return T(n.archiveAgent(f,c==="archive"));if(c==="current"&&d==="POST"){const v=n.setCurrent(f,String(u.revision??""));return v?T(v,200,{etag:v.home_etag}):ee(`revision ${String(u.revision??"")}`)}if(c==="revisions"&&b)return T({revisions:n.revisions(f),next_cursor:null});if(c==="runs"&&b){const v=ht(n.runs({agent:f,status:y.get("status")??void 0,archived:y.get("archived")==="true"}),y);return T({runs:v.items,next_cursor:v.next_cursor})}if(c==="runs"&&d==="POST"){if(_.native_status&&!_.native_status.connected)return _e(409,"conflict","This agent is disconnected: connect it again to run it.");const v=Array.isArray(u.file_ids)?u.file_ids.filter(Z=>typeof Z=="string"):[],G=v.map(Z=>{const ue=qt.get(Z);return ue?{id:Z,...ue}:null}),H=v.find((Z,ue)=>!G[ue]);if(H)return _e(422,"input_invalid",`No file ${H}: pick it again.`,{field:"file_ids"});const L=n.start(f,u.input&&typeof u.input=="object"?u.input:{},"person",void 0,G.filter(Z=>Z!==null));return L?T(L,202,{location:`/v2/runs/${L.run_id}`}):ee(`agent ${f}`)}if(c==="source"&&b)return T({enabled:!1,moved:!1,state:"needs_connection",blockers:[]});if(c==="learning"){const[v,...G]=q;if(!v&&b)return T(n.learning(f));if(v==="corrections"&&(b||d==="PUT")){if(d==="PUT"&&n.writeCorrections(f,String(u.text??""))===null)return ee(`learning for agent ${f}`);const H=((S=n.learning(f))==null?void 0:S.corrections)??"",L=`"${W(`corrections:${H}`,16)}"`;return T({text:H,etag:L,cap_bytes:2048},200,{etag:L})}if(v==="cost"&&b)return T(n.learningCost(f));if(v==="promotions"&&b)return T(n.promotions(f));if(v==="loop"&&b)return T(n.loop(f));if(v==="audits"&&b)return T(n.audits(f));if(v==="log"&&b)return T({items:[],total:((j=n.learning(f))==null?void 0:j.log.total)??0,next_cursor:null});if(v==="workflows"&&G[1]==="revisions"&&G.length===2&&b)return T(n.workflowRevisions(G[0]));if(v==="files"){const H=d==="POST"?G.at(-1):null,L=(H?G.slice(0,-1):G).join("/"),Z=n.learningFile(f,L);return Z===null?ee(`file ${L}`):H&&!n.workflowAction(f,L,H)?_e(409,"conflict",`The workflow is not in a state to ${H}.`):!b&&!H?ce():new Response(Z,{status:200,headers:{"content-type":"text/markdown; charset=utf-8",etag:`"${W(`file:${L}:${H??""}:${Date.now()}`,16)}"`}})}}return b?ee(`route ${h}`):ce()}if(C==="runs"){if(!f){if(!b)return ce();const v=ht(n.runs({status:y.get("status")??void 0,archived:y.get("archived")==="true"}),y);return T({runs:v.items,next_cursor:v.next_cursor})}const _=n.run(f);if(!_)return ee(`run ${f}`);if(!c)return b?T(_):d==="PATCH"&&typeof u.max_cost_usd=="number"?T(n.raiseCap(f,u.max_cost_usd)):ce();if(c==="timeline"&&b){const v=()=>{const ue=n.run(f),be=n.rows(f);return{r:ue,rows:be,n:be.length*8+(ue.pending?1:0)+(ue.ended_at?2:0)+(be.some(ve=>{var Pe;return(Pe=ve.summary)==null?void 0:Pe.startsWith("Asked your approval")})?4:0)+1}},G=y.has("after")?Number(y.get("after")):null,H=Date.now()+Math.min(Number(y.get("wait_ms"))||0,4e3);let L=v();for(;G!==null&&L.n===G&&!L.r.ended_at&&Date.now()<H&&!((P=D==null?void 0:D.signal)!=null&&P.aborted);)await Ht(250,D==null?void 0:D.signal),L=v();const Z=G!==null&&L.n===G;return T({run_id:f,status:L.r.status,state:L.r.state,reset:!Z,rows:Z?[]:L.rows,drop:[],next_after:L.n,unchanged:Z,has_more:!1,final:!!L.r.ended_at,cost:L.r.cost,poll_after_ms:L.r.ended_at?0:500})}if(c==="files"&&b){const v=n.files(f)??{};if(!q.length)return T({run_id:f,files:Object.entries(v).map(([H,L])=>({path:H,size_bytes:new TextEncoder().encode(L).length,modified_at:_.ended_at??_.updated_at,content_type:H.endsWith(".csv")?"text/csv; charset=utf-8":"text/markdown; charset=utf-8"})),complete:!0,truncated:!1});const G=v[q.join("/")];return G===void 0?ee(`file ${q.join("/")}`):new Response(G,{status:200,headers:{"content-type":"text/plain; charset=utf-8"}})}if(c==="graph"&&b){const v=n.graph(f);return v?T(v):ee(`graph for run ${f}`)}if(c==="trace"&&b)return T(n.trace(f));if(c==="usage"&&b)return T(n.usage(f));if(c==="learning"&&b)return q[0]==="diff"?T({base:null,head:null,files:[]}):T(n.runLearning(f)??null);if(c==="computer"&&b)return T({state:"off",why:"This run has no screen: its agent has no computer.",hold:"agent"});if(c==="grade"&&d==="PUT"&&typeof u.correct=="boolean")return T(n.grade(f,u));if(d==="POST"){if(c==="pause"||c==="resume"){const v=n.setPaused(f,c==="pause");return v?T(v):_e(409,"conflict","Only a workflow run pauses.")}if(c==="approvals"&&q[0])return((F=_.pending)==null?void 0:F.kind)==="approval"&&_.pending.id===q[0]?(n.answer(f,{decision:u.decision==="deny"?"deny":"allow"}),new Response(null,{status:204})):_e(409,"conflict","This call no longer waits for an answer.",{reason:"not_pending"});if(c==="messages"){const v=n.message(f,String(u.content??"")),G=n.run(f);return T({run_id:f,message_id:`msg_demo_${Date.now()}`,mode:v,status:G.status,state:G.state,poll_after_ms:500},202)}if(c==="stop"||c==="cancel")return n.stop(f,c==="cancel")?T({run_id:f,status:c==="cancel"?"cancelled":"completed"},202):_e(409,"conflict","The run has already ended.");if(c==="archive"||c==="unarchive")return T(n.archive(f,c==="archive"))}return b?ee(`route ${h}`):ce()}if(C==="stats"&&b){const _=y.get("from");return T(n.stats({..._?{from:Date.parse(_)}:{},...y.get("agent")?{agent:y.get("agent")}:{}}))}if(C==="triggers"){if(!f){if(b)return T({triggers:n.triggers()});if(d==="POST"&&u.source&&u.target){const v=n.createTrigger(u);return v?T(v,201):_e(422,"invalid_request","The trigger's target agent is not one of this server's.")}return ce()}const _=n.trigger(f);if(!_)return ee(`trigger ${f}`);if(!c)return b?T(_):d==="PATCH"?T(n.updateTrigger(f,u)):d==="DELETE"?(n.deleteTrigger(f),T({deleted:!0,composio:{done:!1,note:""}})):ce();if(c==="firings"&&b)return T({firings:n.firings(f)});if(c==="fire"&&d==="POST")return T(n.fire(f));if(c==="secret"&&d==="POST"){const v=n.rotateTriggerSecret(f);return v?T(v):_e(409,"conflict","Only a webhook trigger has a signing secret.")}return b?ee(`route ${h}`):ce()}if(C==="observations"&&b){const _=Number(y.get("days"))||30;return T({connectors:[],sessions:[],usage:{input_tokens:0,output_tokens:0,cache_read_tokens:null,cache_write_tokens:null,total_tokens:0,cache_hit_rate:null,overflow:!1,status:"unavailable",models:[],daily:[]},limits:{session_retention_days:90,usage_retention_days:90,window_start:new Date(n.opened-_*U).toISOString()}})}if(b&&h==="/settings/mcp-servers")return T({servers:[]});if(b&&h==="/settings/tools")return T({});if(b&&h==="/connectors")return T({connectors:[]});if(b&&h==="/suggestions")return T(i.list());if(b&&h==="/integrations/github/repositories")return T(i.repositories());if(b&&h==="/integrations/github")return T({connected:!0});if(d==="POST"&&h==="/suggestions/scans"){const _=i.rescan(String(u.repo??""));return _?T(_,202):ee(`repository ${String(u.repo??"")}`)}if(C==="suggestions"&&f){if(b&&!c){const _=i.detail(f);return _?T(_):ee(`suggestion ${f}`)}if(d==="POST"&&(c==="discard"||c==="restore")){const _=i.decide(f,c==="discard"?"discarded":"open");return _?T(_):ee(`suggestion ${f}`)}if(d==="POST"&&c==="create"){const _=i.create(f,typeof u.name=="string"?u.name:void 0);return _?T(_,201):ee(`suggestion ${f}`)}}return d==="POST"&&h==="/native/discover"?T(n.discoverNative(String(u.project??""),u.runtime==="codex"||u.runtime==="claude-code"?u.runtime:void 0)):d==="POST"&&h==="/native/connect"&&typeof u.project=="string"&&(u.runtime==="codex"||u.runtime==="claude-code")?T(n.connectNative(u),201):d==="POST"&&h==="/connectors/enrollment"?T({enrollment_token:`arcn_demo_${W(`enroll:${Date.now()}`,24)}`,expires_at:new Date(Date.now()+10*6e4).toISOString(),workspace_id:"local"},201):b&&h==="/computers"?T({kinds:[],paired:[]}):d==="POST"&&h==="/workflows/validate"?T({ok:!0,issues:[],warnings:[]}):d==="DELETE"&&C==="files"&&f?(qt.drop(f),new Response(null,{status:204})):b?ee(`route ${h}`):ce()};return async(d,h)=>{var R;const y=new URL(typeof d=="string"?d:d instanceof URL?d.href:d.url,"http://demo.invalid"),u=((h==null?void 0:h.method)??"GET").toUpperCase();let D={};if(typeof(h==null?void 0:h.body)=="string"&&h.body)try{const x=JSON.parse(h.body);x&&typeof x=="object"&&!Array.isArray(x)&&(D=x)}catch{}if(await Ht(40,h==null?void 0:h.signal),(R=h==null?void 0:h.signal)!=null&&R.aborted)throw new DOMException("The request was aborted.","AbortError");return g(u,y.pathname.replace(/^\/v2(?=\/)/,""),y.searchParams,D,h,d)}}function Mr({real:t}){const n=fn();return{fetch:Er({real:t,world:n}),fileUrl:(o,i)=>{var h;const g=n.page(i);if(g)return g;const d=(h=n.files(o))==null?void 0:h[i];return`data:text/plain;charset=utf-8,${encodeURIComponent(d??"")}`}}}export{Yn as DEMO_REFUSAL,Mr as createDemo,Er as createDemoFetch,jr as demoCapabilities};