@ouro.bot/cli 0.1.0-alpha.157 → 0.1.0-alpha.1571

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 (1675) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -42
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  13. package/assets/bluebubbles-host +264 -0
  14. package/assets/sanctuary-host-launcher.sh +16 -0
  15. package/changelog.json +9170 -44
  16. package/deploy/unraid/Dockerfile +85 -0
  17. package/deploy/unraid/INSTALL.md +64 -0
  18. package/deploy/unraid/README.txt +3034 -0
  19. package/deploy/unraid/audit-container-spec.sh +4 -0
  20. package/deploy/unraid/container-runtime.json +1 -0
  21. package/deploy/unraid/credit-gateway.md +95 -0
  22. package/deploy/unraid/docker-man-template-transaction.mjs +733 -0
  23. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  24. package/deploy/unraid/github_known_hosts +3 -0
  25. package/deploy/unraid/install.sh +274 -0
  26. package/deploy/unraid/migrate-sanctuary-bundle.mjs +63 -0
  27. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  28. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  29. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  30. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  31. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  32. package/deploy/unraid/ouro-host-lock.mjs +245 -0
  33. package/deploy/unraid/ouro-sync-ssh +98 -0
  34. package/deploy/unraid/ouro-sync.sudoers +3 -0
  35. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  36. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  37. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  38. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  39. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  40. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1604 -0
  41. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  42. package/deploy/unraid/sanctuary-replay-gate.mjs +2781 -0
  43. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  44. package/deploy/unraid/sanctuary-sync-cutover.sh +1039 -0
  45. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2088 -0
  46. package/deploy/unraid/sanctuary-unit16-run.sh +570 -0
  47. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  48. package/deploy/unraid/sanctuary.ouro/agent.json +72 -0
  49. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  50. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  51. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  52. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  53. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2533 -0
  54. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  55. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  56. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  60. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  61. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  62. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +274 -0
  63. package/deploy/unraid/sanctuary.xml +30 -0
  64. package/desk.lock.json +8 -0
  65. package/dist/a2a/approval-relay-forward.js +117 -0
  66. package/dist/a2a/approval-relay.js +95 -0
  67. package/dist/a2a/approval-request-wire.js +123 -0
  68. package/dist/a2a/card.js +57 -0
  69. package/dist/a2a/client.js +331 -0
  70. package/dist/a2a/config.js +50 -0
  71. package/dist/a2a/delegated-command-grants.js +93 -0
  72. package/dist/a2a/delegated-command.js +200 -0
  73. package/dist/a2a/delegation-stores.js +56 -0
  74. package/dist/a2a/did-resolution.js +205 -0
  75. package/dist/a2a/escalation-grants.js +84 -0
  76. package/dist/a2a/escalation-wiring.js +60 -0
  77. package/dist/a2a/identity.js +258 -0
  78. package/dist/a2a/inbound-share.js +131 -0
  79. package/dist/a2a/mission-result-wire.js +265 -0
  80. package/dist/a2a/onboarding.js +133 -0
  81. package/dist/a2a/operator-trust.js +399 -0
  82. package/dist/a2a/outbox-client.js +59 -0
  83. package/dist/a2a/outbox-store.js +245 -0
  84. package/dist/a2a/outbox-wire.js +106 -0
  85. package/dist/a2a/pin-store.js +167 -0
  86. package/dist/a2a/refusals.js +55 -0
  87. package/dist/a2a/relay-client.js +106 -0
  88. package/dist/a2a/relay-config-vault.js +64 -0
  89. package/dist/a2a/relay-contacts.js +120 -0
  90. package/dist/a2a/relay-inbox.js +360 -0
  91. package/dist/a2a/relay-retirements.js +89 -0
  92. package/dist/a2a/replay-grant-holders.js +33 -0
  93. package/dist/a2a/replay-harness.js +188 -0
  94. package/dist/a2a/resolution-proof.js +53 -0
  95. package/dist/a2a/sealed-chat.js +142 -0
  96. package/dist/a2a/seen-ledger.js +216 -0
  97. package/dist/a2a/server.js +1088 -0
  98. package/dist/a2a/task-store.js +69 -0
  99. package/dist/a2a/transport.js +100 -0
  100. package/dist/a2a/trust-commands.js +203 -0
  101. package/dist/a2a/trusted-files.js +185 -0
  102. package/dist/a2a/types.js +3 -0
  103. package/dist/actions/generated/mailbox/actions.json +592 -0
  104. package/dist/actions/generated/mailbox/commands.json +181 -0
  105. package/dist/actions/generated/mailbox/mcp.json +454 -0
  106. package/dist/actions/generated/mailbox-tools/tools.json +516 -0
  107. package/dist/arc/attention-types.js +8 -0
  108. package/dist/arc/cares.js +360 -0
  109. package/dist/arc/episodes.js +118 -0
  110. package/dist/arc/evolution.js +490 -0
  111. package/dist/arc/flight-recorder.js +1009 -0
  112. package/dist/arc/intentions.js +134 -0
  113. package/dist/arc/json-store.js +117 -0
  114. package/dist/arc/obligations.js +386 -0
  115. package/dist/arc/packets.js +336 -0
  116. package/dist/arc/presence.js +185 -0
  117. package/dist/arc/task-lifecycle.js +57 -0
  118. package/dist/commerce/store.js +755 -0
  119. package/dist/commerce/types.js +3 -0
  120. package/dist/eval/assertions/index.js +378 -0
  121. package/dist/eval/billing-guard.js +23 -0
  122. package/dist/eval/budget.js +142 -0
  123. package/dist/eval/domain/case.js +115 -0
  124. package/dist/eval/domain/stats.js +19 -0
  125. package/dist/eval/guest-entry.js +18 -0
  126. package/dist/eval/h-guest-entry.js +19 -0
  127. package/dist/eval/interview-entry.js +174 -0
  128. package/dist/eval/interview-grade-entry.js +36 -0
  129. package/dist/eval/interview-guest-entry.js +19 -0
  130. package/dist/eval/interviews/allocation.js +90 -0
  131. package/dist/eval/interviews/final.js +133 -0
  132. package/dist/eval/interviews/grader.js +209 -0
  133. package/dist/eval/interviews/guest/arms.js +173 -0
  134. package/dist/eval/interviews/guest/ax/ax-command.js +792 -0
  135. package/dist/eval/interviews/guest/ax/effects.js +51 -0
  136. package/dist/eval/interviews/guest/ax/exit-codes.js +51 -0
  137. package/dist/eval/interviews/guest/ax/help.js +181 -0
  138. package/dist/eval/interviews/guest/ax/mcp.js +246 -0
  139. package/dist/eval/interviews/guest/ax/outcome.js +211 -0
  140. package/dist/eval/interviews/guest/ax/output.js +53 -0
  141. package/dist/eval/interviews/guest/ax/precise-copy.js +200 -0
  142. package/dist/eval/interviews/guest/ax/problem.js +95 -0
  143. package/dist/eval/interviews/guest/ax/voice.js +83 -0
  144. package/dist/eval/interviews/guest/ax/wait.js +158 -0
  145. package/dist/eval/interviews/guest/books-core.js +54 -0
  146. package/dist/eval/interviews/guest/cli-shell.js +267 -0
  147. package/dist/eval/interviews/guest/h/codex.js +201 -0
  148. package/dist/eval/interviews/guest/h/fidelity.js +59 -0
  149. package/dist/eval/interviews/guest/h/openhands.js +176 -0
  150. package/dist/eval/interviews/guest/h/run.js +99 -0
  151. package/dist/eval/interviews/guest/h/wire.js +403 -0
  152. package/dist/eval/interviews/guest/loop.js +87 -0
  153. package/dist/eval/interviews/guest/operations.js +108 -0
  154. package/dist/eval/interviews/guest/run.js +81 -0
  155. package/dist/eval/interviews/guest/u/arms.js +268 -0
  156. package/dist/eval/interviews/h/kit.js +119 -0
  157. package/dist/eval/interviews/latch.js +143 -0
  158. package/dist/eval/interviews/protocol.js +120 -0
  159. package/dist/eval/interviews/rewrite.js +57 -0
  160. package/dist/eval/interviews/runner.js +354 -0
  161. package/dist/eval/interviews/u/kit.js +117 -0
  162. package/dist/eval/kill-switch.js +33 -0
  163. package/dist/eval/month-ledger.js +95 -0
  164. package/dist/eval/readback/hedges.js +39 -0
  165. package/dist/eval/remote-entry.js +32 -0
  166. package/dist/eval/report.js +85 -0
  167. package/dist/eval/run-command.js +188 -0
  168. package/dist/eval/run-entry.js +93 -0
  169. package/dist/eval/sandbox/agent-profile.js +74 -0
  170. package/dist/eval/sandbox/declared-gaps.js +17 -0
  171. package/dist/eval/sandbox/docker.js +353 -0
  172. package/dist/eval/sandbox/guest.js +55 -0
  173. package/dist/eval/sandbox/host-lock.js +62 -0
  174. package/dist/eval/sandbox/images.js +39 -0
  175. package/dist/eval/sandbox/oracle.js +32 -0
  176. package/dist/eval/sandbox/projection.js +127 -0
  177. package/dist/eval/sandbox/readback.js +137 -0
  178. package/dist/eval/sandbox/remote.js +102 -0
  179. package/dist/eval/sandbox/slugger-projection.js +377 -0
  180. package/dist/eval/self-test.js +84 -0
  181. package/dist/eval/stop-command.js +71 -0
  182. package/dist/eval/stop-entry.js +46 -0
  183. package/dist/eval/targets/index.js +127 -0
  184. package/dist/eval/transport/provider-proxy.js +262 -0
  185. package/dist/eval/transport/synthetic-sanctuary.js +111 -0
  186. package/dist/eval/transport/telegram-turn.js +241 -0
  187. package/dist/eval/watch/cli.js +63 -0
  188. package/dist/eval/watch/guarded-fs.js +254 -0
  189. package/dist/eval/watch/log-reader.js +99 -0
  190. package/dist/eval/watch/rows.js +143 -0
  191. package/dist/eval/watch/run-watch.js +160 -0
  192. package/dist/eval/watch-entry.js +26 -0
  193. package/dist/gateway/keys.js +117 -0
  194. package/dist/gateway/server.js +429 -0
  195. package/dist/heart/active-work.js +421 -45
  196. package/dist/heart/agent-entry.js +255 -4
  197. package/dist/heart/approval-files.js +94 -0
  198. package/dist/heart/approval-store.js +1000 -0
  199. package/dist/heart/atomic-file.js +115 -0
  200. package/dist/heart/attachments/downloaded-store.js +89 -0
  201. package/dist/heart/attachments/image-normalize.js +201 -0
  202. package/dist/heart/attachments/materialize.js +97 -0
  203. package/dist/heart/attachments/originals.js +102 -0
  204. package/dist/heart/attachments/render.js +29 -0
  205. package/dist/heart/attachments/sources/bluebubbles.js +155 -0
  206. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  207. package/dist/heart/attachments/sources/downloaded.js +76 -0
  208. package/dist/heart/attachments/sources/index.js +19 -0
  209. package/dist/heart/attachments/store.js +132 -0
  210. package/dist/heart/attachments/transcribe-audio.js +231 -0
  211. package/dist/heart/attachments/types.js +93 -0
  212. package/dist/heart/attachments/understand.js +195 -0
  213. package/dist/heart/auth/auth-flow.js +589 -0
  214. package/dist/heart/auth/github-device-login.js +104 -0
  215. package/dist/heart/autonomy-budget.js +426 -0
  216. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  217. package/dist/heart/awaiting/await-alert.js +152 -0
  218. package/dist/heart/awaiting/await-expiry.js +143 -0
  219. package/dist/heart/awaiting/await-loader.js +91 -0
  220. package/dist/heart/awaiting/await-parser.js +152 -0
  221. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  222. package/dist/heart/awaiting/await-scheduler.js +462 -0
  223. package/dist/heart/background-operations.js +281 -0
  224. package/dist/heart/bluebubbles-host-account.js +78 -0
  225. package/dist/heart/bridges/manager.js +137 -17
  226. package/dist/heart/bridges/store.js +14 -2
  227. package/dist/heart/bundle-state.js +168 -0
  228. package/dist/heart/chat-interaction.js +69 -0
  229. package/dist/heart/commitments.js +44 -14
  230. package/dist/heart/config-registry.js +340 -0
  231. package/dist/heart/config.js +191 -140
  232. package/dist/heart/context-loss-gauntlet.js +387 -0
  233. package/dist/heart/context-loss-sentinel.js +1206 -0
  234. package/dist/heart/core.js +2760 -695
  235. package/dist/heart/cross-chat-delivery.js +29 -22
  236. package/dist/heart/daemon/agent-config-check.js +494 -0
  237. package/dist/heart/daemon/agent-discovery.js +304 -3
  238. package/dist/heart/daemon/agent-home.js +409 -0
  239. package/dist/heart/daemon/agent-service.js +210 -28
  240. package/dist/heart/daemon/agentic-repair.js +548 -0
  241. package/dist/heart/daemon/app-sessions-record.js +82 -0
  242. package/dist/heart/daemon/await-private-wake.js +59 -0
  243. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  244. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  245. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  246. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  247. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  248. package/dist/heart/daemon/cadence.js +110 -0
  249. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  250. package/dist/heart/daemon/cli-commands/a2a.js +26 -0
  251. package/dist/heart/daemon/cli-commands/cards.js +68 -0
  252. package/dist/heart/daemon/cli-commands/coding-tools.js +13 -0
  253. package/dist/heart/daemon/cli-commands/desk.js +43 -0
  254. package/dist/heart/daemon/cli-commands/dns.js +13 -0
  255. package/dist/heart/daemon/cli-commands/entry-points.js +182 -0
  256. package/dist/heart/daemon/cli-commands/failure-code.js +11 -0
  257. package/dist/heart/daemon/cli-commands/friends.js +18 -0
  258. package/dist/heart/daemon/cli-commands/habits.js +15 -0
  259. package/dist/heart/daemon/cli-commands/lifecycle.js +42 -0
  260. package/dist/heart/daemon/cli-commands/mail.js +11 -0
  261. package/dist/heart/daemon/cli-commands/mind.js +25 -0
  262. package/dist/heart/daemon/cli-commands/presence.js +28 -0
  263. package/dist/heart/daemon/cli-commands/providers.js +20 -0
  264. package/dist/heart/daemon/cli-commands/rsvp.js +20 -0
  265. package/dist/heart/daemon/cli-commands/shepherd.js +17 -0
  266. package/dist/heart/daemon/cli-commands/vault.js +23 -0
  267. package/dist/heart/daemon/cli-defaults.js +997 -0
  268. package/dist/heart/daemon/cli-desk.js +346 -0
  269. package/dist/heart/daemon/cli-exec.js +9688 -0
  270. package/dist/heart/daemon/cli-gate.js +198 -0
  271. package/dist/heart/daemon/cli-help.js +800 -0
  272. package/dist/heart/daemon/cli-manifest.js +115 -0
  273. package/dist/heart/daemon/cli-parse.js +3635 -0
  274. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  275. package/dist/heart/daemon/cli-render.js +816 -0
  276. package/dist/heart/daemon/cli-types.js +8 -0
  277. package/dist/heart/daemon/compile-cache.js +69 -0
  278. package/dist/heart/daemon/connect-bay.js +323 -0
  279. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  280. package/dist/heart/daemon/container-healthcheck.js +123 -0
  281. package/dist/heart/daemon/container-runtime.js +97 -0
  282. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  283. package/dist/heart/daemon/container-spec-auditor.js +261 -0
  284. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  285. package/dist/heart/daemon/daemon-cli.js +29 -3163
  286. package/dist/heart/daemon/daemon-entry.js +1074 -55
  287. package/dist/heart/daemon/daemon-health.js +51 -1
  288. package/dist/heart/daemon/daemon-rollup.js +57 -0
  289. package/dist/heart/daemon/daemon-runtime-sync.js +147 -13
  290. package/dist/heart/daemon/daemon-tombstone.js +116 -3
  291. package/dist/heart/daemon/daemon.js +1983 -131
  292. package/dist/heart/daemon/desk-admin.js +420 -0
  293. package/dist/heart/daemon/dns-workflow.js +394 -0
  294. package/dist/heart/daemon/doctor-types.js +8 -0
  295. package/dist/heart/daemon/doctor.js +1890 -0
  296. package/dist/heart/daemon/freshness.js +345 -0
  297. package/dist/heart/daemon/habit-private-wake.js +61 -0
  298. package/dist/heart/daemon/health-monitor.js +242 -12
  299. package/dist/heart/daemon/home-filesystem.js +93 -0
  300. package/dist/heart/daemon/hook-post-tool-use.js +149 -0
  301. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  302. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  303. package/dist/heart/daemon/http-health-probe.js +80 -0
  304. package/dist/heart/daemon/human-command-screens.js +234 -0
  305. package/dist/heart/daemon/human-readiness.js +114 -0
  306. package/dist/heart/daemon/inner-status.js +7 -18
  307. package/dist/heart/daemon/interactive-repair.js +394 -0
  308. package/dist/heart/daemon/launchd.js +40 -8
  309. package/dist/heart/daemon/linux-service.js +382 -0
  310. package/dist/heart/daemon/log-tailer.js +79 -10
  311. package/dist/heart/daemon/logs-prune.js +132 -0
  312. package/dist/heart/daemon/mailroom-copy-proof.js +158 -0
  313. package/dist/heart/daemon/mcp-canary.js +525 -0
  314. package/dist/heart/daemon/message-router.js +65 -5
  315. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  316. package/dist/heart/daemon/os-cron-deps.js +5 -0
  317. package/dist/heart/daemon/os-cron.js +45 -15
  318. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  319. package/dist/heart/daemon/ouro-cli-main.js +50 -0
  320. package/dist/heart/daemon/ouro-entry.js +43 -20
  321. package/dist/heart/daemon/plugin-cli.js +432 -0
  322. package/dist/heart/daemon/portable-git-install.js +265 -0
  323. package/dist/heart/daemon/portable-git.js +179 -0
  324. package/dist/heart/daemon/presence-daemon.js +265 -0
  325. package/dist/heart/daemon/presence-roster.js +260 -0
  326. package/dist/heart/daemon/presence.js +469 -0
  327. package/dist/heart/daemon/process-manager.js +790 -71
  328. package/dist/heart/daemon/process-tree.js +109 -0
  329. package/dist/heart/daemon/provider-discovery.js +171 -0
  330. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  331. package/dist/heart/daemon/prunable-bundle.js +144 -0
  332. package/dist/heart/daemon/pulse.js +511 -0
  333. package/dist/heart/daemon/readiness-repair.js +365 -0
  334. package/dist/heart/daemon/run-hooks.js +2 -0
  335. package/dist/heart/daemon/runtime-logging.js +54 -14
  336. package/dist/heart/daemon/runtime-metadata.js +2 -30
  337. package/dist/heart/daemon/runtime-mode.js +13 -2
  338. package/dist/heart/daemon/runtime-replacement-handoff.js +207 -0
  339. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2659 -0
  340. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  341. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  342. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +956 -0
  343. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  344. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  345. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  346. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  347. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1370 -0
  348. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  349. package/dist/heart/daemon/sanctuary-bundle-migration.js +974 -0
  350. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  351. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  352. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  353. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  354. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +210 -0
  355. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  356. package/dist/heart/daemon/sanctuary-package-management.js +113 -0
  357. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  358. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  359. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +481 -0
  360. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +614 -0
  361. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +763 -0
  362. package/dist/heart/daemon/sanctuary-telegram-test-driver-entry.js +97 -0
  363. package/dist/heart/daemon/sanctuary-telegram-test-driver.js +294 -0
  364. package/dist/heart/daemon/sense-manager.js +1071 -60
  365. package/dist/heart/daemon/skill-management-installer.js +1 -1
  366. package/dist/heart/daemon/socket-client.js +180 -12
  367. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  368. package/dist/heart/daemon/startup-tui.js +339 -0
  369. package/dist/heart/daemon/state-retention.js +234 -0
  370. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  371. package/dist/heart/daemon/task-scheduler.js +115 -15
  372. package/dist/heart/daemon/terminal-ui.js +503 -0
  373. package/dist/heart/daemon/thoughts.js +133 -49
  374. package/dist/heart/daemon/up-progress.js +366 -0
  375. package/dist/heart/daemon/vault-items.js +56 -0
  376. package/dist/heart/daemon/vault-outage.js +74 -0
  377. package/dist/heart/delegated-work-report.js +115 -0
  378. package/dist/heart/delegation.js +0 -3
  379. package/dist/heart/external-events/router.js +1556 -0
  380. package/dist/heart/failure-reports.js +398 -0
  381. package/dist/heart/file-lock.js +109 -0
  382. package/dist/heart/frontend-approval-runtime.js +506 -0
  383. package/dist/heart/frontend-journal.js +215 -0
  384. package/dist/heart/frontend-session-service.js +330 -0
  385. package/dist/heart/frontend-socket-client.js +173 -0
  386. package/dist/heart/frontend-socket.js +434 -0
  387. package/dist/heart/frontend-turn-errors.js +20 -0
  388. package/dist/heart/git-binary.js +115 -0
  389. package/dist/heart/habits/habit-cancel.js +810 -0
  390. package/dist/heart/habits/habit-lifecycle.js +1324 -0
  391. package/dist/heart/{daemon → habits}/habit-migration.js +41 -28
  392. package/dist/heart/habits/habit-parser.js +258 -0
  393. package/dist/heart/habits/habit-runtime-state.js +93 -0
  394. package/dist/heart/habits/habit-scheduler.js +667 -0
  395. package/dist/heart/habits/habit-session-summary.js +318 -0
  396. package/dist/heart/habits/habit-session.js +638 -0
  397. package/dist/heart/{daemon → hatch}/hatch-flow.js +60 -36
  398. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  399. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -6
  400. package/dist/heart/hatch/specialist-tools.js +395 -0
  401. package/dist/heart/identity.js +404 -60
  402. package/dist/heart/kept-notes.js +289 -0
  403. package/dist/heart/letters/doors-tools.js +63 -0
  404. package/dist/heart/letters/doors.js +436 -0
  405. package/dist/heart/letters/letter-index.js +89 -0
  406. package/dist/heart/letters/letter.js +247 -0
  407. package/dist/heart/letters/store.js +210 -0
  408. package/dist/heart/letters/writer.js +298 -0
  409. package/dist/heart/machine-identity.js +175 -0
  410. package/dist/heart/mail-import-discovery.js +356 -0
  411. package/dist/heart/mcp/mcp-server.js +922 -0
  412. package/dist/heart/migrate-config.js +100 -0
  413. package/dist/heart/model-capabilities.js +98 -16
  414. package/dist/heart/model-limits.js +49 -0
  415. package/dist/heart/optional-packages.js +77 -0
  416. package/dist/heart/orientation-frame.js +393 -0
  417. package/dist/heart/platform.js +81 -0
  418. package/dist/heart/primitives.js +1 -1
  419. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  420. package/dist/heart/private-runtime/index.js +18 -0
  421. package/dist/heart/private-runtime/ledger.js +212 -0
  422. package/dist/heart/private-runtime/policy.js +303 -0
  423. package/dist/heart/private-runtime/types.js +2 -0
  424. package/dist/heart/progress-story.js +1 -1
  425. package/dist/heart/provider-attempt.js +137 -0
  426. package/dist/heart/provider-binding-resolver.js +273 -0
  427. package/dist/heart/provider-credentials.js +449 -0
  428. package/dist/heart/provider-failover.js +260 -37
  429. package/dist/heart/provider-fallback.js +228 -0
  430. package/dist/heart/provider-models.js +96 -0
  431. package/dist/heart/provider-ping-child.js +125 -0
  432. package/dist/heart/provider-ping-entry.js +8 -0
  433. package/dist/heart/provider-ping.js +217 -78
  434. package/dist/heart/provider-readiness-cache.js +119 -0
  435. package/dist/heart/provider-visibility.js +188 -0
  436. package/dist/heart/providers/account-pool.js +717 -0
  437. package/dist/heart/providers/anthropic-token.js +15 -47
  438. package/dist/heart/providers/anthropic.js +275 -80
  439. package/dist/heart/providers/azure.js +19 -31
  440. package/dist/heart/providers/error-classification.js +129 -0
  441. package/dist/heart/providers/github-copilot.js +131 -36
  442. package/dist/heart/providers/minimax-vlm.js +189 -0
  443. package/dist/heart/providers/minimax.js +19 -27
  444. package/dist/heart/providers/openai-codex-token.js +349 -0
  445. package/dist/heart/providers/openai-codex.js +46 -57
  446. package/dist/heart/providers/openai-compatible.js +177 -0
  447. package/dist/heart/quota/fleet-readings.js +222 -0
  448. package/dist/heart/quota/tranche.js +59 -0
  449. package/dist/heart/reach-channel.js +85 -0
  450. package/dist/heart/reply-style.js +52 -0
  451. package/dist/heart/run-ledger.js +247 -0
  452. package/dist/heart/runtime-capability-check.js +170 -0
  453. package/dist/heart/runtime-credentials.js +647 -0
  454. package/dist/heart/runtime-cwd.js +87 -0
  455. package/dist/heart/sense-truth.js +26 -4
  456. package/dist/heart/sent-message-ledger.js +98 -0
  457. package/dist/heart/session-activity.js +89 -23
  458. package/dist/heart/session-events.js +1609 -0
  459. package/dist/heart/session-playback-cli-main.js +10 -0
  460. package/dist/heart/session-playback-cli.js +36 -0
  461. package/dist/heart/session-playback.js +231 -0
  462. package/dist/heart/session-redaction-repair-cli-main.js +34 -0
  463. package/dist/heart/session-redaction-repair.js +552 -0
  464. package/dist/heart/session-stats-cli-main.js +10 -0
  465. package/dist/heart/session-stats.js +183 -0
  466. package/dist/heart/session-transcript.js +133 -0
  467. package/dist/heart/shelf-claims.js +136 -0
  468. package/dist/heart/shepherd/custody-types.js +2 -0
  469. package/dist/heart/shepherd/mandates.js +352 -0
  470. package/dist/heart/shepherd/operation-commands.js +19 -0
  471. package/dist/heart/shepherd/operations.js +139 -0
  472. package/dist/heart/shepherd/supervision-read.js +131 -0
  473. package/dist/heart/shepherd/supervision.js +114 -0
  474. package/dist/heart/shepherd/types.js +2 -0
  475. package/dist/heart/shepherd-config.js +113 -0
  476. package/dist/heart/source-grounding.js +313 -0
  477. package/dist/heart/sqlite.js +18 -0
  478. package/dist/heart/start-of-turn-packet.js +372 -0
  479. package/dist/heart/steward-policy.js +656 -0
  480. package/dist/heart/streaming.js +627 -193
  481. package/dist/heart/structured-output.js +196 -0
  482. package/dist/heart/sync-classification.js +176 -0
  483. package/dist/heart/sync-health.js +152 -0
  484. package/dist/heart/sync-lock.js +431 -0
  485. package/dist/heart/sync.js +1583 -0
  486. package/dist/heart/target-resolution.js +7 -7
  487. package/dist/heart/tempo.js +93 -0
  488. package/dist/heart/temporal-view.js +41 -0
  489. package/dist/heart/termination-guard.js +27 -0
  490. package/dist/heart/timeouts.js +101 -0
  491. package/dist/heart/tool-activity-callbacks.js +27 -4
  492. package/dist/heart/tool-approval.js +382 -0
  493. package/dist/heart/tool-description.js +29 -9
  494. package/dist/heart/tool-friction.js +55 -0
  495. package/dist/heart/tool-images.js +42 -0
  496. package/dist/heart/tool-loop.js +9 -3
  497. package/dist/heart/tool-output-budget.js +41 -0
  498. package/dist/heart/turn-context.js +503 -0
  499. package/dist/heart/turn-execution-lease.js +78 -0
  500. package/dist/heart/turn-summary.js +216 -0
  501. package/dist/heart/versioning/host-self-update.js +118 -0
  502. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  503. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +3 -2
  504. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  505. package/dist/heart/versioning/ouro-recovery-launcher.js +98 -0
  506. package/dist/heart/versioning/ouro-version-manager.js +432 -0
  507. package/dist/heart/versioning/release-sources.js +185 -0
  508. package/dist/heart/versioning/self-update-defaults.js +443 -0
  509. package/dist/heart/versioning/self-update.js +270 -0
  510. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  511. package/dist/heart/{daemon → versioning}/update-checker.js +12 -35
  512. package/dist/heart/versioning/update-hooks.js +160 -0
  513. package/dist/heart/versioning/update-state.js +134 -0
  514. package/dist/heart/versioning/updater-launchd.js +204 -0
  515. package/dist/heart/versioning/version-intent.js +114 -0
  516. package/dist/heart/work-card.js +380 -0
  517. package/dist/mailroom/attention.js +167 -0
  518. package/dist/mailroom/autonomy.js +209 -0
  519. package/dist/mailroom/azure-sdk.js +27 -0
  520. package/dist/mailroom/blob-store.js +991 -0
  521. package/dist/mailroom/body-cache.js +61 -0
  522. package/dist/mailroom/cache-sync-cli.js +58 -0
  523. package/dist/mailroom/core.js +813 -0
  524. package/dist/mailroom/entry.js +169 -0
  525. package/dist/mailroom/file-store.js +568 -0
  526. package/dist/mailroom/hosted-cache-sync.js +384 -0
  527. package/dist/mailroom/mbox-import.js +393 -0
  528. package/dist/mailroom/migration.js +164 -0
  529. package/dist/mailroom/outbound.js +380 -0
  530. package/dist/mailroom/policy.js +263 -0
  531. package/dist/mailroom/reader.js +308 -0
  532. package/dist/mailroom/search-cache.js +513 -0
  533. package/dist/mailroom/search-relevance.js +319 -0
  534. package/dist/mailroom/smtp-ingress.js +176 -0
  535. package/dist/mailroom/source-state.js +176 -0
  536. package/dist/mailroom/sweep-orphans-cli.js +34 -0
  537. package/dist/mailroom/thread.js +109 -0
  538. package/dist/mailroom/travel-extract.js +89 -0
  539. package/dist/mind/bundle-manifest.js +25 -4
  540. package/dist/mind/context.js +335 -198
  541. package/dist/mind/desk-section.js +332 -0
  542. package/dist/mind/diary-integrity.js +60 -0
  543. package/dist/mind/diary.js +38 -56
  544. package/dist/mind/embedding-provider.js +60 -0
  545. package/dist/mind/file-state.js +179 -0
  546. package/dist/mind/friend-link-codes.js +209 -0
  547. package/dist/mind/friend-merge.js +336 -0
  548. package/dist/mind/house-names.js +43 -0
  549. package/dist/mind/note-search.js +198 -0
  550. package/dist/mind/obligation-steering.js +15 -9
  551. package/dist/mind/outbound-record.js +176 -0
  552. package/dist/mind/pending.js +294 -11
  553. package/dist/mind/prompt-budget.js +511 -0
  554. package/dist/mind/prompt-refresh.js +3 -2
  555. package/dist/mind/prompt.js +922 -375
  556. package/dist/mind/provenance-trust.js +26 -0
  557. package/dist/mind/record-paths.js +312 -0
  558. package/dist/mind/scrutiny.js +121 -0
  559. package/dist/mind/session-transaction.js +642 -0
  560. package/dist/mind/token-estimate.js +17 -0
  561. package/dist/mind/where-am-i.js +176 -0
  562. package/dist/nerves/cli-logging.js +7 -1
  563. package/dist/nerves/coverage/audit-rules.js +15 -6
  564. package/dist/nerves/coverage/audit.js +28 -2
  565. package/dist/nerves/coverage/cli-main.js +6 -1
  566. package/dist/nerves/coverage/cli.js +1 -1
  567. package/dist/nerves/coverage/contract.js +5 -5
  568. package/dist/nerves/coverage/file-completeness.js +153 -5
  569. package/dist/nerves/coverage/run-artifacts.js +55 -35
  570. package/dist/nerves/coverage/source-scanner.js +4 -4
  571. package/dist/nerves/index.js +266 -30
  572. package/dist/nerves/observation.js +18 -0
  573. package/dist/nerves/redact.js +79 -0
  574. package/dist/nerves/review/cli-main.js +10 -0
  575. package/dist/nerves/review/cli.js +156 -0
  576. package/dist/nerves/review/core.js +159 -0
  577. package/dist/nerves/runtime.js +16 -1
  578. package/dist/repertoire/ado-client.js +15 -56
  579. package/dist/repertoire/ado-semantic.js +108 -40
  580. package/dist/repertoire/api-client.js +97 -0
  581. package/dist/repertoire/auth-required.js +22 -0
  582. package/dist/repertoire/bitwarden-native.js +458 -0
  583. package/dist/repertoire/bitwarden-store.js +1296 -0
  584. package/dist/repertoire/bundle-templates.js +71 -0
  585. package/dist/repertoire/bw-installer.js +268 -0
  586. package/dist/repertoire/coding/context-pack.js +80 -3
  587. package/dist/repertoire/coding/feedback.js +27 -26
  588. package/dist/repertoire/coding/index.js +63 -6
  589. package/dist/repertoire/coding/manager.js +31 -14
  590. package/dist/repertoire/coding/orca-client.js +194 -0
  591. package/dist/repertoire/coding/orca-manager.js +460 -0
  592. package/dist/repertoire/coding/router.js +124 -0
  593. package/dist/repertoire/coding/spawner.js +3 -2
  594. package/dist/repertoire/coding/tools.js +178 -34
  595. package/dist/repertoire/coding/workbench-client.js +272 -0
  596. package/dist/repertoire/coding/workbench-manager.js +404 -0
  597. package/dist/repertoire/commerce-errors.js +109 -0
  598. package/dist/repertoire/commerce-self-test.js +156 -0
  599. package/dist/repertoire/credential-access.js +183 -0
  600. package/dist/repertoire/desk/classifier.js +362 -0
  601. package/dist/repertoire/desk-mcp.js +204 -0
  602. package/dist/repertoire/duffel-client.js +185 -0
  603. package/dist/repertoire/github-client.js +14 -55
  604. package/dist/repertoire/graph-client.js +11 -52
  605. package/dist/repertoire/guardrails.js +1174 -70
  606. package/dist/repertoire/house-sweep.js +471 -0
  607. package/dist/repertoire/in-turn-tools-door.js +55 -0
  608. package/dist/repertoire/mcp-client.js +58 -5
  609. package/dist/repertoire/mcp-declared-tools.js +156 -0
  610. package/dist/repertoire/mcp-manager.js +457 -141
  611. package/dist/repertoire/mcp-tools.js +199 -0
  612. package/dist/repertoire/mcp-write-guard.js +85 -0
  613. package/dist/repertoire/plugin-mcp.js +175 -0
  614. package/dist/repertoire/plugins.js +253 -0
  615. package/dist/repertoire/relationship-authorization.js +322 -0
  616. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  617. package/dist/repertoire/shell-sessions.js +136 -0
  618. package/dist/repertoire/skill-search.js +177 -0
  619. package/dist/repertoire/skill-summaries.js +129 -0
  620. package/dist/repertoire/skills.js +34 -4
  621. package/dist/repertoire/stripe-client.js +163 -0
  622. package/dist/repertoire/tool-arguments.js +180 -0
  623. package/dist/repertoire/tool-candidates.js +50 -0
  624. package/dist/repertoire/tool-catalog.js +228 -0
  625. package/dist/repertoire/tool-error-code.js +30 -0
  626. package/dist/repertoire/tool-limits.js +20 -0
  627. package/dist/repertoire/tool-results.js +29 -0
  628. package/dist/repertoire/tools-a2a.js +792 -0
  629. package/dist/repertoire/tools-app-sessions.js +219 -0
  630. package/dist/repertoire/tools-attachments.js +302 -0
  631. package/dist/repertoire/tools-awaiting.js +934 -0
  632. package/dist/repertoire/tools-base.js +85 -1420
  633. package/dist/repertoire/tools-bridge.js +153 -0
  634. package/dist/repertoire/tools-bundle.js +998 -0
  635. package/dist/repertoire/tools-chat.js +185 -0
  636. package/dist/repertoire/tools-commerce.js +272 -0
  637. package/dist/repertoire/tools-config.js +199 -0
  638. package/dist/repertoire/tools-continuity.js +648 -0
  639. package/dist/repertoire/tools-credential.js +410 -0
  640. package/dist/repertoire/tools-escalation.js +98 -0
  641. package/dist/repertoire/tools-evolution.js +560 -0
  642. package/dist/repertoire/tools-files.js +521 -0
  643. package/dist/repertoire/tools-flight.js +313 -0
  644. package/dist/repertoire/tools-flow.js +169 -0
  645. package/dist/repertoire/tools-friend-link.js +65 -0
  646. package/dist/repertoire/tools-github.js +11 -4
  647. package/dist/repertoire/tools-habits.js +111 -0
  648. package/dist/repertoire/tools-house-care.js +190 -0
  649. package/dist/repertoire/tools-mail.js +1928 -0
  650. package/dist/repertoire/tools-notes.js +571 -0
  651. package/dist/repertoire/tools-obligations.js +187 -0
  652. package/dist/repertoire/tools-orientation.js +36 -0
  653. package/dist/repertoire/tools-record.js +497 -0
  654. package/dist/repertoire/tools-rsvp.js +148 -0
  655. package/dist/repertoire/tools-runtime.js +260 -0
  656. package/dist/repertoire/tools-sanctuary-host.js +213 -0
  657. package/dist/repertoire/tools-session.js +1198 -0
  658. package/dist/repertoire/tools-shell.js +275 -0
  659. package/dist/repertoire/tools-shepherd-guidance.js +183 -0
  660. package/dist/repertoire/tools-shepherd.js +369 -0
  661. package/dist/repertoire/tools-steward-policy.js +157 -0
  662. package/dist/repertoire/tools-stripe.js +244 -0
  663. package/dist/repertoire/tools-surface.js +557 -0
  664. package/dist/repertoire/tools-teams.js +67 -17
  665. package/dist/repertoire/tools-telegram-contacts.js +41 -0
  666. package/dist/repertoire/tools-travel.js +142 -0
  667. package/dist/repertoire/tools-trip.js +1041 -0
  668. package/dist/repertoire/tools-unraid.js +627 -0
  669. package/dist/repertoire/tools-user-profile.js +166 -0
  670. package/dist/repertoire/tools-vault.js +46 -0
  671. package/dist/repertoire/tools-voice-local.js +210 -0
  672. package/dist/repertoire/tools-voice.js +153 -0
  673. package/dist/repertoire/tools-web.js +238 -0
  674. package/dist/repertoire/tools.js +614 -288
  675. package/dist/repertoire/travel-api-client.js +463 -0
  676. package/dist/repertoire/unraid-client.js +155 -0
  677. package/dist/repertoire/unraid-restart.js +342 -0
  678. package/dist/repertoire/user-profile.js +131 -0
  679. package/dist/repertoire/vault-setup.js +298 -0
  680. package/dist/repertoire/vault-unlock.js +816 -0
  681. package/dist/rsvp/aisleplanner-client.js +354 -0
  682. package/dist/rsvp/cli.js +936 -0
  683. package/dist/rsvp/config.js +327 -0
  684. package/dist/rsvp/cutover.js +453 -0
  685. package/dist/rsvp/diagnostics.js +232 -0
  686. package/dist/rsvp/diff-renderer.js +176 -0
  687. package/dist/rsvp/habit-policy.js +109 -0
  688. package/dist/rsvp/habit-stage.js +122 -0
  689. package/dist/rsvp/incident-bundle.js +97 -0
  690. package/dist/rsvp/migration.js +204 -0
  691. package/dist/rsvp/native-habit-runner.js +621 -0
  692. package/dist/rsvp/outbound-state.js +628 -0
  693. package/dist/rsvp/query.js +118 -0
  694. package/dist/rsvp/replay.js +233 -0
  695. package/dist/rsvp/snapshot.js +232 -0
  696. package/dist/rsvp/spend-ledger.js +175 -0
  697. package/dist/scripts/claude-code-stop-hook.js +4 -3
  698. package/dist/senses/a2a-entry.js +145 -0
  699. package/dist/senses/acp-server.js +386 -0
  700. package/dist/senses/app-sessions/client.js +128 -0
  701. package/dist/senses/app-sessions/digest-cards.js +263 -0
  702. package/dist/senses/app-sessions/digest-push.js +108 -0
  703. package/dist/senses/app-sessions/digest-sources.js +204 -0
  704. package/dist/senses/app-sessions/digest.js +284 -0
  705. package/dist/senses/app-sessions/run-command.js +51 -0
  706. package/dist/senses/app-sessions/sense.js +242 -0
  707. package/dist/senses/app-sessions/shepherd-cli.js +166 -0
  708. package/dist/senses/app-sessions/shepherd-rows.js +67 -0
  709. package/dist/senses/app-sessions/store.js +149 -0
  710. package/dist/senses/app-sessions/waiting-prompts.js +137 -0
  711. package/dist/senses/app-sessions/waiting-status.js +23 -0
  712. package/dist/senses/app-sessions-entry.js +87 -0
  713. package/dist/senses/attention-queue.js +95 -6
  714. package/dist/senses/await-turn-message.js +65 -0
  715. package/dist/senses/bluebubbles/active-turns.js +241 -0
  716. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  717. package/dist/senses/bluebubbles/attachment-download.js +143 -0
  718. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +391 -49
  719. package/dist/senses/bluebubbles/context-packet.js +207 -0
  720. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  721. package/dist/senses/bluebubbles/entry.js +80 -0
  722. package/dist/senses/bluebubbles/host-account-verifier.js +113 -0
  723. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  724. package/dist/senses/bluebubbles/index.js +4666 -0
  725. package/dist/senses/bluebubbles/latest-turn.js +342 -0
  726. package/dist/senses/bluebubbles/media.js +255 -0
  727. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +152 -30
  728. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  729. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  730. package/dist/senses/bluebubbles/processed-log.js +133 -0
  731. package/dist/senses/bluebubbles/reactions.js +18 -0
  732. package/dist/senses/bluebubbles/replay.js +284 -0
  733. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +47 -4
  734. package/dist/senses/bluebubbles/semantic-receipts.js +2014 -0
  735. package/dist/senses/bluebubbles/send-file.js +20 -0
  736. package/dist/senses/bluebubbles/send-health.js +126 -0
  737. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  738. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  739. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  740. package/dist/senses/chat-file.js +75 -0
  741. package/dist/senses/cli/bracketed-paste.js +82 -0
  742. package/dist/senses/cli/image-paste.js +287 -0
  743. package/dist/senses/cli/image-ref-navigation.js +75 -0
  744. package/dist/senses/cli/ink-app.js +156 -0
  745. package/dist/senses/cli/inline-diff.js +64 -0
  746. package/dist/senses/cli/input-keys.js +209 -0
  747. package/dist/senses/cli/kill-ring.js +86 -0
  748. package/dist/senses/cli/message-list.js +51 -0
  749. package/dist/senses/cli/ouro-tui.js +633 -0
  750. package/dist/senses/cli/spinner-imperative.js +135 -0
  751. package/dist/senses/cli/spinner.js +101 -0
  752. package/dist/senses/cli/status-line.js +60 -0
  753. package/dist/senses/cli/streaming-markdown.js +526 -0
  754. package/dist/senses/cli/tool-display.js +85 -0
  755. package/dist/senses/cli/tool-render.js +85 -0
  756. package/dist/senses/cli/tui-store.js +252 -0
  757. package/dist/senses/cli/virtual-list.js +35 -0
  758. package/dist/senses/cli-entry.js +62 -9
  759. package/dist/senses/cli.js +625 -370
  760. package/dist/senses/commands.js +29 -3
  761. package/dist/senses/context-packet-ledger.js +367 -0
  762. package/dist/senses/context-packets.js +154 -0
  763. package/dist/senses/habit-lifecycle-guard.js +24 -0
  764. package/dist/senses/habit-turn-message.js +58 -6
  765. package/dist/senses/inbound-journal.js +186 -0
  766. package/dist/senses/ingress-evidence.js +2 -0
  767. package/dist/senses/mail-entry.js +69 -0
  768. package/dist/senses/mail.js +524 -0
  769. package/dist/senses/ordinary-owner-decision.js +98 -0
  770. package/dist/senses/pipeline.js +1223 -296
  771. package/dist/senses/private-runtime-worker.js +820 -0
  772. package/dist/senses/private-runtime.js +1648 -0
  773. package/dist/senses/proactive-content-guard.js +144 -0
  774. package/dist/senses/program-status.js +155 -0
  775. package/dist/senses/repeat-while.js +36 -0
  776. package/dist/senses/reply-gate.js +237 -0
  777. package/dist/senses/root-host-approval-port.js +345 -0
  778. package/dist/senses/root-host-approval-runtime.js +393 -0
  779. package/dist/senses/sanctuary-authority-resident.js +102 -0
  780. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  781. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  782. package/dist/senses/sanctuary-grounding.js +118 -0
  783. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +21 -0
  784. package/dist/senses/sanctuary-health-acceptance-probe.js +802 -0
  785. package/dist/senses/sanctuary-health-runner.js +106 -0
  786. package/dist/senses/sanctuary-health.js +442 -0
  787. package/dist/senses/sanctuary-house.js +97 -0
  788. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  789. package/dist/senses/sanctuary-interactive-control.js +410 -0
  790. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  791. package/dist/senses/sanctuary-media-optimization.js +517 -0
  792. package/dist/senses/sanctuary-runtime.js +392 -0
  793. package/dist/senses/sanctuary-sab.js +85 -0
  794. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  795. package/dist/senses/sense-shutdown.js +72 -0
  796. package/dist/senses/shared-turn.js +741 -97
  797. package/dist/senses/shepherd/agent-presentation.js +88 -0
  798. package/dist/senses/shepherd/attention-page.js +166 -0
  799. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  800. package/dist/senses/shepherd/attention.js +295 -0
  801. package/dist/senses/shepherd/checkin-config.js +76 -0
  802. package/dist/senses/shepherd/checkin-store.js +383 -0
  803. package/dist/senses/shepherd/client.js +196 -0
  804. package/dist/senses/shepherd/cmux.js +483 -0
  805. package/dist/senses/shepherd/composer.js +336 -0
  806. package/dist/senses/shepherd/conversation-hold.js +78 -0
  807. package/dist/senses/shepherd/feedback-reply.js +108 -0
  808. package/dist/senses/shepherd/feedback-source.js +20 -0
  809. package/dist/senses/shepherd/feedback-store.js +328 -0
  810. package/dist/senses/shepherd/feedback-submit.js +182 -0
  811. package/dist/senses/shepherd/feedback-worker.js +208 -0
  812. package/dist/senses/shepherd/guidance.js +273 -0
  813. package/dist/senses/shepherd/herdr.js +427 -0
  814. package/dist/senses/shepherd/host.js +14 -0
  815. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  816. package/dist/senses/shepherd/judge-evaluation-command.js +185 -0
  817. package/dist/senses/shepherd/judge-evaluation-entry.js +20 -0
  818. package/dist/senses/shepherd/judge-evaluation.js +144 -0
  819. package/dist/senses/shepherd/judge.js +210 -0
  820. package/dist/senses/shepherd/notice-outbox.js +254 -0
  821. package/dist/senses/shepherd/observation-publisher.js +320 -0
  822. package/dist/senses/shepherd/operations-defaults.js +86 -0
  823. package/dist/senses/shepherd/operations.js +159 -0
  824. package/dist/senses/shepherd/owner-notice.js +496 -0
  825. package/dist/senses/shepherd/prompt-state.js +60 -0
  826. package/dist/senses/shepherd/recovery.js +543 -0
  827. package/dist/senses/shepherd/redact.js +66 -0
  828. package/dist/senses/shepherd/returns.js +79 -0
  829. package/dist/senses/shepherd/sense.js +862 -0
  830. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  831. package/dist/senses/shepherd/surface.js +125 -0
  832. package/dist/senses/shepherd/target-binding.js +13 -0
  833. package/dist/senses/shepherd/terminal-process.js +147 -0
  834. package/dist/senses/shepherd-entry.js +98 -0
  835. package/dist/senses/surface-tool.js +60 -34
  836. package/dist/senses/teams-attachments.js +68 -0
  837. package/dist/senses/teams-entry.js +80 -9
  838. package/dist/senses/teams-image.js +128 -0
  839. package/dist/senses/teams-inbound.js +76 -0
  840. package/dist/senses/teams-off-turn.js +199 -0
  841. package/dist/senses/teams-outbox.js +249 -0
  842. package/dist/senses/teams.js +1250 -366
  843. package/dist/senses/telegram-admission.js +700 -0
  844. package/dist/senses/telegram-approval-relay.js +293 -0
  845. package/dist/senses/telegram-approval-runtime.js +831 -0
  846. package/dist/senses/telegram-attachments.js +128 -0
  847. package/dist/senses/telegram-audit-ledger.js +220 -0
  848. package/dist/senses/telegram-authority-transport.js +233 -0
  849. package/dist/senses/telegram-chat-actions.js +57 -0
  850. package/dist/senses/telegram-client.js +1896 -0
  851. package/dist/senses/telegram-effect-adapter.js +892 -0
  852. package/dist/senses/telegram-entry.js +87 -0
  853. package/dist/senses/telegram-handoff.js +150 -0
  854. package/dist/senses/telegram-identity-key.js +143 -0
  855. package/dist/senses/telegram-markdown.js +331 -0
  856. package/dist/senses/telegram-owner-route.js +129 -0
  857. package/dist/senses/telegram.js +2789 -0
  858. package/dist/senses/terminal-handoff.js +44 -0
  859. package/dist/senses/trust-gate.js +104 -9
  860. package/dist/senses/turn-attempts.js +171 -0
  861. package/dist/senses/turn-watch.js +268 -0
  862. package/dist/senses/voice/audio-playback.js +237 -0
  863. package/dist/senses/voice/audio-routing.js +119 -0
  864. package/dist/senses/voice/call-auth.js +250 -0
  865. package/dist/senses/voice/elevenlabs.js +202 -0
  866. package/dist/senses/voice/floor-control.js +431 -0
  867. package/dist/senses/voice/floor-controller.js +115 -0
  868. package/dist/senses/voice/golden-path.js +116 -0
  869. package/dist/senses/voice/index.js +29 -0
  870. package/dist/senses/voice/local-audio-control.js +344 -0
  871. package/dist/senses/voice/local-audio-devices.js +516 -0
  872. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  873. package/dist/senses/voice/local-audio-identity.js +103 -0
  874. package/dist/senses/voice/local-audio-join.js +325 -0
  875. package/dist/senses/voice/local-audio-mute.js +199 -0
  876. package/dist/senses/voice/local-audio-notify.js +124 -0
  877. package/dist/senses/voice/local-audio-prompts.js +116 -0
  878. package/dist/senses/voice/local-audio-transport.js +427 -0
  879. package/dist/senses/voice/local-audio.js +281 -0
  880. package/dist/senses/voice/local-media-stream.js +145 -0
  881. package/dist/senses/voice/meeting.js +113 -0
  882. package/dist/senses/voice/outbound.js +190 -0
  883. package/dist/senses/voice/phone.js +33 -0
  884. package/dist/senses/voice/playback.js +139 -0
  885. package/dist/senses/voice/process-guards.js +51 -0
  886. package/dist/senses/voice/realtime-eval.js +496 -0
  887. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  888. package/dist/senses/voice/realtime-trace.js +531 -0
  889. package/dist/senses/voice/realtime-utterances.js +158 -0
  890. package/dist/senses/voice/transcript.js +70 -0
  891. package/dist/senses/voice/turn.js +219 -0
  892. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  893. package/dist/senses/voice/twilio-phone.js +5660 -0
  894. package/dist/senses/voice/types.js +2 -0
  895. package/dist/senses/voice/utterances.js +207 -0
  896. package/dist/senses/voice/whisper.js +153 -0
  897. package/dist/senses/voice-entry.js +84 -0
  898. package/dist/senses/voice-realtime-eval-command.js +99 -0
  899. package/dist/senses/voice-realtime-eval-entry.js +25 -0
  900. package/dist/senses/voice-twilio-entry.js +88 -0
  901. package/dist/trips/core.js +138 -0
  902. package/dist/trips/store.js +265 -0
  903. package/dist/util/frontmatter.js +69 -0
  904. package/node_modules/@ouro.bot/friends/LICENSE +201 -0
  905. package/node_modules/@ouro.bot/friends/README.md +687 -0
  906. package/node_modules/@ouro.bot/friends/actions/generated/mcp.json +1105 -0
  907. package/node_modules/@ouro.bot/friends/changelog.json +197 -0
  908. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.d.ts +39 -0
  909. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.js +54 -0
  910. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +117 -0
  911. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.js +202 -0
  912. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.d.ts +50 -0
  913. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.js +32 -0
  914. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.d.ts +38 -0
  915. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.js +120 -0
  916. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.d.ts +195 -0
  917. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.js +342 -0
  918. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.d.ts +26 -0
  919. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.js +140 -0
  920. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +62 -0
  921. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +83 -0
  922. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.d.ts +26 -0
  923. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.js +82 -0
  924. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.d.ts +5 -0
  925. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.js +84 -0
  926. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.d.ts +22 -0
  927. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.js +17 -0
  928. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.d.ts +15 -0
  929. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.js +61 -0
  930. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.d.ts +47 -0
  931. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.js +95 -0
  932. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.d.ts +58 -0
  933. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.js +113 -0
  934. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.d.ts +42 -0
  935. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.js +87 -0
  936. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.d.ts +5 -0
  937. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.js +19 -0
  938. package/node_modules/@ouro.bot/friends/dist/account-roster.d.ts +52 -0
  939. package/node_modules/@ouro.bot/friends/dist/account-roster.js +108 -0
  940. package/node_modules/@ouro.bot/friends/dist/agent-peer.d.ts +26 -0
  941. package/node_modules/@ouro.bot/friends/dist/agent-peer.js +138 -0
  942. package/node_modules/@ouro.bot/friends/dist/audit.d.ts +42 -0
  943. package/node_modules/@ouro.bot/friends/dist/audit.js +86 -0
  944. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +16 -0
  945. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/channel.js +83 -4
  946. package/node_modules/@ouro.bot/friends/dist/connect-authority.d.ts +43 -0
  947. package/node_modules/@ouro.bot/friends/dist/connect-authority.js +84 -0
  948. package/node_modules/@ouro.bot/friends/dist/connect.d.ts +56 -0
  949. package/node_modules/@ouro.bot/friends/dist/connect.js +163 -0
  950. package/node_modules/@ouro.bot/friends/dist/consent.d.ts +34 -0
  951. package/node_modules/@ouro.bot/friends/dist/consent.js +65 -0
  952. package/node_modules/@ouro.bot/friends/dist/coordination.d.ts +116 -0
  953. package/node_modules/@ouro.bot/friends/dist/coordination.js +329 -0
  954. package/node_modules/@ouro.bot/friends/dist/delegation-grant.d.ts +21 -0
  955. package/node_modules/@ouro.bot/friends/dist/delegation-grant.js +39 -0
  956. package/node_modules/@ouro.bot/friends/dist/file-bundle.d.ts +17 -0
  957. package/node_modules/@ouro.bot/friends/dist/file-bundle.js +27 -0
  958. package/node_modules/@ouro.bot/friends/dist/friend-lookup.d.ts +9 -0
  959. package/node_modules/@ouro.bot/friends/dist/friend-lookup.js +69 -0
  960. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +19 -0
  961. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +157 -0
  962. package/node_modules/@ouro.bot/friends/dist/grant-store.d.ts +7 -0
  963. package/node_modules/@ouro.bot/friends/dist/grant-store.js +8 -0
  964. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +43 -0
  965. package/node_modules/@ouro.bot/friends/dist/grants.js +100 -0
  966. package/node_modules/@ouro.bot/friends/dist/group-context.d.ts +21 -0
  967. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/group-context.js +5 -4
  968. package/node_modules/@ouro.bot/friends/dist/identity.d.ts +17 -0
  969. package/node_modules/@ouro.bot/friends/dist/identity.js +68 -0
  970. package/node_modules/@ouro.bot/friends/dist/index.d.ts +73 -0
  971. package/node_modules/@ouro.bot/friends/dist/index.js +164 -0
  972. package/node_modules/@ouro.bot/friends/dist/link-identity.d.ts +14 -0
  973. package/node_modules/@ouro.bot/friends/dist/link-identity.js +157 -0
  974. package/node_modules/@ouro.bot/friends/dist/mailbox/index.d.ts +105 -0
  975. package/node_modules/@ouro.bot/friends/dist/mailbox/index.js +205 -0
  976. package/node_modules/@ouro.bot/friends/dist/mcp/bin.d.ts +2 -0
  977. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +17 -0
  978. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.d.ts +40 -0
  979. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +744 -0
  980. package/node_modules/@ouro.bot/friends/dist/mcp/index.d.ts +6 -0
  981. package/node_modules/@ouro.bot/friends/dist/mcp/index.js +14 -0
  982. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.d.ts +7 -0
  983. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +59 -0
  984. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.d.ts +10 -0
  985. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +23 -0
  986. package/node_modules/@ouro.bot/friends/dist/mcp/server.d.ts +30 -0
  987. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +195 -0
  988. package/node_modules/@ouro.bot/friends/dist/message.d.ts +93 -0
  989. package/node_modules/@ouro.bot/friends/dist/message.js +129 -0
  990. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +89 -0
  991. package/node_modules/@ouro.bot/friends/dist/mission-result.js +207 -0
  992. package/node_modules/@ouro.bot/friends/dist/mission-share.d.ts +94 -0
  993. package/node_modules/@ouro.bot/friends/dist/mission-share.js +232 -0
  994. package/node_modules/@ouro.bot/friends/dist/mission-store-file.d.ts +18 -0
  995. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +169 -0
  996. package/node_modules/@ouro.bot/friends/dist/mission-store.d.ts +10 -0
  997. package/node_modules/@ouro.bot/friends/dist/mission-store.js +9 -0
  998. package/node_modules/@ouro.bot/friends/dist/missions.d.ts +31 -0
  999. package/node_modules/@ouro.bot/friends/dist/missions.js +99 -0
  1000. package/node_modules/@ouro.bot/friends/dist/notes.d.ts +11 -0
  1001. package/node_modules/@ouro.bot/friends/dist/notes.js +90 -0
  1002. package/node_modules/@ouro.bot/friends/dist/observability.d.ts +27 -0
  1003. package/node_modules/@ouro.bot/friends/dist/observability.js +31 -0
  1004. package/node_modules/@ouro.bot/friends/dist/outcomes.d.ts +9 -0
  1005. package/node_modules/@ouro.bot/friends/dist/outcomes.js +51 -0
  1006. package/node_modules/@ouro.bot/friends/dist/resolver.d.ts +59 -0
  1007. package/node_modules/@ouro.bot/friends/dist/resolver.js +276 -0
  1008. package/node_modules/@ouro.bot/friends/dist/results.d.ts +10 -0
  1009. package/node_modules/@ouro.bot/friends/dist/results.js +2 -0
  1010. package/node_modules/@ouro.bot/friends/dist/room.d.ts +22 -0
  1011. package/node_modules/@ouro.bot/friends/dist/room.js +40 -0
  1012. package/node_modules/@ouro.bot/friends/dist/roster-store-file.d.ts +16 -0
  1013. package/node_modules/@ouro.bot/friends/dist/roster-store-file.js +125 -0
  1014. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.d.ts +9 -0
  1015. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.js +20 -0
  1016. package/node_modules/@ouro.bot/friends/dist/roster-store.d.ts +29 -0
  1017. package/node_modules/@ouro.bot/friends/dist/roster-store.js +9 -0
  1018. package/node_modules/@ouro.bot/friends/dist/roster-verifier.d.ts +23 -0
  1019. package/node_modules/@ouro.bot/friends/dist/roster-verifier.js +47 -0
  1020. package/node_modules/@ouro.bot/friends/dist/share.d.ts +113 -0
  1021. package/node_modules/@ouro.bot/friends/dist/share.js +314 -0
  1022. package/node_modules/@ouro.bot/friends/dist/standing.d.ts +83 -0
  1023. package/node_modules/@ouro.bot/friends/dist/standing.js +111 -0
  1024. package/node_modules/@ouro.bot/friends/dist/store-file.d.ts +82 -0
  1025. package/node_modules/@ouro.bot/friends/dist/store-file.js +1089 -0
  1026. package/node_modules/@ouro.bot/friends/dist/store.d.ts +43 -0
  1027. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +10 -0
  1028. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/tokens.js +7 -4
  1029. package/node_modules/@ouro.bot/friends/dist/trust-explanation.d.ts +22 -0
  1030. package/node_modules/@ouro.bot/friends/dist/trust-explanation.js +90 -0
  1031. package/node_modules/@ouro.bot/friends/dist/trust-mutation.d.ts +16 -0
  1032. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +67 -0
  1033. package/node_modules/@ouro.bot/friends/dist/types.d.ts +333 -0
  1034. package/node_modules/@ouro.bot/friends/dist/types.js +55 -0
  1035. package/node_modules/@ouro.bot/friends/dist/util/cap-string.d.ts +7 -0
  1036. package/node_modules/@ouro.bot/friends/dist/util/cap-string.js +35 -0
  1037. package/node_modules/@ouro.bot/friends/dist/util/safe-id.d.ts +1 -0
  1038. package/node_modules/@ouro.bot/friends/dist/util/safe-id.js +10 -0
  1039. package/node_modules/@ouro.bot/friends/dist/verifier.d.ts +11 -0
  1040. package/node_modules/@ouro.bot/friends/dist/verifier.js +29 -0
  1041. package/node_modules/@ouro.bot/friends/dist/whoami.d.ts +7 -0
  1042. package/node_modules/@ouro.bot/friends/dist/whoami.js +39 -0
  1043. package/node_modules/@ouro.bot/friends/package.json +82 -0
  1044. package/node_modules/libsodium/LICENSE +16 -0
  1045. package/node_modules/libsodium/README.md +281 -0
  1046. package/node_modules/libsodium/dist/modules/libsodium.js +1 -0
  1047. package/node_modules/libsodium/dist/modules-esm/libsodium.mjs +1 -0
  1048. package/node_modules/libsodium/package.json +54 -0
  1049. package/node_modules/libsodium-wrappers/LICENSE +16 -0
  1050. package/node_modules/libsodium-wrappers/README.md +281 -0
  1051. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.d.ts +2155 -0
  1052. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js +1 -0
  1053. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.d.mts +2743 -0
  1054. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.mjs +1 -0
  1055. package/node_modules/libsodium-wrappers/package.json +74 -0
  1056. package/npm-shrinkwrap.json +8789 -0
  1057. package/package.json +97 -12
  1058. package/skills/agent-commerce.md +116 -0
  1059. package/skills/browser-navigation.md +120 -0
  1060. package/skills/commerce-setup-guide.md +116 -0
  1061. package/skills/commerce-setup.md +87 -0
  1062. package/skills/configure-dev-tools.md +32 -14
  1063. package/skills/sense-setup.md +56 -0
  1064. package/skills/travel-planning.md +141 -0
  1065. package/vendor/desk/.claude-plugin/plugin.json +35 -0
  1066. package/vendor/desk/.mcp.claude-codex.json +28 -0
  1067. package/vendor/desk/.mcp.copilot.json +16 -0
  1068. package/vendor/desk/.ouro-desk.json +6 -0
  1069. package/vendor/desk/CHANGELOG.md +7644 -0
  1070. package/vendor/desk/README.md +195 -0
  1071. package/vendor/desk/activation/README.md +98 -0
  1072. package/vendor/desk/activation/copilot-root.flattened-bundle.json +38 -0
  1073. package/vendor/desk/activation/desk.activation.json +251 -0
  1074. package/vendor/desk/activation/host-capability-evidence.md +46 -0
  1075. package/vendor/desk/activation/support-matrix.json +84 -0
  1076. package/vendor/desk/agency.json +20 -0
  1077. package/vendor/desk/agents/observer.agent.md +26 -0
  1078. package/vendor/desk/agents/observer.md +29 -0
  1079. package/vendor/desk/agents/worker.agent.md +32 -0
  1080. package/vendor/desk/agents/worker.md +40 -0
  1081. package/vendor/desk/artifacts/tombstones/tombstone.schema.json +53 -0
  1082. package/vendor/desk/artifacts/tombstones/tombstones.jsonl +1 -0
  1083. package/vendor/desk/changelog.d/README.md +12 -0
  1084. package/vendor/desk/docs/agent-files.md +104 -0
  1085. package/vendor/desk/docs/agentic-engineering-v2-rfc.md +206 -0
  1086. package/vendor/desk/docs/agentic-engineering-v3-rfc.md +109 -0
  1087. package/vendor/desk/docs/browser-remote-desktops.md +69 -0
  1088. package/vendor/desk/docs/dependency-activation-stories-and-criteria.md +500 -0
  1089. package/vendor/desk/docs/evaluation-packet.md +363 -0
  1090. package/vendor/desk/docs/factory-local-capture.md +651 -0
  1091. package/vendor/desk/docs/factory-store-playbook.md +927 -0
  1092. package/vendor/desk/docs/images/factory-site.png +0 -0
  1093. package/vendor/desk/docs/issue-drains.md +81 -0
  1094. package/vendor/desk/docs/lfs-inspection.md +55 -0
  1095. package/vendor/desk/docs/preview-diagnostics.md +11 -0
  1096. package/vendor/desk/docs/relays.md +88 -0
  1097. package/vendor/desk/docs/schedules.md +69 -0
  1098. package/vendor/desk/docs/search-recovery.md +22 -0
  1099. package/vendor/desk/docs/session-labels.md +157 -0
  1100. package/vendor/desk/docs/session-retention.md +125 -0
  1101. package/vendor/desk/docs/sessions.md +17 -0
  1102. package/vendor/desk/docs/stalled-nudges.md +54 -0
  1103. package/vendor/desk/docs/webhooks.md +80 -0
  1104. package/vendor/desk/docs/workspace-tidy.md +74 -0
  1105. package/vendor/desk/hooks/boot-checks.cjs +7 -0
  1106. package/vendor/desk/hooks/claude-session-start.cjs +123 -0
  1107. package/vendor/desk/hooks/compatible-node.cjs +97 -0
  1108. package/vendor/desk/hooks/copilot-boot-prompt.cjs +69 -0
  1109. package/vendor/desk/hooks/copilot-durable-files.cjs +8 -0
  1110. package/vendor/desk/hooks/copilot-hooks.json +61 -0
  1111. package/vendor/desk/hooks/copilot-intake-context.cjs +5 -0
  1112. package/vendor/desk/hooks/copilot-lane-model.cjs +8 -0
  1113. package/vendor/desk/hooks/copilot-session-start.cjs +264 -0
  1114. package/vendor/desk/hooks/copilot-skill-current.cjs +28 -0
  1115. package/vendor/desk/hooks/factory-end.cjs +5 -0
  1116. package/vendor/desk/hooks/factory-start.cjs +27 -0
  1117. package/vendor/desk/hooks/hooks.json +40 -0
  1118. package/vendor/desk/hooks/lib/boot-checks.cjs +643 -0
  1119. package/vendor/desk/hooks/lib/child-agent.cjs +14 -0
  1120. package/vendor/desk/hooks/lib/copilot-intake-context.cjs +73 -0
  1121. package/vendor/desk/hooks/lib/current-release.cjs +162 -0
  1122. package/vendor/desk/hooks/lib/delivery-stop.cjs +326 -0
  1123. package/vendor/desk/hooks/lib/detach-worker.cjs +43 -0
  1124. package/vendor/desk/hooks/lib/durable-files.cjs +102 -0
  1125. package/vendor/desk/hooks/lib/factory-end.cjs +330 -0
  1126. package/vendor/desk/hooks/lib/lane-model.cjs +82 -0
  1127. package/vendor/desk/hooks/lib/node-required.cjs +56 -0
  1128. package/vendor/desk/hooks/lib/orca-session-title.cjs +60 -0
  1129. package/vendor/desk/hooks/lib/session-end.cjs +30 -0
  1130. package/vendor/desk/hooks/lib/sync-end.cjs +89 -0
  1131. package/vendor/desk/hooks/loop-start.cjs +105 -0
  1132. package/vendor/desk/hooks/node-missing.sh +78 -0
  1133. package/vendor/desk/hooks/orca-session-title.cjs +8 -0
  1134. package/vendor/desk/hooks/session-end.cjs +8 -0
  1135. package/vendor/desk/mcp/README.md +277 -0
  1136. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1137. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1138. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1139. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1140. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1141. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/darwin-arm64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1142. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1143. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1144. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-127/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1145. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1146. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1147. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1148. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1149. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1150. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/linux-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1151. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/support-matrix.json +72 -0
  1152. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1153. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1154. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-137/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1155. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.manifest.json +881 -0
  1156. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.sha256 +1 -0
  1157. package/vendor/desk/mcp/artifacts/runtime-deps/1.4.0-alpha.6/win32-x64-node-147/3b0cb8b1e7dd77a982b38375fe88a5278bd77974213e18be025d7dc8deea800f/runtime-deps.tgz +0 -0
  1158. package/vendor/desk/mcp/artifacts/runtime-deps/README.md +25 -0
  1159. package/vendor/desk/mcp/bootstrap.cjs +787 -0
  1160. package/vendor/desk/mcp/docs/private-feedback.md +13 -0
  1161. package/vendor/desk/mcp/idle-proxy.cjs +431 -0
  1162. package/vendor/desk/mcp/index.js +813 -0
  1163. package/vendor/desk/mcp/package-lock.json +3717 -0
  1164. package/vendor/desk/mcp/package.json +44 -0
  1165. package/vendor/desk/mcp/scripts/agency-desk-channel.js +7 -0
  1166. package/vendor/desk/mcp/scripts/build-runtime-deps-pack.js +5 -0
  1167. package/vendor/desk/mcp/scripts/crew.js +89 -0
  1168. package/vendor/desk/mcp/scripts/drains-launcher.mjs +330 -0
  1169. package/vendor/desk/mcp/scripts/drains.js +5 -0
  1170. package/vendor/desk/mcp/scripts/factory.js +666 -0
  1171. package/vendor/desk/mcp/scripts/file-desk-problem.js +9 -0
  1172. package/vendor/desk/mcp/scripts/finish-commit.js +7 -0
  1173. package/vendor/desk/mcp/scripts/lfs.js +37 -0
  1174. package/vendor/desk/mcp/scripts/local-recovery.js +445 -0
  1175. package/vendor/desk/mcp/scripts/migrations.js +11 -0
  1176. package/vendor/desk/mcp/scripts/private-view.js +177 -0
  1177. package/vendor/desk/mcp/scripts/resolve-desk-root.js +105 -0
  1178. package/vendor/desk/mcp/scripts/session-boot.js +22 -0
  1179. package/vendor/desk/mcp/scripts/session-retention.js +5 -0
  1180. package/vendor/desk/mcp/scripts/session-sync.js +10 -0
  1181. package/vendor/desk/mcp/scripts/sessions.js +5 -0
  1182. package/vendor/desk/mcp/scripts/sync-push.js +13 -0
  1183. package/vendor/desk/mcp/scripts/tidy-status.js +8 -0
  1184. package/vendor/desk/mcp/scripts/verify-runtime-deps-pack.js +5 -0
  1185. package/vendor/desk/mcp/src/actions/desk-read.actions.mts +73 -0
  1186. package/vendor/desk/mcp/src/actions/desk-session.actions.mts +57 -0
  1187. package/vendor/desk/mcp/src/actions/desk-web.actions.mts +52 -0
  1188. package/vendor/desk/mcp/src/actions/desk.actions.mts +5 -0
  1189. package/vendor/desk/mcp/src/actions/generated/desk/OuroActions.swift +649 -0
  1190. package/vendor/desk/mcp/src/actions/generated/desk/OuroActionsReins.swift +61 -0
  1191. package/vendor/desk/mcp/src/actions/generated/desk/actions.json +315 -0
  1192. package/vendor/desk/mcp/src/actions/generated/desk/commands.json +145 -0
  1193. package/vendor/desk/mcp/src/actions/generated/desk/mcp.json +289 -0
  1194. package/vendor/desk/mcp/src/actions/generated/desk/web.ts +59 -0
  1195. package/vendor/desk/mcp/src/actions/generated/desk/webmcp.json +250 -0
  1196. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActions.swift +241 -0
  1197. package/vendor/desk/mcp/src/actions/generated/desk-web/OuroActionsReins.swift +25 -0
  1198. package/vendor/desk/mcp/src/actions/generated/desk-web/actions.json +73 -0
  1199. package/vendor/desk/mcp/src/actions/generated/desk-web/commands.json +53 -0
  1200. package/vendor/desk/mcp/src/actions/generated/desk-web/mcp.json +83 -0
  1201. package/vendor/desk/mcp/src/actions/generated/desk-web/web.ts +47 -0
  1202. package/vendor/desk/mcp/src/actions/generated/desk-web/webmcp.json +81 -0
  1203. package/vendor/desk/mcp/src/actions/served.js +5 -0
  1204. package/vendor/desk/mcp/src/activation/admit.js +77 -0
  1205. package/vendor/desk/mcp/src/activation/failures.js +65 -0
  1206. package/vendor/desk/mcp/src/activation/readiness-policy.js +102 -0
  1207. package/vendor/desk/mcp/src/activation/schema.js +17 -0
  1208. package/vendor/desk/mcp/src/activation/superpowers-context.js +274 -0
  1209. package/vendor/desk/mcp/src/activation/validate.js +540 -0
  1210. package/vendor/desk/mcp/src/artifacts/tombstones.js +61 -0
  1211. package/vendor/desk/mcp/src/crew/initiative.js +287 -0
  1212. package/vendor/desk/mcp/src/crew/workspace.js +1285 -0
  1213. package/vendor/desk/mcp/src/db/init.js +75 -0
  1214. package/vendor/desk/mcp/src/db/schema.sql +83 -0
  1215. package/vendor/desk/mcp/src/desk/active-tasks.js +408 -0
  1216. package/vendor/desk/mcp/src/desk/card-commit-guard.js +282 -0
  1217. package/vendor/desk/mcp/src/desk/cleanup-index.js +53 -0
  1218. package/vendor/desk/mcp/src/desk/content-home.js +262 -0
  1219. package/vendor/desk/mcp/src/desk/crew-config.js +102 -0
  1220. package/vendor/desk/mcp/src/desk/crew-member.js +196 -0
  1221. package/vendor/desk/mcp/src/desk/crew-roster.js +151 -0
  1222. package/vendor/desk/mcp/src/desk/frontmatter-lite.js +228 -0
  1223. package/vendor/desk/mcp/src/desk/gh-logins.js +109 -0
  1224. package/vendor/desk/mcp/src/desk/handles.js +123 -0
  1225. package/vendor/desk/mcp/src/desk/handoff-reference.js +35 -0
  1226. package/vendor/desk/mcp/src/desk/improvement-authority.js +3 -0
  1227. package/vendor/desk/mcp/src/desk/improvement-cards.js +704 -0
  1228. package/vendor/desk/mcp/src/desk/improvement-person.js +51 -0
  1229. package/vendor/desk/mcp/src/desk/lifecycle.js +16 -0
  1230. package/vendor/desk/mcp/src/desk/machine-desks.js +119 -0
  1231. package/vendor/desk/mcp/src/desk/naming.js +333 -0
  1232. package/vendor/desk/mcp/src/desk/organization.js +592 -0
  1233. package/vendor/desk/mcp/src/desk/resources.js +274 -0
  1234. package/vendor/desk/mcp/src/desk/runtime-resolver.js +30 -0
  1235. package/vendor/desk/mcp/src/desk/scratch-paths.js +44 -0
  1236. package/vendor/desk/mcp/src/desk/step-delivery.js +140 -0
  1237. package/vendor/desk/mcp/src/desk/steps.js +263 -0
  1238. package/vendor/desk/mcp/src/desk/tidy.js +930 -0
  1239. package/vendor/desk/mcp/src/desk/unsigned-deliveries.js +359 -0
  1240. package/vendor/desk/mcp/src/factory/agent-types.js +45 -0
  1241. package/vendor/desk/mcp/src/factory/andon-watch.js +109 -0
  1242. package/vendor/desk/mcp/src/factory/binding.js +612 -0
  1243. package/vendor/desk/mcp/src/factory/boot-check.js +645 -0
  1244. package/vendor/desk/mcp/src/factory/capture-classify.js +158 -0
  1245. package/vendor/desk/mcp/src/factory/capture-count.js +183 -0
  1246. package/vendor/desk/mcp/src/factory/capture-flush.js +268 -0
  1247. package/vendor/desk/mcp/src/factory/capture-publish.js +141 -0
  1248. package/vendor/desk/mcp/src/factory/capture-schema.js +193 -0
  1249. package/vendor/desk/mcp/src/factory/capture-sweep.js +239 -0
  1250. package/vendor/desk/mcp/src/factory/catch-point.js +60 -0
  1251. package/vendor/desk/mcp/src/factory/commit-resolve.js +94 -0
  1252. package/vendor/desk/mcp/src/factory/consent-answer.js +37 -0
  1253. package/vendor/desk/mcp/src/factory/context-capability.js +15 -0
  1254. package/vendor/desk/mcp/src/factory/context-outbox.js +885 -0
  1255. package/vendor/desk/mcp/src/factory/context-run.js +386 -0
  1256. package/vendor/desk/mcp/src/factory/context-schema.js +249 -0
  1257. package/vendor/desk/mcp/src/factory/copilot-turn-index.js +93 -0
  1258. package/vendor/desk/mcp/src/factory/copilot-usage.js +148 -0
  1259. package/vendor/desk/mcp/src/factory/credential.js +45 -0
  1260. package/vendor/desk/mcp/src/factory/derive-claude.js +960 -0
  1261. package/vendor/desk/mcp/src/factory/derive-codex.js +734 -0
  1262. package/vendor/desk/mcp/src/factory/derive-common.js +279 -0
  1263. package/vendor/desk/mcp/src/factory/derive-copilot.js +1057 -0
  1264. package/vendor/desk/mcp/src/factory/derive-run.js +807 -0
  1265. package/vendor/desk/mcp/src/factory/desk-problem-file.js +310 -0
  1266. package/vendor/desk/mcp/src/factory/desk-problem-fingerprint.js +70 -0
  1267. package/vendor/desk/mcp/src/factory/desk-problem-known.js +246 -0
  1268. package/vendor/desk/mcp/src/factory/desk-problem-template.js +107 -0
  1269. package/vendor/desk/mcp/src/factory/desk-repo.js +1223 -0
  1270. package/vendor/desk/mcp/src/factory/desk-task-line.js +28 -0
  1271. package/vendor/desk/mcp/src/factory/desk-visibility.js +48 -0
  1272. package/vendor/desk/mcp/src/factory/end-hook.js +14 -0
  1273. package/vendor/desk/mcp/src/factory/evaluate-kick.js +164 -0
  1274. package/vendor/desk/mcp/src/factory/evaluate-run.js +678 -0
  1275. package/vendor/desk/mcp/src/factory/evaluator-step.js +484 -0
  1276. package/vendor/desk/mcp/src/factory/filer-launch.js +79 -0
  1277. package/vendor/desk/mcp/src/factory/flush-health.js +26 -0
  1278. package/vendor/desk/mcp/src/factory/flush.js +1758 -0
  1279. package/vendor/desk/mcp/src/factory/focus.js +326 -0
  1280. package/vendor/desk/mcp/src/factory/headless-flag.cjs +32 -0
  1281. package/vendor/desk/mcp/src/factory/headless-flag.js +25 -0
  1282. package/vendor/desk/mcp/src/factory/headless-ledger.js +743 -0
  1283. package/vendor/desk/mcp/src/factory/headless.js +567 -0
  1284. package/vendor/desk/mcp/src/factory/held-route.js +93 -0
  1285. package/vendor/desk/mcp/src/factory/host-flags.js +36 -0
  1286. package/vendor/desk/mcp/src/factory/improvement-verify.js +429 -0
  1287. package/vendor/desk/mcp/src/factory/kaizen-file.js +231 -0
  1288. package/vendor/desk/mcp/src/factory/label-binding.js +90 -0
  1289. package/vendor/desk/mcp/src/factory/label-schema.js +426 -0
  1290. package/vendor/desk/mcp/src/factory/local-status.js +368 -0
  1291. package/vendor/desk/mcp/src/factory/loop-conditions.js +121 -0
  1292. package/vendor/desk/mcp/src/factory/loop-health.js +500 -0
  1293. package/vendor/desk/mcp/src/factory/loop-slot.js +90 -0
  1294. package/vendor/desk/mcp/src/factory/loop-status.js +100 -0
  1295. package/vendor/desk/mcp/src/factory/loop-switch.cjs +14 -0
  1296. package/vendor/desk/mcp/src/factory/loop-worker-state.js +96 -0
  1297. package/vendor/desk/mcp/src/factory/loop-worker.js +290 -0
  1298. package/vendor/desk/mcp/src/factory/marker.js +61 -0
  1299. package/vendor/desk/mcp/src/factory/mirror-step.js +145 -0
  1300. package/vendor/desk/mcp/src/factory/os-protect.js +243 -0
  1301. package/vendor/desk/mcp/src/factory/outbox.js +2231 -0
  1302. package/vendor/desk/mcp/src/factory/outcome.js +431 -0
  1303. package/vendor/desk/mcp/src/factory/pipeline/andon.js +319 -0
  1304. package/vendor/desk/mcp/src/factory/pipeline/attention-rollup.js +158 -0
  1305. package/vendor/desk/mcp/src/factory/pipeline/attention.js +146 -0
  1306. package/vendor/desk/mcp/src/factory/pipeline/build.js +299 -0
  1307. package/vendor/desk/mcp/src/factory/pipeline/compare.js +148 -0
  1308. package/vendor/desk/mcp/src/factory/pipeline/formulas.js +652 -0
  1309. package/vendor/desk/mcp/src/factory/pipeline/kaizen.js +387 -0
  1310. package/vendor/desk/mcp/src/factory/pipeline/lifecycle-clocks.js +345 -0
  1311. package/vendor/desk/mcp/src/factory/pipeline/normalize.js +73 -0
  1312. package/vendor/desk/mcp/src/factory/pipeline/number-states.js +154 -0
  1313. package/vendor/desk/mcp/src/factory/pipeline/outcomes.js +268 -0
  1314. package/vendor/desk/mcp/src/factory/pipeline/report.js +737 -0
  1315. package/vendor/desk/mcp/src/factory/pipeline/rollups.js +883 -0
  1316. package/vendor/desk/mcp/src/factory/pipeline/stretches.js +523 -0
  1317. package/vendor/desk/mcp/src/factory/pipeline/timeline.js +199 -0
  1318. package/vendor/desk/mcp/src/factory/pipeline/validate-pr.js +238 -0
  1319. package/vendor/desk/mcp/src/factory/pipeline/versions.js +42 -0
  1320. package/vendor/desk/mcp/src/factory/pipeline/walk.js +1177 -0
  1321. package/vendor/desk/mcp/src/factory/plugin-registry.js +72 -0
  1322. package/vendor/desk/mcp/src/factory/plugin-sources.cjs +249 -0
  1323. package/vendor/desk/mcp/src/factory/pr-green.js +77 -0
  1324. package/vendor/desk/mcp/src/factory/process-lock.js +142 -0
  1325. package/vendor/desk/mcp/src/factory/proof-session.js +75 -0
  1326. package/vendor/desk/mcp/src/factory/publish.js +637 -0
  1327. package/vendor/desk/mcp/src/factory/published-schema.js +648 -0
  1328. package/vendor/desk/mcp/src/factory/reconcile-reasons.js +22 -0
  1329. package/vendor/desk/mcp/src/factory/reconcile-step.js +251 -0
  1330. package/vendor/desk/mcp/src/factory/reconcile.js +808 -0
  1331. package/vendor/desk/mcp/src/factory/release-version.js +134 -0
  1332. package/vendor/desk/mcp/src/factory/repo-name.js +13 -0
  1333. package/vendor/desk/mcp/src/factory/retention.js +60 -0
  1334. package/vendor/desk/mcp/src/factory/route-desk.js +40 -0
  1335. package/vendor/desk/mcp/src/factory/route-issues.js +251 -0
  1336. package/vendor/desk/mcp/src/factory/route-local.js +264 -0
  1337. package/vendor/desk/mcp/src/factory/schema.js +957 -0
  1338. package/vendor/desk/mcp/src/factory/session-kind.js +16 -0
  1339. package/vendor/desk/mcp/src/factory/session-lifetime.js +56 -0
  1340. package/vendor/desk/mcp/src/factory/session-route.js +183 -0
  1341. package/vendor/desk/mcp/src/factory/shell-git.js +500 -0
  1342. package/vendor/desk/mcp/src/factory/store-issues.js +143 -0
  1343. package/vendor/desk/mcp/src/factory/store-route.js +208 -0
  1344. package/vendor/desk/mcp/src/factory/test-state-guard.js +103 -0
  1345. package/vendor/desk/mcp/src/factory/time.js +36 -0
  1346. package/vendor/desk/mcp/src/factory/tool-issue-file.js +84 -0
  1347. package/vendor/desk/mcp/src/factory/tool-kinds.js +87 -0
  1348. package/vendor/desk/mcp/src/factory/triage-schema.js +233 -0
  1349. package/vendor/desk/mcp/src/factory/windows-acl.js +679 -0
  1350. package/vendor/desk/mcp/src/indexer/chunk.js +232 -0
  1351. package/vendor/desk/mcp/src/indexer/discover.js +442 -0
  1352. package/vendor/desk/mcp/src/indexer/exclusions.js +247 -0
  1353. package/vendor/desk/mcp/src/indexer/index.js +167 -0
  1354. package/vendor/desk/mcp/src/indexer/refs.js +0 -0
  1355. package/vendor/desk/mcp/src/indexer/text-hash.js +18 -0
  1356. package/vendor/desk/mcp/src/lib/ouro-actions/actions.claims.json +75 -0
  1357. package/vendor/desk/mcp/src/lib/ouro-actions/dist-manifest.json +70 -0
  1358. package/vendor/desk/mcp/src/lib/ouro-actions/ouro-actions.mts +1416 -0
  1359. package/vendor/desk/mcp/src/lib/ouro-ui/LICENSE +21 -0
  1360. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-claims.ts +191 -0
  1361. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-command.ts +1040 -0
  1362. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/checks.ts +343 -0
  1363. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/cli.ts +240 -0
  1364. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/component.ts +430 -0
  1365. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/dev-commands.ts +204 -0
  1366. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/doctor.ts +126 -0
  1367. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/effects.ts +68 -0
  1368. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/exit-codes.ts +75 -0
  1369. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/help.ts +220 -0
  1370. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/mcp.ts +268 -0
  1371. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/outcome.ts +265 -0
  1372. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/output.ts +67 -0
  1373. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/precise-copy.ts +235 -0
  1374. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/problem.ts +124 -0
  1375. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.kit.mts +8 -0
  1376. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/surfaces.ts +568 -0
  1377. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/terminal.ts +245 -0
  1378. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/voice.ts +136 -0
  1379. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/wait.ts +226 -0
  1380. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/work-event.ts +181 -0
  1381. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.kit.mts +18 -0
  1382. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.ts +2110 -0
  1383. package/vendor/desk/mcp/src/package-metadata.js +20 -0
  1384. package/vendor/desk/mcp/src/protected/legacy-ledger.js +55 -0
  1385. package/vendor/desk/mcp/src/readiness/leftovers.js +75 -0
  1386. package/vendor/desk/mcp/src/readiness/process-start.js +149 -0
  1387. package/vendor/desk/mcp/src/runtime/admission-worker.js +194 -0
  1388. package/vendor/desk/mcp/src/runtime/admission.js +177 -0
  1389. package/vendor/desk/mcp/src/runtime/agency-desk-channel.js +342 -0
  1390. package/vendor/desk/mcp/src/runtime/agents-md.js +62 -0
  1391. package/vendor/desk/mcp/src/runtime/append-lane.js +68 -0
  1392. package/vendor/desk/mcp/src/runtime/argv-safe-reason.js +55 -0
  1393. package/vendor/desk/mcp/src/runtime/boot-dependencies.js +75 -0
  1394. package/vendor/desk/mcp/src/runtime/boot-text.js +504 -0
  1395. package/vendor/desk/mcp/src/runtime/boot.js +1676 -0
  1396. package/vendor/desk/mcp/src/runtime/bootstrap.js +1455 -0
  1397. package/vendor/desk/mcp/src/runtime/chunked-import.js +102 -0
  1398. package/vendor/desk/mcp/src/runtime/copilot-commit-trailer.js +133 -0
  1399. package/vendor/desk/mcp/src/runtime/copilot-session.js +155 -0
  1400. package/vendor/desk/mcp/src/runtime/deliver.js +506 -0
  1401. package/vendor/desk/mcp/src/runtime/desk-channel.js +86 -0
  1402. package/vendor/desk/mcp/src/runtime/desk-failure.js +26 -0
  1403. package/vendor/desk/mcp/src/runtime/desk-health.js +168 -0
  1404. package/vendor/desk/mcp/src/runtime/desk-session.js +1451 -0
  1405. package/vendor/desk/mcp/src/runtime/diagnostic-server.js +72 -0
  1406. package/vendor/desk/mcp/src/runtime/diagnostics.js +241 -0
  1407. package/vendor/desk/mcp/src/runtime/drains-cli.js +195 -0
  1408. package/vendor/desk/mcp/src/runtime/drains.js +1220 -0
  1409. package/vendor/desk/mcp/src/runtime/elsewhere-note.js +9 -0
  1410. package/vendor/desk/mcp/src/runtime/failure-evidence.js +21 -0
  1411. package/vendor/desk/mcp/src/runtime/fast-refs.js +209 -0
  1412. package/vendor/desk/mcp/src/runtime/filer-throttle.js +66 -0
  1413. package/vendor/desk/mcp/src/runtime/focused-card.js +147 -0
  1414. package/vendor/desk/mcp/src/runtime/front-door.js +204 -0
  1415. package/vendor/desk/mcp/src/runtime/gate-wait.js +2 -0
  1416. package/vendor/desk/mcp/src/runtime/git-inspection.js +201 -0
  1417. package/vendor/desk/mcp/src/runtime/git-read-worker.js +157 -0
  1418. package/vendor/desk/mcp/src/runtime/health.js +50 -0
  1419. package/vendor/desk/mcp/src/runtime/hooks.js +353 -0
  1420. package/vendor/desk/mcp/src/runtime/hosted.js +165 -0
  1421. package/vendor/desk/mcp/src/runtime/inbox.js +102 -0
  1422. package/vendor/desk/mcp/src/runtime/index-drift.js +118 -0
  1423. package/vendor/desk/mcp/src/runtime/last-start.js +133 -0
  1424. package/vendor/desk/mcp/src/runtime/lesson-section.js +92 -0
  1425. package/vendor/desk/mcp/src/runtime/lessons-shelf.js +100 -0
  1426. package/vendor/desk/mcp/src/runtime/lfs.js +319 -0
  1427. package/vendor/desk/mcp/src/runtime/native-path.js +12 -0
  1428. package/vendor/desk/mcp/src/runtime/newest-release.js +197 -0
  1429. package/vendor/desk/mcp/src/runtime/node-selection.js +233 -0
  1430. package/vendor/desk/mcp/src/runtime/orca-session-title.js +225 -0
  1431. package/vendor/desk/mcp/src/runtime/other-sessions.js +183 -0
  1432. package/vendor/desk/mcp/src/runtime/pending-migrations.js +657 -0
  1433. package/vendor/desk/mcp/src/runtime/plugin-update.js +215 -0
  1434. package/vendor/desk/mcp/src/runtime/pluginless-runtimes.js +34 -0
  1435. package/vendor/desk/mcp/src/runtime/pr-publication.js +252 -0
  1436. package/vendor/desk/mcp/src/runtime/preview-snapshot.js +23 -0
  1437. package/vendor/desk/mcp/src/runtime/publication-mode.js +19 -0
  1438. package/vendor/desk/mcp/src/runtime/relays.js +983 -0
  1439. package/vendor/desk/mcp/src/runtime/release-alert.js +148 -0
  1440. package/vendor/desk/mcp/src/runtime/remote-identity.js +162 -0
  1441. package/vendor/desk/mcp/src/runtime/resolve-here.js +4 -0
  1442. package/vendor/desk/mcp/src/runtime/runtime-deps-cli.js +65 -0
  1443. package/vendor/desk/mcp/src/runtime/runtime-deps.js +1109 -0
  1444. package/vendor/desk/mcp/src/runtime/runtime-identity.js +22 -0
  1445. package/vendor/desk/mcp/src/runtime/runtime-swap.js +101 -0
  1446. package/vendor/desk/mcp/src/runtime/schedules.js +235 -0
  1447. package/vendor/desk/mcp/src/runtime/session-activity.js +190 -0
  1448. package/vendor/desk/mcp/src/runtime/session-label.js +30 -0
  1449. package/vendor/desk/mcp/src/runtime/session-retention.js +662 -0
  1450. package/vendor/desk/mcp/src/runtime/session-sync.js +333 -0
  1451. package/vendor/desk/mcp/src/runtime/session-trailer.js +126 -0
  1452. package/vendor/desk/mcp/src/runtime/sessions-cli.js +301 -0
  1453. package/vendor/desk/mcp/src/runtime/signoff-listed.js +81 -0
  1454. package/vendor/desk/mcp/src/runtime/skills.js +76 -0
  1455. package/vendor/desk/mcp/src/runtime/stale-card-lead.js +52 -0
  1456. package/vendor/desk/mcp/src/runtime/stale-desk-refresh.js +198 -0
  1457. package/vendor/desk/mcp/src/runtime/stale-desk.js +219 -0
  1458. package/vendor/desk/mcp/src/runtime/stalled.js +255 -0
  1459. package/vendor/desk/mcp/src/runtime/standing-authority.js +79 -0
  1460. package/vendor/desk/mcp/src/runtime/startup-boot.js +341 -0
  1461. package/vendor/desk/mcp/src/runtime/startup-resolve.js +140 -0
  1462. package/vendor/desk/mcp/src/runtime/state-branch.js +203 -0
  1463. package/vendor/desk/mcp/src/runtime/status-compact.js +165 -0
  1464. package/vendor/desk/mcp/src/runtime/status-inspection-child.js +26 -0
  1465. package/vendor/desk/mcp/src/runtime/status-inspection.js +147 -0
  1466. package/vendor/desk/mcp/src/runtime/status-root.js +39 -0
  1467. package/vendor/desk/mcp/src/runtime/sync-worker.js +913 -0
  1468. package/vendor/desk/mcp/src/runtime/test-state-guard.js +107 -0
  1469. package/vendor/desk/mcp/src/runtime/unmerged-saves.js +273 -0
  1470. package/vendor/desk/mcp/src/runtime/workspace-claim.js +53 -0
  1471. package/vendor/desk/mcp/src/runtime/workspace-evidence.js +96 -0
  1472. package/vendor/desk/mcp/src/runtime/workspace-tidy.js +509 -0
  1473. package/vendor/desk/mcp/src/search/direct-lexical.js +54 -0
  1474. package/vendor/desk/mcp/src/search/embedder.js +108 -0
  1475. package/vendor/desk/mcp/src/search/engine.js +406 -0
  1476. package/vendor/desk/mcp/src/search/files-router.js +22 -0
  1477. package/vendor/desk/mcp/src/search/old-index.js +46 -0
  1478. package/vendor/desk/mcp/src/search/vectors.js +60 -0
  1479. package/vendor/desk/mcp/src/server.js +390 -0
  1480. package/vendor/desk/mcp/src/tool-names.js +71 -0
  1481. package/vendor/desk/mcp/src/tool-refusal.cjs +35 -0
  1482. package/vendor/desk/mcp/src/tool-schema-parts.js +12 -0
  1483. package/vendor/desk/mcp/src/tool-schemas.js +320 -0
  1484. package/vendor/desk/mcp/src/tools/_card-commit.js +148 -0
  1485. package/vendor/desk/mcp/src/tools/archive-links.js +188 -0
  1486. package/vendor/desk/mcp/src/tools/archive-move.js +18 -0
  1487. package/vendor/desk/mcp/src/tools/archive-native-session.js +728 -0
  1488. package/vendor/desk/mcp/src/tools/archive-state.js +513 -0
  1489. package/vendor/desk/mcp/src/tools/delivery-gate.js +251 -0
  1490. package/vendor/desk/mcp/src/tools/desk-save.js +449 -0
  1491. package/vendor/desk/mcp/src/tools/doctor.js +122 -0
  1492. package/vendor/desk/mcp/src/tools/done-evidence.js +260 -0
  1493. package/vendor/desk/mcp/src/tools/factory-context.js +204 -0
  1494. package/vendor/desk/mcp/src/tools/friction.js +332 -0
  1495. package/vendor/desk/mcp/src/tools/improvement.js +156 -0
  1496. package/vendor/desk/mcp/src/tools/lesson-lines.js +22 -0
  1497. package/vendor/desk/mcp/src/tools/lesson-owners.js +137 -0
  1498. package/vendor/desk/mcp/src/tools/lesson-team.js +169 -0
  1499. package/vendor/desk/mcp/src/tools/lesson.js +254 -0
  1500. package/vendor/desk/mcp/src/tools/local-only.js +151 -0
  1501. package/vendor/desk/mcp/src/tools/move.js +823 -0
  1502. package/vendor/desk/mcp/src/tools/native-stage-context.js +32 -0
  1503. package/vendor/desk/mcp/src/tools/note.js +267 -0
  1504. package/vendor/desk/mcp/src/tools/search.js +634 -0
  1505. package/vendor/desk/mcp/src/tools/shared-write.js +196 -0
  1506. package/vendor/desk/mcp/src/tools/sibling-desk.js +43 -0
  1507. package/vendor/desk/mcp/src/tools/status.js +236 -0
  1508. package/vendor/desk/mcp/src/tools/task-archive-due.js +9 -0
  1509. package/vendor/desk/mcp/src/tools/task-archived-resource.js +53 -0
  1510. package/vendor/desk/mcp/src/tools/task-body.js +141 -0
  1511. package/vendor/desk/mcp/src/tools/task-focus.js +164 -0
  1512. package/vendor/desk/mcp/src/tools/task-log.js +80 -0
  1513. package/vendor/desk/mcp/src/tools/task-signoff.js +155 -0
  1514. package/vendor/desk/mcp/src/tools/task.js +1780 -0
  1515. package/vendor/desk/mcp/src/tools/track-row.js +89 -0
  1516. package/vendor/desk/mcp/src/tools/track.js +240 -0
  1517. package/vendor/desk/mcp/src/util/agency-session.cjs +29 -0
  1518. package/vendor/desk/mcp/src/util/archive-links.js +105 -0
  1519. package/vendor/desk/mcp/src/util/bash.js +36 -0
  1520. package/vendor/desk/mcp/src/util/capture-record.js +73 -0
  1521. package/vendor/desk/mcp/src/util/cas-commit.js +252 -0
  1522. package/vendor/desk/mcp/src/util/citations.js +54 -0
  1523. package/vendor/desk/mcp/src/util/created-dirs.js +71 -0
  1524. package/vendor/desk/mcp/src/util/deferred-tools.js +51 -0
  1525. package/vendor/desk/mcp/src/util/desk-owner.js +99 -0
  1526. package/vendor/desk/mcp/src/util/env-value.js +13 -0
  1527. package/vendor/desk/mcp/src/util/file-identity.js +40 -0
  1528. package/vendor/desk/mcp/src/util/finish-commit.js +145 -0
  1529. package/vendor/desk/mcp/src/util/fm.js +410 -0
  1530. package/vendor/desk/mcp/src/util/git-config-file.js +85 -0
  1531. package/vendor/desk/mcp/src/util/git-stage.js +440 -0
  1532. package/vendor/desk/mcp/src/util/main-publish.js +240 -0
  1533. package/vendor/desk/mcp/src/util/markdown-links.cjs +555 -0
  1534. package/vendor/desk/mcp/src/util/object-input.js +59 -0
  1535. package/vendor/desk/mcp/src/util/paths.js +647 -0
  1536. package/vendor/desk/mcp/src/util/rank.js +189 -0
  1537. package/vendor/desk/mcp/src/util/redact.js +92 -0
  1538. package/vendor/desk/mcp/src/util/remove-retry.js +35 -0
  1539. package/vendor/desk/mcp/src/util/rename-retry.js +73 -0
  1540. package/vendor/desk/mcp/src/util/route-around.js +265 -0
  1541. package/vendor/desk/mcp/src/util/shell-quote.js +18 -0
  1542. package/vendor/desk/mcp/src/util/startup-direction.js +124 -0
  1543. package/vendor/desk/mcp/src/util/state-ignore.js +33 -0
  1544. package/vendor/desk/mcp/src/util/tool-commits.js +64 -0
  1545. package/vendor/desk/mcp/src/util/unicode-16/LICENSE-MIT.txt +7 -0
  1546. package/vendor/desk/mcp/src/util/unicode-16/README.md +9 -0
  1547. package/vendor/desk/mcp/src/util/unicode-16/letter.cjs +1 -0
  1548. package/vendor/desk/mcp/src/util/unicode-16/mark.cjs +1 -0
  1549. package/vendor/desk/mcp/src/util/unicode-16/number.cjs +1 -0
  1550. package/vendor/desk/mcp/web-auth.cjs +1914 -0
  1551. package/vendor/desk/mcp/web-browser-discovery.cjs +53 -0
  1552. package/vendor/desk/mcp/web-catalog.json +34 -0
  1553. package/vendor/desk/mcp/web-launch.cjs +101 -0
  1554. package/vendor/desk/mcp/web-sso.cjs +52 -0
  1555. package/vendor/desk/mcp/web.cjs +1239 -0
  1556. package/vendor/desk/migrations/01-move-to-ourostack-desk.md +188 -0
  1557. package/vendor/desk/migrations/02-tidy-desk.md +87 -0
  1558. package/vendor/desk/migrations/03-desk-release-channel.md +38 -0
  1559. package/vendor/desk/optional/session-label/consumer.mjs +237 -0
  1560. package/vendor/desk/optional/session-label/extension.mjs +32 -0
  1561. package/vendor/desk/plugin.json +54 -0
  1562. package/vendor/desk/settings.json +3 -0
  1563. package/vendor/desk/skills/add-workspace-mcp/SKILL.md +180 -0
  1564. package/vendor/desk/skills/adopt-inflight-work/SKILL.md +212 -0
  1565. package/vendor/desk/skills/archive-workflow/SKILL.md +132 -0
  1566. package/vendor/desk/skills/content-routing/SKILL.md +95 -0
  1567. package/vendor/desk/skills/coordinating-lanes/SKILL.md +24 -0
  1568. package/vendor/desk/skills/core-meeting-capture/SKILL.md +47 -0
  1569. package/vendor/desk/skills/core-meeting-capture/references/capture-contract.md +175 -0
  1570. package/vendor/desk/skills/curator/SKILL.md +103 -0
  1571. package/vendor/desk/skills/delightful-decks/SKILL.md +67 -0
  1572. package/vendor/desk/skills/desk-problem/SKILL.md +87 -0
  1573. package/vendor/desk/skills/directory-structure/SKILL.md +169 -0
  1574. package/vendor/desk/skills/doc-review-rigor/SKILL.md +63 -0
  1575. package/vendor/desk/skills/draining-issues/SKILL.md +62 -0
  1576. package/vendor/desk/skills/evaluate-release/SKILL.md +96 -0
  1577. package/vendor/desk/skills/evidence-discipline/SKILL.md +146 -0
  1578. package/vendor/desk/skills/factory-evaluator/SKILL.md +122 -0
  1579. package/vendor/desk/skills/factory-task-context/SKILL.md +116 -0
  1580. package/vendor/desk/skills/factory-work/SKILL.md +16 -0
  1581. package/vendor/desk/skills/fast-honest-ci/SKILL.md +70 -0
  1582. package/vendor/desk/skills/fast-honest-ci/examples.md +49 -0
  1583. package/vendor/desk/skills/first-run-bootstrap/SKILL.md +95 -0
  1584. package/vendor/desk/skills/friction-management/SKILL.md +98 -0
  1585. package/vendor/desk/skills/git-hygiene/SKILL.md +259 -0
  1586. package/vendor/desk/skills/independent-review/SKILL.md +34 -0
  1587. package/vendor/desk/skills/interaction-style/SKILL.md +241 -0
  1588. package/vendor/desk/skills/lesson-capture/SKILL.md +85 -0
  1589. package/vendor/desk/skills/lesson-capture/agents-md-budget.mjs +61 -0
  1590. package/vendor/desk/skills/live-ui-iteration/SKILL.md +35 -0
  1591. package/vendor/desk/skills/online-evaluation/SKILL.md +81 -0
  1592. package/vendor/desk/skills/operator-voice-comments/LICENSE-humanize +21 -0
  1593. package/vendor/desk/skills/operator-voice-comments/SKILL.md +94 -0
  1594. package/vendor/desk/skills/operator-voice-comments/human-voice.md +43 -0
  1595. package/vendor/desk/skills/outside-approval/SKILL.md +10 -0
  1596. package/vendor/desk/skills/peer-pr-review/SKILL.md +104 -0
  1597. package/vendor/desk/skills/pr-feedback-on-own-pr/SKILL.md +149 -0
  1598. package/vendor/desk/skills/pr-review-interrogation/SKILL.md +121 -0
  1599. package/vendor/desk/skills/pr-reviewer-audit/SKILL.md +68 -0
  1600. package/vendor/desk/skills/pr-reviewer-audit/helpers/audit.py +353 -0
  1601. package/vendor/desk/skills/pr-reviewer-audit/helpers/test_audit.py +522 -0
  1602. package/vendor/desk/skills/pr-self-review/SKILL.md +86 -0
  1603. package/vendor/desk/skills/pr-surface-hygiene/SKILL.md +129 -0
  1604. package/vendor/desk/skills/pr-surface-hygiene/check-visual-proof.cjs +112 -0
  1605. package/vendor/desk/skills/pr-surface-hygiene/repository-setup.md +19 -0
  1606. package/vendor/desk/skills/pr-surface-hygiene/resources/pr-visual-proof.yml +29 -0
  1607. package/vendor/desk/skills/pr-surface-hygiene/resources/pull-request-template.md +5 -0
  1608. package/vendor/desk/skills/preflight-actions/SKILL.md +60 -0
  1609. package/vendor/desk/skills/preview-feedback/SKILL.md +70 -0
  1610. package/vendor/desk/skills/prior-art/SKILL.md +14 -0
  1611. package/vendor/desk/skills/repo-handling/SKILL.md +67 -0
  1612. package/vendor/desk/skills/rnd-lab/SKILL.md +52 -0
  1613. package/vendor/desk/skills/runtime-symptom-investigation/SKILL.md +110 -0
  1614. package/vendor/desk/skills/session-resumption/SKILL.md +128 -0
  1615. package/vendor/desk/skills/session-start/SKILL.md +54 -0
  1616. package/vendor/desk/skills/session-start/details.md +150 -0
  1617. package/vendor/desk/skills/session-start-migrations/README.md +71 -0
  1618. package/vendor/desk/skills/session-start-migrations/SKILL.md +108 -0
  1619. package/vendor/desk/skills/start-task/SKILL.md +88 -0
  1620. package/vendor/desk/skills/task-card-format/SKILL.md +198 -0
  1621. package/vendor/desk/skills/task-lifecycle/SKILL.md +217 -0
  1622. package/vendor/desk/skills/track-card-format/SKILL.md +90 -0
  1623. package/vendor/desk/skills/using-desk/SKILL.md +58 -0
  1624. package/vendor/desk/skills/using-superpowers-with-desk/SKILL.md +158 -0
  1625. package/vendor/desk/skills/visual-proof/SKILL.md +42 -0
  1626. package/vendor/desk/skills/work-orchestration/SKILL.md +177 -0
  1627. package/dist/heart/daemon/auth-flow.js +0 -457
  1628. package/dist/heart/daemon/habit-parser.js +0 -119
  1629. package/dist/heart/daemon/habit-scheduler.js +0 -369
  1630. package/dist/heart/daemon/mcp-server.js +0 -591
  1631. package/dist/heart/daemon/ouro-path-installer.js +0 -221
  1632. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  1633. package/dist/heart/daemon/specialist-tools.js +0 -283
  1634. package/dist/heart/daemon/update-hooks.js +0 -138
  1635. package/dist/heart/obligations.js +0 -197
  1636. package/dist/heart/session-recall.js +0 -216
  1637. package/dist/mind/associative-recall.js +0 -287
  1638. package/dist/mind/friends/resolver.js +0 -84
  1639. package/dist/mind/friends/store-file.js +0 -190
  1640. package/dist/mind/friends/trust-explanation.js +0 -74
  1641. package/dist/mind/friends/types.js +0 -29
  1642. package/dist/mind/journal-index.js +0 -161
  1643. package/dist/mind/obligations.js +0 -134
  1644. package/dist/repertoire/tasks/board.js +0 -134
  1645. package/dist/repertoire/tasks/index.js +0 -224
  1646. package/dist/repertoire/tasks/lifecycle.js +0 -80
  1647. package/dist/repertoire/tasks/middleware.js +0 -65
  1648. package/dist/repertoire/tasks/parser.js +0 -171
  1649. package/dist/repertoire/tasks/scanner.js +0 -132
  1650. package/dist/repertoire/tasks/transitions.js +0 -126
  1651. package/dist/repertoire/tools-bluebubbles.js +0 -94
  1652. package/dist/senses/bluebubbles-entry.js +0 -13
  1653. package/dist/senses/bluebubbles-media.js +0 -339
  1654. package/dist/senses/bluebubbles.js +0 -1327
  1655. package/dist/senses/inner-dialog-worker.js +0 -154
  1656. package/dist/senses/inner-dialog.js +0 -739
  1657. package/subagents/README.md +0 -7
  1658. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  1659. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  1660. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  1661. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  1662. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  1663. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  1664. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  1665. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  1666. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  1667. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  1668. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  1669. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  1670. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  1671. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  1672. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  1673. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  1674. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
  1675. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -0,0 +1,2533 @@
1
+ #!/usr/bin/env node
2
+ // Sanctuary media MCP server — the Butler's media surface.
3
+ //
4
+ // Design authority: the Butler's own tool-surface spec (Telegram msgs 1700-1713, 2026-09-19).
5
+ // Two hard constraints it set, enforced here:
6
+ // 1. Anything deterministic lives in the tool, not in the agent's reasoning.
7
+ // 2. No "call A, parse it, build B" — every return payload carries the cross-reference
8
+ // fields needed to answer the obvious follow-up without a second call.
9
+ //
10
+ // Protocol: JSON-RPC 2.0 over stdio, newline framed, MCP 2024-11-05.
11
+
12
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
13
+ import { dirname } from "node:path"
14
+ import { pathToFileURL } from "node:url"
15
+
16
+ const CRED_PATH = process.env.SANCTUARY_MEDIA_CREDENTIALS ?? "/home/ouro/AgentBundles/sanctuary.ouro/mcp/media-credentials.json"
17
+
18
+ // Credentials are host-specific and deliberately NOT packaged. A fresh install
19
+ // has none, and the server must still start and list its tools — otherwise the
20
+ // whole MCP server fails to connect and the agent silently loses the surface.
21
+ // Missing credentials become a named, reportable per-call failure instead.
22
+ let cred = null
23
+ let credError = null
24
+ try {
25
+ cred = JSON.parse(readFileSync(CRED_PATH, "utf8"))
26
+ } catch (e) {
27
+ credError = `Media credentials are unavailable at ${CRED_PATH} (${e.code ?? e.message}). The media tools cannot reach Jellyseerr/Sonarr/Radarr/Prowlarr until that file is created.`
28
+ }
29
+
30
+ const SEERR = cred?.jellyseerr ?? { url: "", apiKey: "" }
31
+ const SONARR = cred?.sonarr ?? { url: "", apiKey: "" }
32
+ const RADARR = cred?.radarr ?? { url: "", apiKey: "" }
33
+ const PROWLARR = cred?.prowlarr ?? { url: "", apiKey: "" }
34
+ // The household's Jellyfin web address: the credential file wins, then house/house.json.
35
+ // With neither, search results carry no play link rather than a guessed one.
36
+ function houseJellyfinWebUrl() {
37
+ try {
38
+ const house = JSON.parse(readFileSync(new URL("../house/house.json", pathToFileURL(CRED_PATH)), "utf8"))
39
+ return typeof house?.jellyfinWebUrl === "string" ? house.jellyfinWebUrl : ""
40
+ } catch {
41
+ return ""
42
+ }
43
+ }
44
+ const JELLYFIN_WEB = String(cred?.jellyfinWebUrl ?? houseJellyfinWebUrl()).replace(/\/+$/u, "")
45
+ // Optional: when the credential file carries { jellyfin: { url, apiKey } } the library
46
+ // is searched in Jellyfin too. Absent, title resolution uses Sonarr and Radarr only.
47
+ const JELLYFIN = cred?.jellyfin ?? { url: "", apiKey: "" }
48
+
49
+ const TIMEOUT_MS = 45_000
50
+ // Interactive release search queries every indexer live and can take minutes.
51
+ const SEARCH_TIMEOUT_MS = 180_000
52
+
53
+ // ---------------------------------------------------------------- http helpers
54
+
55
+ async function req(base, path, { key, header = "X-Api-Key", method = "GET", body, query, timeoutMs = TIMEOUT_MS } = {}) {
56
+ let url = `${base}${path}`
57
+ if (query) {
58
+ const parts = Object.entries(query)
59
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
60
+ // encodeURIComponent, not URLSearchParams: Jellyseerr rejects '+' for spaces.
61
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
62
+ if (parts.length) url += `?${parts.join("&")}`
63
+ }
64
+ const headers = { [header]: key, Accept: "application/json" }
65
+ if (body !== undefined) headers["Content-Type"] = "application/json"
66
+ let res
67
+ try {
68
+ res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) })
69
+ } catch (e) {
70
+ throw new ServiceError(`${serviceOf(base)}_unreachable`, `${serviceOf(base)} did not respond: ${e.name === "TimeoutError" ? "timeout" : e.message}`)
71
+ }
72
+ if (!res.ok) {
73
+ const text = await res.text().catch(() => "")
74
+ throw new ServiceError(`${serviceOf(base)}_http_${res.status}`, `${serviceOf(base)} returned ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`)
75
+ }
76
+ if (res.status === 204) return null
77
+ // Sonarr/Radarr answer some DELETEs with 200 and an empty body; that is success, not a parse failure.
78
+ const raw = await res.text()
79
+ return raw.trim() ? JSON.parse(raw) : null
80
+ }
81
+
82
+ function serviceOf(base) {
83
+ if (base === SEERR.url) return "jellyseerr"
84
+ if (base === SONARR.url) return "sonarr"
85
+ if (base === RADARR.url) return "radarr"
86
+ if (base === PROWLARR.url) return "prowlarr"
87
+ if (JELLYFIN.url && base === JELLYFIN.url) return "jellyfin"
88
+ return "service"
89
+ }
90
+
91
+ class ServiceError extends Error {
92
+ constructor(code, message) { super(message); this.code = code }
93
+ }
94
+
95
+ const seerr = (path, opts = {}) => req(SEERR.url, `/api/v1${path}`, { key: SEERR.apiKey, ...opts })
96
+ // Long enough that an ordinary slow start is not called dead, short enough that
97
+ // nobody waits a day for a release that was never going to arrive.
98
+ const STALL_AFTER_HOURS = 6
99
+
100
+ const sonarr = (path, opts = {}) => req(SONARR.url, `/api/v3${path}`, { key: SONARR.apiKey, ...opts })
101
+ const radarr = (path, opts = {}) => req(RADARR.url, `/api/v3${path}`, { key: RADARR.apiKey, ...opts })
102
+ const prowlarr = (path, opts = {}) => req(PROWLARR.url, `/api/v1${path}`, { key: PROWLARR.apiKey, ...opts })
103
+
104
+ // ------------------------------------------------------------------ mapping
105
+
106
+ // Jellyseerr media status codes.
107
+ const MEDIA_STATUS = { 1: "unknown", 2: "pending", 4: "partially_available", 5: "available" }
108
+ const REQUEST_STATUS = { 1: "pending_approval", 2: "approved", 3: "declined", 4: "failed" }
109
+
110
+ const TMDB_GENRES = {
111
+ 28: "Action", 12: "Adventure", 16: "Animation", 35: "Comedy", 80: "Crime", 99: "Documentary",
112
+ 18: "Drama", 10751: "Family", 14: "Fantasy", 36: "History", 27: "Horror", 10402: "Music",
113
+ 9648: "Mystery", 10749: "Romance", 878: "Science Fiction", 10770: "TV Movie", 53: "Thriller",
114
+ 10752: "War", 37: "Western", 10759: "Action & Adventure", 10762: "Kids", 10763: "News",
115
+ 10764: "Reality", 10765: "Sci-Fi & Fantasy", 10766: "Soap", 10767: "Talk", 10768: "War & Politics",
116
+ }
117
+
118
+ function genreNames(item) {
119
+ const ids = item.genreIds ?? (item.genres ?? []).map((g) => g.id)
120
+ return ids.map((id) => TMDB_GENRES[id]).filter(Boolean)
121
+ }
122
+
123
+ // Jellyseerr's media status 3 only means Sonarr/Radarr track the title; it says nothing about
124
+ // a download or a request. Name what is actually known so nobody reads it as "processing".
125
+ function shelfStateOf(kind, info) {
126
+ if (info.status === 3) return info.downloadStatus?.length ? "downloading" : `in_${kind === "series" ? "sonarr" : "radarr"}_not_downloading`
127
+ return MEDIA_STATUS[info.status] ?? "not_on_shelf"
128
+ }
129
+
130
+ // A request exists only if Jellyseerr lists one; the media status is not a request.
131
+ function requestStateOf(info) {
132
+ if (!Array.isArray(info.requests)) return info.status ? "unknown_check_media_request_status" : "never_requested"
133
+ if (info.requests.length === 0) return "never_requested"
134
+ return REQUEST_STATUS[info.requests[info.requests.length - 1].status] ?? "requested"
135
+ }
136
+
137
+ export function shelfItem(item) {
138
+ const kind = item.mediaType === "tv" ? "series" : item.mediaType === "movie" ? "movie" : (item.firstAirDate ? "series" : "movie")
139
+ const date = item.releaseDate ?? item.firstAirDate ?? ""
140
+ const info = item.mediaInfo ?? {}
141
+ const status = shelfStateOf(kind, info)
142
+ return {
143
+ title: item.title ?? item.name ?? null,
144
+ year: date ? Number(date.slice(0, 4)) : null,
145
+ kind,
146
+ tmdb_id: item.id ?? null,
147
+ tvdb_id: info.tvdbId ?? null,
148
+ genres: genreNames(item),
149
+ overview: typeof item.overview === "string" ? item.overview.slice(0, 400) : null,
150
+ // The two fields that stop a second call:
151
+ on_shelf: status === "available" || status === "partially_available",
152
+ shelf_state: status,
153
+ request_state: requestStateOf(info),
154
+ sonarr_id: kind === "series" ? (info.externalServiceId ?? null) : null,
155
+ radarr_id: kind === "movie" ? (info.externalServiceId ?? null) : null,
156
+ poster_path: item.posterPath ? `https://image.tmdb.org/t/p/w500${item.posterPath}` : null,
157
+ vote_average: item.voteAverage ?? null,
158
+ }
159
+ }
160
+
161
+ // ------------------------------------------------------- title resolution
162
+ //
163
+ // One resolver for every tool that takes a title. A title typed from memory is
164
+ // rarely the catalogue's title: "chef" is "The Chef Show", "chef shwo" is a typo.
165
+ // The 2026-09-29 failure was a library search that required the whole title and
166
+ // so reported a tracked series as nonexistent. Matching is therefore partial and
167
+ // typo-tolerant, in-library candidates always come first, and the TVDB/TMDB
168
+ // lookup only runs when the library has nothing.
169
+
170
+ export function normalizeTitle(s) {
171
+ return String(s ?? "")
172
+ .normalize("NFKD").replace(/[\u0300-\u036f]/g, "")
173
+ .toLowerCase().replace(/&/g, " and ").replace(/['\u2019]/g, "")
174
+ .replace(/[^a-z0-9]+/g, " ").trim().replace(/^the /, "")
175
+ }
176
+
177
+ // Optimal-string-alignment distance: an adjacent swap ("shwo") costs one edit.
178
+ function editDistance(a, b) {
179
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)])
180
+ for (let j = 1; j <= b.length; j += 1) d[0][j] = j
181
+ for (let i = 1; i <= a.length; i += 1) {
182
+ for (let j = 1; j <= b.length; j += 1) {
183
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
184
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1)
185
+ }
186
+ }
187
+ return d[a.length][b.length]
188
+ }
189
+
190
+ const MATCH_RANK = { exact: 0, prefix: 1, token: 2, fuzzy: 3 }
191
+
192
+ // Returns "exact" | "prefix" | "token" | "fuzzy" | null.
193
+ export function matchKind(query, title) {
194
+ const nq = normalizeTitle(query)
195
+ const nt = normalizeTitle(title)
196
+ if (!nq || !nt) return null
197
+ if (nq === nt) return "exact"
198
+ if (nt.startsWith(nq)) return "prefix"
199
+ const qt = nq.split(" ")
200
+ const tt = nt.split(" ")
201
+ if (qt.every((q) => tt.some((t) => t === q || (q.length >= 3 && t.includes(q))))) return "token"
202
+ if (nq.length >= 3 && nt.includes(nq)) return "token"
203
+ // Typos. Short tokens must be exact; a 4-letter token may only be fuzzy when
204
+ // another query token already matched exactly, so "chef" never drifts to "chess".
205
+ const exactHit = (q) => tt.includes(q)
206
+ const fuzzyHit = (q) => tt.some((t) => {
207
+ if (q.length < 4 || t.length < 4) return false
208
+ const tol = q.length >= 8 ? 2 : 1
209
+ return editDistance(q, t) <= tol
210
+ })
211
+ const anyExact = qt.some(exactHit)
212
+ const ok = qt.every((q) => exactHit(q) || (fuzzyHit(q) && (q.length >= 5 || (qt.length > 1 && anyExact))))
213
+ return ok ? "fuzzy" : null
214
+ }
215
+
216
+ function rankCandidates(term, items) {
217
+ return items
218
+ .map((c) => ({ ...c, match: matchKind(term, c.title) }))
219
+ .filter((c) => c.match)
220
+ .sort((x, y) => MATCH_RANK[x.match] - MATCH_RANK[y.match]
221
+ || Math.abs(normalizeTitle(x.title).length - normalizeTitle(term).length) - Math.abs(normalizeTitle(y.title).length - normalizeTitle(term).length))
222
+ }
223
+
224
+ const libraryCandidate = (kind, i) => ({ kind, source: kind === "series" ? "sonarr" : "radarr", service_id: i.id, title: i.title,
225
+ year: i.year ?? null, tmdb_id: i.tmdbId ?? null, tvdb_id: i.tvdbId ?? null, in_library: true,
226
+ overview: typeof i.overview === "string" ? i.overview : null })
227
+
228
+ // Subject matching. People name a film by what it is about as often as by its title: on 2026-11-19 Ari asked for
229
+ // "that new holmes documentary", which was Radarr 1061, You Can See Everything, and a title-only search said it had
230
+ // never been requested. So after the title matches come tracked items whose overview contains every distinctive
231
+ // word of the query. They are labelled match "subject" with the overview text, and nothing acts on one by itself.
232
+ const SUBJECT_STOP = new Set(["new", "newest", "latest", "recent", "old", "documentary", "documentaries", "doc", "docu",
233
+ "docuseries", "film", "films", "movie", "movies", "show", "shows", "series", "season", "episode", "that", "this",
234
+ "about", "with", "from", "asked", "wanted", "requested", "thing", "your", "mine"])
235
+
236
+ function subjectTokens(term) {
237
+ return normalizeTitle(term).split(" ").filter((t) => t.length >= 4 && !SUBJECT_STOP.has(t))
238
+ }
239
+
240
+ const candidateKey = (c) => `${c.kind}:${c.service_id ?? c.jellyfin_id ?? c.title}`
241
+
242
+ function subjectMatches(term, items, titled) {
243
+ const tokens = subjectTokens(term)
244
+ if (!tokens.length) return []
245
+ const taken = new Set(titled.map(candidateKey))
246
+ return items
247
+ .filter((i) => i.overview && !taken.has(candidateKey(i)))
248
+ .filter((i) => { const words = new Set(normalizeTitle(i.overview).split(" ")); return tokens.every((t) => words.has(t)) })
249
+ .map((i) => ({ ...i, match: "subject", matched_overview: i.overview.slice(0, 240) }))
250
+ }
251
+
252
+ // Every library item whose title matches, best first. Sonarr and Radarr are the
253
+ // source of truth for what is tracked; Jellyfin (when configured) adds what is
254
+ // on the shelf and marks items it shares with them.
255
+ export async function findLibraryCandidates(term, kind = "any") {
256
+ const jobs = []
257
+ if (kind !== "movie") jobs.push(sonarr("/series").then((l) => (Array.isArray(l) ? l : []).map((i) => libraryCandidate("series", i))))
258
+ if (kind !== "series") jobs.push(radarr("/movie").then((l) => (Array.isArray(l) ? l : []).map((i) => libraryCandidate("movie", i))))
259
+ // One service being down must not hide the other's matches; say which failed.
260
+ const settled = await Promise.allSettled(jobs)
261
+ const notes = []
262
+ for (const r of settled) if (r.status === "rejected") notes.push(`library_unavailable: ${r.reason?.message ?? r.reason}`)
263
+ if (settled.every((r) => r.status === "rejected")) throw settled[0].reason
264
+ let items = settled.flatMap((r) => (r.status === "fulfilled" ? r.value : []))
265
+ if (JELLYFIN.url && JELLYFIN.apiKey) {
266
+ try {
267
+ const body = await req(JELLYFIN.url, "/Items", { key: JELLYFIN.apiKey, header: "X-Emby-Token",
268
+ query: { searchTerm: term, IncludeItemTypes: kind === "series" ? "Series" : kind === "movie" ? "Movie" : "Series,Movie", Recursive: true, Limit: 25 } })
269
+ for (const j of body?.Items ?? []) {
270
+ const k = j.Type === "Series" ? "series" : "movie"
271
+ const tmdb = Number(j.ProviderIds?.Tmdb ?? j.ProviderIds?.tmdb) || null
272
+ const twin = items.find((i) => i.kind === k && ((tmdb && i.tmdb_id === tmdb) || normalizeTitle(i.title) === normalizeTitle(j.Name)))
273
+ if (twin) twin.in_jellyfin = true
274
+ else items.push({ kind: k, source: "jellyfin", service_id: null, jellyfin_id: j.Id ?? null, title: j.Name, year: j.ProductionYear ?? null,
275
+ tmdb_id: tmdb, tvdb_id: null, in_library: true, in_jellyfin: true })
276
+ }
277
+ } catch (e) {
278
+ notes.push(`jellyfin_unavailable: ${e.message}`)
279
+ }
280
+ }
281
+ const titled = rankCandidates(term, items)
282
+ const ranked = [...titled, ...subjectMatches(term, items, titled)].map(({ overview, ...c }) => c)
283
+ if (notes.length) Object.defineProperty(ranked, "notes", { value: notes, enumerable: false })
284
+ return ranked
285
+ }
286
+
287
+ // The catalogue fallback, used only when the library has no candidate. These are
288
+ // titles Sonarr/Radarr could add, so they are labelled not_in_library.
289
+ export async function lookupCandidates(term, kind = "any") {
290
+ const out = []
291
+ const jobs = []
292
+ if (kind !== "movie") jobs.push(sonarr("/series/lookup", { query: { term } }).then((l) => (Array.isArray(l) ? l : []).forEach((i) => out.push({ kind: "series", source: "sonarr_lookup", service_id: i.id ?? null, title: i.title, year: i.year ?? null, tmdb_id: i.tmdbId ?? null, tvdb_id: i.tvdbId ?? null, in_library: Boolean(i.id), match: matchKind(term, i.title) ?? "lookup" }))).catch(() => {}))
293
+ if (kind !== "series") jobs.push(radarr("/movie/lookup", { query: { term } }).then((l) => (Array.isArray(l) ? l : []).forEach((i) => out.push({ kind: "movie", source: "radarr_lookup", service_id: i.id ?? null, title: i.title, year: i.year ?? null, tmdb_id: i.tmdbId ?? null, tvdb_id: null, in_library: Boolean(i.id), match: matchKind(term, i.title) ?? "lookup" }))).catch(() => {}))
294
+ await Promise.all(jobs)
295
+ return out.sort((x, y) => (MATCH_RANK[x.match] ?? 4) - (MATCH_RANK[y.match] ?? 4)).slice(0, 10)
296
+ }
297
+
298
+ // In-library candidates first; the lookup fallback only when there are none.
299
+ export async function resolveTitle(term, kind = "any") {
300
+ const library = await findLibraryCandidates(term, kind)
301
+ if (library.length) return { library_matches: library, lookup_candidates: [], not_in_library: false, notes: library.notes ?? [] }
302
+ const lookup = (await lookupCandidates(term, kind)).filter((c) => !c.in_library).map((c) => ({ ...c, not_in_library: true }))
303
+ return { library_matches: [], lookup_candidates: lookup, not_in_library: true, notes: [] }
304
+ }
305
+
306
+ // ------------------------------------------------------------- tool: search
307
+
308
+ export async function mediaSearch(a) {
309
+ const kind = a.kind ?? "any"
310
+ const limit = Math.min(Math.max(a.limit ?? 12, 1), 20)
311
+ const onShelf = a.on_shelf // true | false | undefined(any)
312
+ let raw = []
313
+ let source
314
+
315
+ if (a.query) {
316
+ source = "title_search"
317
+ const body = await seerr("/search", { query: { query: a.query, page: 1 } })
318
+ raw = body.results ?? []
319
+ } else {
320
+ source = "discover"
321
+ const keywordIds = []
322
+ for (const kw of a.keywords ?? []) {
323
+ const hit = await seerr("/search/keyword", { query: { query: kw, page: 1 } })
324
+ const exact = (hit.results ?? []).find((k) => k.name.toLowerCase() === kw.toLowerCase()) ?? (hit.results ?? [])[0]
325
+ if (exact) keywordIds.push(exact.id)
326
+ }
327
+ const genreIds = (a.genres ?? [])
328
+ .map((name) => Number(Object.entries(TMDB_GENRES).find(([, v]) => v.toLowerCase() === String(name).toLowerCase())?.[0]))
329
+ .filter((n) => Number.isFinite(n))
330
+ const [yMin, yMax] = a.year_range ?? []
331
+ const paths = kind === "series" ? ["/discover/tv"] : kind === "movie" ? ["/discover/movies"] : ["/discover/movies", "/discover/tv"]
332
+ // One page of discover is ~20 popular titles, of which only a couple are
333
+ // usually on this shelf — answering "what cozy autumn films do we own?" from
334
+ // that reads as though the shelf is nearly empty. When the caller filters by
335
+ // shelf state, walk further pages until enough matches accumulate.
336
+ const maxPages = onShelf === undefined ? 1 : 5
337
+ for (const p of paths) {
338
+ const isTv = p.endsWith("/tv")
339
+ for (let page = 1; page <= maxPages; page += 1) {
340
+ const q = { page, sortBy: a.sort === "release_year" ? "primary_release_date.desc" : "popularity.desc" }
341
+ if (genreIds.length) q.genre = genreIds.join(",")
342
+ if (keywordIds.length) q.keywords = keywordIds.join(",")
343
+ if (yMin) q[isTv ? "firstAirDateGte" : "primaryReleaseDateGte"] = `${yMin}-01-01`
344
+ if (yMax) q[isTv ? "firstAirDateLte" : "primaryReleaseDateLte"] = `${yMax}-12-31`
345
+ const body = await seerr(p, { query: q })
346
+ const results = body.results ?? []
347
+ raw.push(...results.map((r) => ({ ...r, mediaType: isTv ? "tv" : "movie" })))
348
+ const matchesSoFar = raw
349
+ .map((r) => (r.mediaInfo?.status === 5 || r.mediaInfo?.status === 4))
350
+ .filter((hit) => hit === (onShelf === true)).length
351
+ if (results.length === 0 || page >= (body.totalPages ?? 1) || matchesSoFar >= limit) break
352
+ }
353
+ }
354
+ }
355
+
356
+ // Partial and typo-tolerant library match, so a half-remembered title still
357
+ // finds what is tracked. Lookup candidates appear only when the library has none.
358
+ const resolution = a.query ? await resolveTitle(a.query, kind).catch((e) => ({ library_matches: [], lookup_candidates: [], not_in_library: null, notes: [`title_resolution_failed: ${e.message}`] })) : null
359
+
360
+ let items = raw.filter((r) => r.mediaType !== "person").map(shelfItem)
361
+ if (kind !== "any") items = items.filter((i) => i.kind === kind)
362
+ if (a.year_range) {
363
+ const [lo, hi] = a.year_range
364
+ items = items.filter((i) => i.year && (!lo || i.year >= lo) && (!hi || i.year <= hi))
365
+ }
366
+ if (onShelf === true) items = items.filter((i) => i.on_shelf)
367
+ if (onShelf === false) items = items.filter((i) => !i.on_shelf)
368
+ if (a.sort === "release_year") items.sort((x, y) => (y.year ?? 0) - (x.year ?? 0))
369
+
370
+ return {
371
+ source,
372
+ matched: items.length,
373
+ items: items.slice(0, limit),
374
+ ...(resolution ? { library_matches: resolution.library_matches.slice(0, 10), lookup_candidates: resolution.lookup_candidates, notes: resolution.notes } : {}),
375
+ applied_filters: { kind, year_range: a.year_range ?? null, genres: a.genres ?? [], keywords: a.keywords ?? [], on_shelf: onShelf ?? "any" },
376
+ // So the agent never claims something is missing when the filter caused it:
377
+ note: resolution?.library_matches.length ? "library_matches lists items already tracked in Sonarr/Radarr (or on the Jellyfin shelf) whose titles match, best first, then any whose overview names what was asked (match: subject, with matched_overview). Offer these before anything else; a subject match is a guess to confirm with the person, not a certainty."
378
+ : items.length === 0 && resolution?.lookup_candidates.length ? "Nothing in the library matches; lookup_candidates are TVDB/TMDB titles that are not in the library."
379
+ : items.length === 0 ? "No matches for these filters. Loosen year_range/genres/keywords before concluding the shelf lacks it." : null,
380
+ }
381
+ }
382
+
383
+ // ------------------------------------------------------------ tool: request
384
+
385
+ // Resolve by TMDB id against the title itself rather than scanning the request
386
+ // list: this household has over a thousand requests, so a page-limited scan
387
+ // silently misses older ones and would file a duplicate.
388
+ async function findExistingRequest(tmdbId, kind) {
389
+ const kinds = kind ? [kind] : ["movie", "series"]
390
+ for (const k of kinds) {
391
+ let detail
392
+ try {
393
+ detail = await seerr(`/${k === "series" ? "tv" : "movie"}/${tmdbId}`)
394
+ } catch {
395
+ continue
396
+ }
397
+ const info = detail?.mediaInfo
398
+ if (!info) continue
399
+ const requests = info.requests ?? []
400
+ const latest = requests.length ? requests[requests.length - 1] : null
401
+ return {
402
+ id: latest?.id ?? null,
403
+ status: latest?.status ?? null,
404
+ createdAt: latest?.createdAt ?? null,
405
+ type: k === "series" ? "tv" : "movie",
406
+ media: { ...info, tmdbId, title: detail.title ?? detail.name ?? null },
407
+ hasRequest: requests.length > 0,
408
+ }
409
+ }
410
+ return null
411
+ }
412
+
413
+ async function mediaRequest(a) {
414
+ let tmdbId = a.tmdb_id
415
+ let kind = a.kind ?? "movie"
416
+ let resolvedTitle = a.title ?? null
417
+ let resolvedYear = a.year ?? null
418
+
419
+ if (!tmdbId) {
420
+ if (!a.title) throw new ServiceError("bad_arguments", "media_request needs tmdb_id, or title (year optional).")
421
+ const body = await seerr("/search", { query: { query: a.title, page: 1 } })
422
+ let cands = (body.results ?? []).filter((r) => r.mediaType === "movie" || r.mediaType === "tv")
423
+ if (a.kind) cands = cands.filter((r) => (a.kind === "series" ? r.mediaType === "tv" : r.mediaType === "movie"))
424
+ if (a.year) cands = cands.filter((r) => ((r.releaseDate ?? r.firstAirDate ?? "").slice(0, 4)) === String(a.year))
425
+ const pick = cands[0]
426
+ if (!pick) {
427
+ return { resolved: false, reason: "no_tmdb_match", searched: { title: a.title, year: a.year ?? null, kind: a.kind ?? "any" },
428
+ human_action_required: true, human_action_reason: `No TMDB match for "${a.title}"${a.year ? ` (${a.year})` : ""}. Check the title or give a year.` }
429
+ }
430
+ tmdbId = pick.id
431
+ kind = pick.mediaType === "tv" ? "series" : "movie"
432
+ resolvedTitle = pick.title ?? pick.name
433
+ resolvedYear = Number((pick.releaseDate ?? pick.firstAirDate ?? "").slice(0, 4)) || null
434
+ }
435
+
436
+ const existing = await findExistingRequest(tmdbId, kind)
437
+ if (existing?.hasRequest) {
438
+ const shelf = shelfStateOf(kind, existing.media ?? {})
439
+ return {
440
+ resolved: true, title: resolvedTitle ?? existing.media?.title ?? null, year: resolvedYear, kind, tmdb_id: tmdbId,
441
+ request_id: `jellyseerr:${existing.id}`,
442
+ approval_state: "already_requested",
443
+ duplicate_of: `jellyseerr:${existing.id}`,
444
+ jellyseerr_status: REQUEST_STATUS[existing.status] ?? "unknown",
445
+ shelf_state: shelf,
446
+ submitted_at: existing.createdAt,
447
+ tvdb_id: existing.media?.tvdbId ?? null,
448
+ sonarr_id: kind === "series" ? (existing.media?.externalServiceId ?? null) : null,
449
+ radarr_id: kind === "movie" ? (existing.media?.externalServiceId ?? null) : null,
450
+ note: shelf === "available" ? "Already on the shelf." : "Already requested; use media_request_status to see why it has not landed.",
451
+ }
452
+ }
453
+
454
+ const payload = { mediaType: kind === "series" ? "tv" : "movie", mediaId: tmdbId }
455
+ if (kind === "series") {
456
+ payload.seasons = a.season_number ? [a.season_number] : "all"
457
+ }
458
+ const created = await seerr("/request", { method: "POST", body: payload })
459
+ return {
460
+ resolved: true, title: resolvedTitle, year: resolvedYear, kind, tmdb_id: tmdbId,
461
+ request_id: `jellyseerr:${created.id}`,
462
+ approval_state: REQUEST_STATUS[created.status] ?? "submitted",
463
+ duplicate_of: null,
464
+ jellyseerr_status: REQUEST_STATUS[created.status] ?? "submitted",
465
+ shelf_state: created.media?.status ? shelfStateOf(kind, created.media) : "not_on_shelf",
466
+ submitted_at: created.createdAt,
467
+ tvdb_id: created.media?.tvdbId ?? null,
468
+ sonarr_id: kind === "series" ? (created.media?.externalServiceId ?? null) : null,
469
+ radarr_id: kind === "movie" ? (created.media?.externalServiceId ?? null) : null,
470
+ seasons_requested: kind === "series" ? (a.season_number ? [a.season_number] : "all") : null,
471
+ note: "Submitted. The indexer hunt runs next; media_request_status will show whether a release was grabbed.",
472
+ }
473
+ }
474
+
475
+ // -------------------------------------------------- acquisition chain health
476
+
477
+ // The failure that stalled this house for three weeks: Prowlarr had zero indexers,
478
+ // so Sonarr reported "0 active indexers" and every request sat at "requested"
479
+ // forever. That must be a first-class, named answer — never something the agent
480
+ // has to infer from an empty release list.
481
+ async function chainHealth() {
482
+ const out = { indexers: { total: 0, enabled: 0, failing: [], ok: [] }, apps: [], problems: [], healthy: true }
483
+ try {
484
+ const list = await prowlarr("/indexer")
485
+ out.indexers.total = list.length
486
+ out.indexers.enabled = list.filter((i) => i.enable).length
487
+ const status = await prowlarr("/indexerstatus").catch(() => [])
488
+ const disabled = new Set((status ?? []).map((s) => s.indexerId))
489
+ for (const i of list) {
490
+ if (!i.enable) continue
491
+ ;(disabled.has(i.id) ? out.indexers.failing : out.indexers.ok).push(i.name)
492
+ }
493
+ const health = await prowlarr("/health").catch(() => [])
494
+ for (const h of health ?? []) {
495
+ if (h.type === "error" && /indexer/i.test(h.source ?? "")) out.problems.push({ service: "prowlarr", message: h.message })
496
+ }
497
+ out.apps = (await prowlarr("/applications").catch(() => [])).map((x) => ({ name: x.name, sync: x.syncLevel }))
498
+ } catch (e) {
499
+ out.problems.push({ service: "prowlarr", message: e.message })
500
+ }
501
+
502
+ if (out.indexers.total === 0) {
503
+ out.healthy = false
504
+ out.problems.push({ service: "prowlarr", message: "Prowlarr has zero indexers configured. Nothing can ever be found or downloaded until indexers are added." })
505
+ } else if (out.indexers.ok.length === 0) {
506
+ out.healthy = false
507
+ out.problems.push({ service: "prowlarr", message: "Every enabled indexer is currently failing. Searches will return nothing." })
508
+ }
509
+ if (out.apps.length === 0) {
510
+ out.healthy = false
511
+ out.problems.push({ service: "prowlarr", message: "Prowlarr is not syncing to Sonarr/Radarr, so they have no working indexers." })
512
+ }
513
+
514
+ for (const [name, call] of [["sonarr", sonarr], ["radarr", radarr]]) {
515
+ try {
516
+ const h = await call("/health")
517
+ for (const item of h ?? []) {
518
+ if (/indexer/i.test(item.source ?? "") && (item.type === "error" || /unavailable/i.test(item.message ?? ""))) {
519
+ out.problems.push({ service: name, message: item.message })
520
+ if (/all/i.test(item.message ?? "")) out.healthy = false
521
+ }
522
+ }
523
+ } catch (e) { out.problems.push({ service: name, message: e.message }) }
524
+ }
525
+ return out
526
+ }
527
+
528
+ // --------------------------------------------------- tool: request status
529
+
530
+ async function resolveTarget(a) {
531
+ if (a.tmdb_id) {
532
+ const r = await findExistingRequest(a.tmdb_id, a.kind)
533
+ if (r?.hasRequest) return r
534
+ }
535
+ if (a.request_id) {
536
+ const id = Number(String(a.request_id).replace(/^jellyseerr:/, ""))
537
+ if (Number.isFinite(id)) {
538
+ try { return await seerr(`/request/${id}`) } catch { /* fall through to title */ }
539
+ }
540
+ }
541
+ if (a.title) {
542
+ const body = await seerr("/search", { query: { query: a.title, page: 1 } })
543
+ // Only titles Jellyseerr already knows about can have a request behind them.
544
+ for (const pick of (body.results ?? []).filter((r) => r.mediaInfo)) {
545
+ const found = await findExistingRequest(pick.id, pick.mediaType === "tv" ? "series" : "movie")
546
+ if (found?.hasRequest) return found
547
+ }
548
+ // Jellyseerr's own search missed it: try the partial/typo-tolerant library
549
+ // match, and follow its best candidate back to a request by TMDB id.
550
+ const best = (await findLibraryCandidates(a.title).catch(() => [])).find((c) => c.tmdb_id)
551
+ if (best) {
552
+ const found = await findExistingRequest(best.tmdb_id, best.kind)
553
+ if (found?.hasRequest) return found
554
+ }
555
+ }
556
+ return null
557
+ }
558
+
559
+ export async function mediaRequestStatus(a) {
560
+ const request = await resolveTarget(a)
561
+ if (!request) {
562
+ const resolution = a.title ? await resolveTitle(a.title).catch(() => null) : null
563
+ return { found: false, reason: "no_matching_request",
564
+ searched: { request_id: a.request_id ?? null, tmdb_id: a.tmdb_id ?? null, title: a.title ?? null },
565
+ ...(resolution ? { library_matches: resolution.library_matches.slice(0, 10), lookup_candidates: resolution.lookup_candidates,
566
+ note: resolution.library_matches.length ? "Not requested through Jellyseerr, but these titles are already in the library. Use media_search_now with the service_id to act on one." : undefined } : {}),
567
+ diagnosis: { stuck_stage: "request", stuck_reason: "never_requested",
568
+ likely_fix: "Submit it with media_request.", human_action_required: false } }
569
+ }
570
+
571
+ const kind = request.type === "tv" ? "series" : "movie"
572
+ const media = request.media ?? {}
573
+ const shelf = shelfStateOf(kind, media)
574
+ const svcId = media.externalServiceId ?? null
575
+
576
+ const result = {
577
+ found: true,
578
+ request: {
579
+ id: `jellyseerr:${request.id}`,
580
+ kind,
581
+ tmdb_id: media.tmdbId ?? null,
582
+ tvdb_id: media.tvdbId ?? null,
583
+ jellyseerr_status: REQUEST_STATUS[request.status] ?? "unknown",
584
+ shelf_state: shelf,
585
+ submitted_at: request.createdAt,
586
+ sonarr_id: kind === "series" ? svcId : null,
587
+ radarr_id: kind === "movie" ? svcId : null,
588
+ },
589
+ search: null, download: null, file: null, chain: null, diagnosis: null,
590
+ }
591
+
592
+ let entity = null, queueRecs = [], history = []
593
+ try {
594
+ if (kind === "series" && svcId) {
595
+ entity = await sonarr(`/series/${svcId}`)
596
+ const q = await sonarr("/queue", { query: { pageSize: 200, includeSeries: true } })
597
+ queueRecs = (q.records ?? []).filter((r) => r.seriesId === svcId)
598
+ history = await sonarr("/history/series", { query: { seriesId: svcId } }).catch(() => [])
599
+ result.request.title = entity.title
600
+ result.file = { on_shelf: (entity.statistics?.episodeFileCount ?? 0) > 0,
601
+ episodes_on_disk: entity.statistics?.episodeFileCount ?? 0,
602
+ episodes_total: entity.statistics?.episodeCount ?? 0,
603
+ size_bytes: entity.statistics?.sizeOnDisk ?? 0,
604
+ path: entity.path ?? null }
605
+ } else if (kind === "movie" && svcId) {
606
+ entity = await radarr(`/movie/${svcId}`)
607
+ const q = await radarr("/queue", { query: { pageSize: 200 } })
608
+ queueRecs = (q.records ?? []).filter((r) => r.movieId === svcId)
609
+ history = await radarr("/history/movie", { query: { movieId: svcId } }).catch(() => [])
610
+ result.request.title = entity.title
611
+ result.file = { on_shelf: Boolean(entity.hasFile), size_bytes: entity.sizeOnDisk ?? 0, path: entity.path ?? null }
612
+ }
613
+ } catch (e) {
614
+ result.chain_error = e.message
615
+ }
616
+
617
+ const grabs = (history ?? []).filter((h) => h.eventType === "grabbed")
618
+ result.search = {
619
+ grab_attempts: grabs.length,
620
+ last_grab_at: grabs[0]?.date ?? null,
621
+ last_grab_title: grabs[0]?.sourceTitle ?? null,
622
+ monitored: entity ? Boolean(entity.monitored) : null,
623
+ }
624
+ const statusNow = Date.now()
625
+ result.download = computeDownloadState(queueRecs, statusNow, (r) => observeProgress(progressKey(r, kind), r.sizeleft ?? 0, statusNow))
626
+
627
+ const chain = await chainHealth()
628
+ result.chain = chain
629
+ result.diagnosis = diagnose({ shelf, result, chain, entity, kind })
630
+ // A title can match more than one tracked item: on 2026-11-19 "holmes" found the old Sherlock Holmes request while the
631
+ // person meant the Elizabeth Holmes documentary Radarr was waiting on. Name the other matches so the answer can too.
632
+ if (a.title && !a.tmdb_id && !a.request_id) {
633
+ const others = (await findLibraryCandidates(a.title).catch(() => []))
634
+ .filter((c) => !(c.kind === kind && ((c.tmdb_id && c.tmdb_id === result.request.tmdb_id) || (svcId && c.service_id === svcId))))
635
+ .slice(0, 5)
636
+ if (others.length) {
637
+ result.other_library_matches = others
638
+ result.other_library_matches_note = "The person may mean one of these tracked titles instead of the request above. Weigh them before answering, and name a likely one or ask which."
639
+ }
640
+ }
641
+ return result
642
+ }
643
+
644
+ // The deterministic core, split out so it can be tested without a live
645
+ // Sonarr/Radarr. `computeDownloadState` and `diagnose` are the whole reason the
646
+ // media surface can answer "why hasn't this downloaded" without the agent
647
+ // guessing, and D-013 (a stalled download read as progress) shipped verified
648
+ // only in production because there was no seam to test them through.
649
+ //
650
+ // A season pack shows up as one queue row per episode, all sharing one
651
+ // downloadId. Summing rows would report a 45 GB pack as 450 GB, so size and
652
+ // "how many downloads" are counted per distinct download, not per row. A
653
+ // torrent that has not moved a byte since it was grabbed is dead, not slow:
654
+ // Radarr reports trackedDownloadStatus "ok" for these indefinitely, so
655
+ // progress is measured against age rather than trusted from the row.
656
+ // The one stall rule: nothing downloaded yet, and older than the stall window.
657
+ // A download that never started, or one still unfinished days later (e.g. stuck at
658
+ // 99.85% with no seeders for the last piece), will not finish on its own.
659
+ const STUCK_INCOMPLETE_AFTER_HOURS = 72
660
+
661
+ export function isStalledRow(r, nowMs) {
662
+ if (!((r.size ?? 0) > 0) || !r.added) return false
663
+ const ageHours = (nowMs - Date.parse(r.added)) / 3_600_000
664
+ const left = r.sizeleft ?? 0
665
+ if (left >= r.size) return ageHours >= STALL_AFTER_HOURS
666
+ return left > 0 && ageHours >= STUCK_INCOMPLETE_AFTER_HOURS
667
+ }
668
+
669
+ const rowPercent = (r) => ((r.size ?? 0) > 0 ? Math.round((((r.size ?? 0) - (r.sizeleft ?? 0)) / r.size) * 100) : null)
670
+
671
+ // The one stall classification, shared by the status, diagnosis, queue, fill and blocklist
672
+ // surfaces. `previous` is the persisted progress memory for this download (or undefined).
673
+ // Returns null while the download may still be moving; otherwise the kind, whether the stall
674
+ // is confirmed (only confirmed stalls are acted on) and the facts the owner is told.
675
+ // The owner's three choices when a download is confirmed dead; one source for every surface that asks.
676
+ export const STALL_OWNER_CHOICES = ["keep_waiting", "find_another_release", "give_up"]
677
+
678
+ export function classifyStall(row, nowMs, previous) {
679
+ const why = stallReason(row, nowMs, previous)
680
+ if (!why) return null
681
+ const left = row.sizeleft ?? 0
682
+ const noEta = row.timeleft === undefined || row.timeleft === null || row.timeleft === "00:00:00"
683
+ const unchanged = previous && previous.sizeleft === left ? previous.at : null
684
+ return {
685
+ kind: why.stall, confirmed: why.confirmed, state: why.confirmed ? "stalled" : "suspected",
686
+ percent_complete: rowPercent(row),
687
+ age_hours: row.added ? Math.round((nowMs - Date.parse(row.added)) / 3_600_000) : null,
688
+ no_eta: noEta,
689
+ unchanged_since: unchanged === null ? null : new Date(unchanged).toISOString(),
690
+ unchanged_hours: unchanged === null ? null : Math.round((nowMs - unchanged) / 3_600_000),
691
+ }
692
+ }
693
+
694
+ // `previousFor(row)` reads the progress memory for a queue row; without it nothing is confirmed
695
+ // beyond the age rules.
696
+ export function computeDownloadState(queueRecs, nowMs, previousFor = () => undefined) {
697
+ const byDownload = new Map()
698
+ for (const r of queueRecs) byDownload.set(r.downloadId ?? `row:${r.id}`, r)
699
+ const downloads = [...byDownload.values()]
700
+ const sizeLeft = downloads.reduce((s, r) => s + (r.sizeleft ?? 0), 0)
701
+ const sizeTotal = downloads.reduce((s, r) => s + (r.size ?? 0), 0)
702
+ const classified = downloads
703
+ .map((r) => ({ r, c: classifyStall(r, nowMs, previousFor(r)) }))
704
+ .filter((x) => x.c)
705
+ .map(({ r, c }) => ({
706
+ title: r.title ?? null,
707
+ added_at: r.added ?? null,
708
+ size_gb: Number(((r.size ?? 0) / 1073741824).toFixed(2)),
709
+ queue_id: r.id ?? null,
710
+ ...c,
711
+ }))
712
+ const slowItems = downloads
713
+ .filter((r) => isStalledRow(r, nowMs) && (r.sizeleft ?? 0) < (r.size ?? 0) && !classifyStall(r, nowMs, previousFor(r)))
714
+ .map((r) => ({ title: r.title ?? null, percent_complete: rowPercent(r), timeleft: r.timeleft ?? null, age_hours: Math.round((nowMs - Date.parse(r.added)) / 3_600_000) }))
715
+ const stalledItems = classified.filter((i) => i.confirmed)
716
+ const suspectedItems = classified.filter((i) => !i.confirmed)
717
+ return {
718
+ active_downloads: downloads.length,
719
+ active_items: queueRecs.length,
720
+ states: [...new Set(downloads.map((r) => r.status))],
721
+ tracked_states: [...new Set(downloads.map((r) => r.trackedDownloadState).filter(Boolean))],
722
+ errors: [...new Set(downloads.map((r) => r.errorMessage).filter(Boolean))],
723
+ size_left_bytes: sizeLeft,
724
+ size_total_bytes: sizeTotal,
725
+ percent_complete: sizeTotal > 0 ? Math.round(((sizeTotal - sizeLeft) / sizeTotal) * 100) : null,
726
+ stalled: stalledItems.length > 0,
727
+ stalled_items: stalledItems,
728
+ suspected_items: suspectedItems,
729
+ slow_items: slowItems,
730
+ }
731
+ }
732
+
733
+ // The deterministic core. The agent must never have to work this out itself.
734
+ export function diagnose({ shelf, result, chain, entity, kind }) {
735
+ const file = result.file ?? {}
736
+ const onShelf = kind === "series" ? (file.episodes_on_disk ?? 0) > 0 : Boolean(file.on_shelf)
737
+ const complete = kind === "series" ? (file.episodes_on_disk ?? 0) >= (file.episodes_total ?? Infinity) : onShelf
738
+
739
+ if (complete) {
740
+ return { stuck_stage: null, stuck_reason: null, likely_fix: null, human_action_required: false,
741
+ summary: "On the shelf and complete. Nothing is stuck." }
742
+ }
743
+ if (result.download.stalled) {
744
+ const items = result.download.stalled_items
745
+ const partials = items.filter((i) => i.kind !== "never_started")
746
+ const neverStarted = items.filter((i) => i.kind === "never_started")
747
+ if (partials.length) {
748
+ // A partial download holds progress that removing it loses, and the owner's standing
749
+ // instruction for this case is to be asked, so nothing here acts on its own.
750
+ const facts = partials.map((i) => {
751
+ const since = i.unchanged_since ? ` since ${i.unchanged_since} (${i.unchanged_hours} hours)` : ""
752
+ return `${i.title ?? "A release"} is stuck at ${i.percent_complete}% with no download activity${since}; no seeders are serving the rest`
753
+ })
754
+ return { stuck_stage: "download", stuck_reason: "stalled_partial_download",
755
+ likely_fix: "ask_owner", human_action_required: true,
756
+ choices: STALL_OWNER_CHOICES,
757
+ percent_complete: result.download.percent_complete,
758
+ detail: items,
759
+ ...(neverStarted.length ? { never_started: { likely_fix: "blocklist_and_research", items: neverStarted } } : {}),
760
+ summary: `${facts.join(". ")}. Whether to keep waiting, find another release, or give up is the owner's choice: removing a partial download loses its progress, so this leaves it in place.${neverStarted.length ? ` Separately, ${neverStarted.length} download(s) didn't start (${neverStarted.map((i) => i.title ?? "a release").join("; ")}); those can be blocklisted and searched again (blocklist_and_research) without asking.` : ""} media_fill_missing can look for a seeded alternative without deleting the partial first; it removes the partial only after a seeded replacement is grabbed.` }
761
+ }
762
+ const oldest = Math.max(...items.map((i) => i.age_hours))
763
+ return { stuck_stage: "download", stuck_reason: "stalled_no_progress",
764
+ likely_fix: "blocklist_and_research", human_action_required: false,
765
+ percent_complete: result.download.percent_complete,
766
+ detail: items,
767
+ summary: `Stalled, not slow. ${items.length === 1 ? "The release" : `${items.length} releases`} ${items.length === 1 ? "has" : "have"} not downloaded anything in ${oldest} hours, which means no seeders rather than a quiet queue. Nothing was lost by waiting this long; blocklist the release and search again for a different one.` }
768
+ }
769
+ if (result.download.active_downloads > 0) {
770
+ const left = result.download.size_left_bytes
771
+ const total = result.download.size_total_bytes
772
+ const gb = (left / 1073741824).toFixed(1)
773
+ const pct = total > 0 ? Math.round(((total - left) / total) * 100) : null
774
+ const what = result.download.active_downloads === 1 && result.download.active_items > 1
775
+ ? `a ${result.download.active_items}-episode pack`
776
+ : `${result.download.active_downloads} download(s)`
777
+ const suspected = result.download.suspected_items ?? []
778
+ const slow = result.download.slow_items ?? []
779
+ return { stuck_stage: null, stuck_reason: null, likely_fix: null, human_action_required: false,
780
+ percent_complete: pct,
781
+ ...(suspected.length ? { stall_suspected: true, detail: suspected } : {}),
782
+ summary: `Downloading now — ${what}${pct === null ? "" : `, ${pct}% done`}, about ${gb} GB to go.${slow.length ? ` Slow but still moving: ${slow.map((i) => `${i.title ?? "a release"} is ${i.percent_complete}% done after ${i.age_hours} hours with an ETA of ${i.timeleft}`).join("; ")}.` : ""}${suspected.length ? ` It reports no ETA after ${Math.max(...suspected.map((i) => i.age_hours))} hours, so it may be stalled; the next check 30 minutes or more later confirms it. There is no ETA to give yet.` : ""}` }
783
+ }
784
+ if (result.download.errors.length) {
785
+ return { stuck_stage: "download", stuck_reason: "download_client_error", likely_fix: "retry_or_replace_release",
786
+ human_action_required: false, detail: result.download.errors,
787
+ summary: `The download client reported: ${result.download.errors.join("; ")}` }
788
+ }
789
+ if (!chain.healthy) {
790
+ return { stuck_stage: "indexers", stuck_reason: "acquisition_chain_down",
791
+ likely_fix: "restore_indexers", human_action_required: true,
792
+ detail: chain.problems,
793
+ summary: `Nothing can download: ${chain.problems.map((p) => p.message).join(" ")} This blocks every request, not just this one.` }
794
+ }
795
+ if (entity && entity.monitored === false) {
796
+ return { stuck_stage: "request", stuck_reason: "not_monitored", likely_fix: "enable_monitoring",
797
+ human_action_required: false, summary: "It is not monitored, so no search will ever run for it." }
798
+ }
799
+ if (result.search.grab_attempts === 0) {
800
+ return { stuck_stage: "search", stuck_reason: "no_search_run_or_no_acceptable_release",
801
+ likely_fix: "rescan", human_action_required: false,
802
+ summary: "Indexers are healthy but nothing has ever been grabbed. A fresh search (media_diagnose_and_fix action=rescan) is the next step." }
803
+ }
804
+ if (onShelf && !complete) {
805
+ return { stuck_stage: "import", stuck_reason: "partially_imported", likely_fix: "rescan",
806
+ human_action_required: false,
807
+ summary: `Partly here: ${file.episodes_on_disk} of ${file.episodes_total} episodes. The rest still need grabbing.` }
808
+ }
809
+ return { stuck_stage: "import", stuck_reason: "grabbed_but_not_imported", likely_fix: "force_import_scan",
810
+ human_action_required: false,
811
+ summary: `It was grabbed (${result.search.last_grab_title ?? "unknown release"}) but didn't land on the shelf.` }
812
+ }
813
+
814
+ // -------------------------------------------------- tool: diagnose_and_fix
815
+
816
+ async function mediaDiagnoseAndFix(a) {
817
+ const before = await mediaRequestStatus({ request_id: a.request_id, tmdb_id: a.tmdb_id, title: a.title })
818
+ if (!before.found) return { result: "no_such_request", before, after: null, human_action_required: true,
819
+ human_action_reason: "Nothing to fix — nobody requested it." }
820
+ const action = a.action ?? (before.diagnosis?.likely_fix ?? "rescan")
821
+
822
+ if (before.diagnosis?.stuck_reason === "acquisition_chain_down" && action !== "report_only") {
823
+ return { action, dry_run: Boolean(a.dry_run), result: "rejected_fix_unsafe", before, after: null,
824
+ human_action_required: true,
825
+ human_action_reason: "The acquisition chain itself is down (see before.chain.problems). Re-searching cannot help until indexers are restored." }
826
+ }
827
+ if (action === "ask_owner") {
828
+ return { action, result: "owner_decision_needed", before, after: null, human_action_required: true,
829
+ choices: before.diagnosis?.choices ?? STALL_OWNER_CHOICES,
830
+ ...(before.diagnosis?.never_started ? { never_started: before.diagnosis.never_started } : {}),
831
+ human_action_reason: before.diagnosis?.summary ?? "The owner decides." }
832
+ }
833
+ if (a.dry_run) {
834
+ return { action, dry_run: true, result: "would_apply", before,
835
+ would_do: describeAction(action), human_action_required: false }
836
+ }
837
+
838
+ const kind = before.request.kind
839
+ const svcId = kind === "series" ? before.request.sonarr_id : before.request.radarr_id
840
+ if (!svcId) return { action, result: "manual_required", before, after: null, human_action_required: true,
841
+ human_action_reason: "This request is not yet mapped into Sonarr/Radarr, so no search can be triggered." }
842
+
843
+ let commanded = null
844
+ if (action === "rescan" || action === "enable_monitoring" || action === "force_import_scan") {
845
+ if (action === "enable_monitoring") {
846
+ if (kind === "series") await sonarr(`/series/${svcId}`, { method: "PUT", body: { ...(await sonarr(`/series/${svcId}`)), monitored: true } })
847
+ else await radarr(`/movie/${svcId}`, { method: "PUT", body: { ...(await radarr(`/movie/${svcId}`)), monitored: true } })
848
+ }
849
+ const cmd = kind === "series"
850
+ ? (action === "force_import_scan" ? { name: "RescanSeries", seriesId: svcId } : { name: "SeriesSearch", seriesId: svcId })
851
+ : (action === "force_import_scan" ? { name: "RescanMovie", movieIds: [svcId] } : { name: "MoviesSearch", movieIds: [svcId] })
852
+ commanded = kind === "series" ? await sonarr("/command", { method: "POST", body: cmd }) : await radarr("/command", { method: "POST", body: cmd })
853
+ } else if (action === "blocklist_and_research") {
854
+ // Removing with blocklist=true is what stops the same dead release being
855
+ // grabbed straight back. The search that follows is then free to pick a
856
+ // different one.
857
+ // Only a download that never started: a partial holds progress and is the owner's call.
858
+ const stalled = (before.download.stalled_items ?? []).filter((i) => i.kind === "never_started")
859
+ if (!stalled.length) return { action, result: "nothing_to_blocklist", before, after: null, human_action_required: false,
860
+ human_action_reason: "No download has been sitting at zero long enough to call it stalled. A partial download is not removed this way: ask the owner." }
861
+ for (const item of stalled) {
862
+ if (item.queue_id === null) continue
863
+ const client = kind === "series" ? sonarr : radarr
864
+ await client(`/queue/${item.queue_id}`, { method: "DELETE", query: { removeFromClient: true, blocklist: true, skipRedownload: true } })
865
+ }
866
+ const cmd = kind === "series" ? { name: "SeriesSearch", seriesId: svcId } : { name: "MoviesSearch", movieIds: [svcId] }
867
+ commanded = kind === "series" ? await sonarr("/command", { method: "POST", body: cmd }) : await radarr("/command", { method: "POST", body: cmd })
868
+ } else {
869
+ return { action, result: "unsupported_action", before, after: null, human_action_required: true,
870
+ human_action_reason: `Action "${action}" is not implemented. Supported: rescan, enable_monitoring, force_import_scan, blocklist_and_research, report_only.` }
871
+ }
872
+
873
+ await new Promise((r) => setTimeout(r, 12_000))
874
+ const after = await mediaRequestStatus({ request_id: a.request_id, tmdb_id: a.tmdb_id, title: a.title })
875
+ return {
876
+ action, dry_run: false, applied_at: new Date().toISOString(),
877
+ command: { id: commanded?.id ?? null, name: commanded?.name ?? null },
878
+ before: { diagnosis: before.diagnosis, grab_attempts: before.search.grab_attempts, active_downloads: before.download.active_downloads },
879
+ after: { diagnosis: after.diagnosis, grab_attempts: after.search.grab_attempts, active_downloads: after.download.active_downloads },
880
+ result: after.download.active_downloads > before.download.active_downloads ? "grabbed_and_downloading"
881
+ : after.search.grab_attempts > before.search.grab_attempts ? "grabbed"
882
+ : "queued_for_search",
883
+ human_action_required: Boolean(after.diagnosis?.human_action_required),
884
+ human_action_reason: after.diagnosis?.human_action_required ? after.diagnosis.summary : null,
885
+ }
886
+ }
887
+
888
+ function describeAction(action) {
889
+ return {
890
+ rescan: "Trigger a fresh indexer search and grab the best acceptable release.",
891
+ enable_monitoring: "Mark it monitored, then search.",
892
+ force_import_scan: "Re-scan the disk so an already-downloaded file gets imported.",
893
+ blocklist_and_research: "Blocklist the stalled release so it cannot be grabbed again, then search for a different one.",
894
+ report_only: "Report only; change nothing.",
895
+ }[action] ?? "Unknown action."
896
+ }
897
+
898
+ // ------------------------------------------------------- tool: play/resolve
899
+
900
+ async function mediaPlayOrResolve(a) {
901
+ const status = await mediaRequestStatus({ request_id: a.request_id, tmdb_id: a.tmdb_id, title: a.title })
902
+ if (!status.found || !status.file) {
903
+ return { playable: false, reason: "not_on_shelf", diagnosis: status.diagnosis ?? null,
904
+ human_action_required: true, human_action_reason: "It is not on the shelf yet." }
905
+ }
906
+ const onShelf = status.request.kind === "series" ? (status.file.episodes_on_disk ?? 0) > 0 : status.file.on_shelf
907
+ return {
908
+ playable: Boolean(onShelf),
909
+ title: status.request.title ?? null,
910
+ kind: status.request.kind,
911
+ tmdb_id: status.request.tmdb_id,
912
+ episodes_on_disk: status.file.episodes_on_disk ?? null,
913
+ episodes_total: status.file.episodes_total ?? null,
914
+ path: status.file.path,
915
+ size_bytes: status.file.size_bytes,
916
+ play_url: onShelf && JELLYFIN_WEB ? `${JELLYFIN_WEB}/web/index.html#!/search.html?query=${encodeURIComponent(status.request.title ?? "")}` : null,
917
+ diagnosis: status.diagnosis,
918
+ }
919
+ }
920
+
921
+ // --------------------------------------------------------- tool: chain health
922
+
923
+ async function mediaChainHealth() {
924
+ const chain = await chainHealth()
925
+ return {
926
+ healthy: chain.healthy,
927
+ indexers: chain.indexers,
928
+ app_sync: chain.apps,
929
+ problems: chain.problems,
930
+ summary: chain.healthy
931
+ ? `Acquisition chain healthy: ${chain.indexers.ok.length} of ${chain.indexers.enabled} enabled indexers responding${chain.indexers.failing.length ? `, failing: ${chain.indexers.failing.join(", ")}` : ""}.`
932
+ : `Acquisition chain DOWN. ${chain.problems.map((p) => p.message).join(" ")}`,
933
+ }
934
+ }
935
+
936
+ // ------------------------------------- tools: search_now / blocklist_stalled
937
+
938
+ // Act on an item already in Sonarr/Radarr directly; no Jellyseerr request needed.
939
+ // Never adds a library item: an unknown title is reported, not created.
940
+ const arrFor = (kind) => (kind === "series" ? sonarr : radarr)
941
+
942
+ async function resolveLibraryItem(a) {
943
+ let candidates
944
+ if ((a.service_id !== undefined && a.service_id !== null) || a.tmdb_id) {
945
+ const list = await arrFor(a.kind)(a.kind === "series" ? "/series" : "/movie")
946
+ const items = (Array.isArray(list) ? list : []).map((i) => { const { overview, ...c } = libraryCandidate(a.kind, i); return c })
947
+ const hit = items.filter((i) => (a.service_id !== undefined && a.service_id !== null ? i.service_id === Number(a.service_id) : i.tmdb_id === Number(a.tmdb_id)))
948
+ if (hit.length === 1) return { item: { id: hit[0].service_id, title: hit[0].title } }
949
+ candidates = hit
950
+ } else if (a.title) {
951
+ const ranked = (await findLibraryCandidates(a.title, a.kind)).filter((c) => c.service_id !== null)
952
+ // Act only when the best tier holds exactly one item and it is not merely a
953
+ // typo-distance match; otherwise name the candidates and let the caller pick.
954
+ const bestTier = ranked.filter((c) => c.match === ranked[0]?.match)
955
+ if (bestTier.length === 1 && bestTier[0].match !== "fuzzy" && bestTier[0].match !== "subject") return { item: { id: bestTier[0].service_id, title: bestTier[0].title } }
956
+ if (!ranked.length) {
957
+ const lookup = (await lookupCandidates(a.title, a.kind)).filter((c) => !c.in_library).map((c) => ({ ...c, not_in_library: true }))
958
+ return { result: "not_found", candidates: lookup }
959
+ }
960
+ candidates = ranked
961
+ } else candidates = []
962
+ return { result: candidates.length ? "ambiguous" : "not_found", candidates: candidates.slice(0, 10) }
963
+ }
964
+
965
+ const QUEUE_PAGE_SIZE = 200
966
+ const QUEUE_MAX_PAGES = 20
967
+
968
+ // The item's queue rows. Filtered server-side (seriesIds/movieIds) and paged, so a
969
+ // long queue cannot hide a row; the client-side filter stays as the backstop.
970
+ async function itemQueue(kind, serviceId) {
971
+ const client = arrFor(kind)
972
+ const idKey = kind === "series" ? "seriesId" : "movieId"
973
+ const filter = kind === "series" ? { seriesIds: serviceId, includeSeries: true } : { movieIds: serviceId }
974
+ const rows = []
975
+ for (let page = 1; page <= QUEUE_MAX_PAGES; page++) {
976
+ const q = await client("/queue", { query: { ...filter, page, pageSize: QUEUE_PAGE_SIZE } })
977
+ const records = q?.records ?? []
978
+ rows.push(...records)
979
+ if (!records.length || !(Number(q?.totalRecords) > page * QUEUE_PAGE_SIZE)) break
980
+ }
981
+ return rows.filter((r) => r[idKey] === serviceId)
982
+ }
983
+
984
+ function queueReport(rows, kind = "series") {
985
+ const now = Date.now()
986
+ return rows.map((r) => {
987
+ const c = classifyStall(r, now, peekProgress(progressKey(r, kind), r.sizeleft ?? 0, now))
988
+ return { queue_id: r.id ?? null, title: r.title ?? null, status: r.status ?? null,
989
+ size_left_bytes: r.sizeleft ?? 0, stalled: Boolean(c?.confirmed), ...(c ? { stall_kind: c.kind } : {}) }
990
+ })
991
+ }
992
+
993
+ // ------------------------------------------------------------ tool: media_queue
994
+
995
+ const QUEUE_VIEW_MAX_ROWS = 100
996
+
997
+ // One queue row as the owner's torrent or usenet client reports it through Sonarr/Radarr.
998
+ export function queueRowView(r, nowMs, previous) {
999
+ const c = classifyStall(r, nowMs, previous)
1000
+ return {
1001
+ queue_id: r.id ?? null, title: r.title ?? null, status: r.status ?? null,
1002
+ tracked_download_state: r.trackedDownloadState ?? null, tracked_download_status: r.trackedDownloadStatus ?? null,
1003
+ percent: pct(r), timeleft: r.timeleft ?? null, size_left_bytes: r.sizeleft ?? 0, size_bytes: r.size ?? 0,
1004
+ protocol: r.protocol ?? null, download_client: r.downloadClient ?? null, indexer: r.indexer ?? null,
1005
+ added: r.added ?? null, stalled: Boolean(c?.confirmed),
1006
+ ...(c ? { stall: { kind: c.kind, state: c.state, percent_complete: c.percent_complete, age_hours: c.age_hours, no_eta: c.no_eta, unchanged_since: c.unchanged_since,
1007
+ ...(c.confirmed ? { owner_decision_needed: true, likely_fix: "ask_owner", choices: STALL_OWNER_CHOICES } : {}) } } : {}),
1008
+ ...(r.errorMessage ? { error_message: String(r.errorMessage).slice(0, 300) } : {}),
1009
+ }
1010
+ }
1011
+
1012
+ // A film or show never ships as a program or a zip. A download whose name or files end in one, or that Sonarr/Radarr flag for an
1013
+ // executable, is a fake release (often malware); the household's standing rule is to clear and blocklist it on sight.
1014
+ export const FAKE_RELEASE_FILE = /\.(exe|scr|bat|msi|cmd|com|vbs|ps1|lnk|zip)$/iu
1015
+ const EXECUTABLE_WARNING = /executable file/iu
1016
+
1017
+ /** Why a queue row is a fake release, or null when it is not one. */
1018
+ export function fakeReleaseReason(r) {
1019
+ for (const name of [r.title, r.outputPath]) {
1020
+ const m = typeof name === "string" ? name.trim().match(FAKE_RELEASE_FILE) : null
1021
+ if (m) return `its name ends in .${m[1].toLowerCase()}, a program or archive, not a video`
1022
+ }
1023
+ for (const s of r.statusMessages ?? []) {
1024
+ for (const line of [s?.title, ...(s?.messages ?? [])]) {
1025
+ if (typeof line !== "string") continue
1026
+ const m = line.trim().match(FAKE_RELEASE_FILE)
1027
+ if (m) return `it holds ${line.trim()}, a program or archive, not a video`
1028
+ if (EXECUTABLE_WARNING.test(line)) return `${serviceName(r)} flagged it: ${line.trim()}`
1029
+ }
1030
+ }
1031
+ return null
1032
+ }
1033
+ const serviceName = (r) => (r.seriesId !== undefined ? "Sonarr" : "Radarr")
1034
+
1035
+ /** Clears and blocklists the fake releases among rows, so the app looks for a real copy; returns what it cleared. */
1036
+ export async function clearFakeReleases(kind, rows) {
1037
+ const fakes = rows.map((r) => ({ r, reason: fakeReleaseReason(r) })).filter((f) => f.reason)
1038
+ if (!fakes.length) return { kept: rows, cleared: [], failed: [] }
1039
+ const cleared = []
1040
+ const failed = []
1041
+ const seen = new Set()
1042
+ const stuck = new Set()
1043
+ const keyOf = (r) => r.downloadId ?? `row-${r.id}`
1044
+ // Rows of one season pack share a download: removing one removes it, so each download is removed once.
1045
+ for (const { r, reason } of fakes) {
1046
+ const key = keyOf(r)
1047
+ if (seen.has(key)) continue
1048
+ seen.add(key)
1049
+ try {
1050
+ await arrFor(kind)(`/queue/${r.id}`, { method: "DELETE", query: { removeFromClient: true, blocklist: true, skipRedownload: false } })
1051
+ cleared.push({ title: r.title ?? null, reason })
1052
+ } catch (error) {
1053
+ stuck.add(key)
1054
+ failed.push({ queue_id: r.id ?? null, title: r.title ?? null, reason, error: String(error?.message ?? error).slice(0, 200) })
1055
+ }
1056
+ }
1057
+ return { kept: rows.filter((r) => !seen.has(keyOf(r)) || stuck.has(keyOf(r))), cleared, failed }
1058
+ }
1059
+
1060
+ // The Sonarr/Radarr download queue (torrent and usenet alike). Its only write is the standing fake-release rule above.
1061
+ export async function mediaQueue(a) {
1062
+ if (a.kind !== "series" && a.kind !== "movie") return { result: "invalid_kind", message: "kind must be 'series' or 'movie'." }
1063
+ let rows
1064
+ let item = null
1065
+ let total = null
1066
+ if ((a.service_id !== undefined && a.service_id !== null) || a.tmdb_id || a.title) {
1067
+ const found = await resolveLibraryItem(a)
1068
+ if (!found.item) return { result: found.result, kind: a.kind, candidates: found.candidates }
1069
+ item = found.item
1070
+ rows = await itemQueue(a.kind, item.id)
1071
+ } else {
1072
+ rows = []
1073
+ const client = arrFor(a.kind)
1074
+ for (let page = 1; page <= QUEUE_MAX_PAGES; page++) {
1075
+ const q = await client("/queue", { query: { page, pageSize: QUEUE_PAGE_SIZE, ...(a.kind === "series" ? { includeSeries: true } : {}) } })
1076
+ const records = q?.records ?? []
1077
+ rows.push(...records)
1078
+ if (Number.isFinite(Number(q?.totalRecords))) total = Number(q.totalRecords)
1079
+ if (!records.length || !(Number(q?.totalRecords) > page * QUEUE_PAGE_SIZE) || rows.length >= QUEUE_VIEW_MAX_ROWS) break
1080
+ }
1081
+ }
1082
+ const fakes = await clearFakeReleases(a.kind, rows)
1083
+ rows = fakes.kept
1084
+ total = Math.max((total ?? 0) - fakes.cleared.length, rows.length)
1085
+ const now = Date.now()
1086
+ // Looking records the sighting in the local progress memory (never in Sonarr/Radarr), so this call can confirm a stall too.
1087
+ const shown = rows.slice(0, QUEUE_VIEW_MAX_ROWS).map((r) => queueRowView(r, now, observeProgress(progressKey(r, a.kind), r.sizeleft ?? 0, now)))
1088
+ return {
1089
+ kind: a.kind, ...(item ? { service_id: item.id, title: item.title } : {}),
1090
+ count: total, shown: shown.length, ...(total > shown.length ? { truncated: true } : {}), queue: shown,
1091
+ ...(fakes.cleared.length ? { cleared_fakes: fakes.cleared, cleared_note: "These were fake releases (a program or archive, not a video). Each is removed from the download client and blocklisted, and Sonarr/Radarr will look for a real copy. Tell the person in one line which title and why; no decision is needed." } : {}),
1092
+ ...(fakes.failed.length ? { fakes_not_cleared: fakes.failed } : {}),
1093
+ summary: !total ? "Nothing for this is in the Sonarr/Radarr queue."
1094
+ : `${total} queue row${total === 1 ? "" : "s"}${total > shown.length ? ` (showing ${shown.length})` : ""}; ${shown.filter((r) => r.stalled).length} stalled${shown.some((r) => r.stall?.state === "suspected") ? `, ${shown.filter((r) => r.stall?.state === "suspected").length} suspected (no ETA, to be confirmed by a check 30 minutes later)` : ""}.`,
1095
+ note: "Sonarr/Radarr don't report seeders or peers. A row stuck at the same percent with no timeleft is the stall signal; for a release's seeder count use media_indexer_search.",
1096
+ }
1097
+ }
1098
+
1099
+ async function runSearch(kind, serviceId) {
1100
+ const body = kind === "series" ? { name: "SeriesSearch", seriesId: serviceId } : { name: "MoviesSearch", movieIds: [serviceId] }
1101
+ const c = await arrFor(kind)("/command", { method: "POST", body })
1102
+ return { id: c?.id ?? null, name: c?.name ?? body.name, status: c?.status ?? null }
1103
+ }
1104
+
1105
+ export async function mediaSearchNow(a) {
1106
+ if (a.kind !== "series" && a.kind !== "movie") return { result: "invalid_kind", message: "kind must be 'series' or 'movie'." }
1107
+ const found = await resolveLibraryItem(a)
1108
+ if (!found.item) return { result: found.result, kind: a.kind, candidates: found.candidates }
1109
+ const { item } = found
1110
+ const command = await runSearch(a.kind, item.id)
1111
+ const queue = queueReport(await itemQueue(a.kind, item.id), a.kind)
1112
+ const rows = queue.length
1113
+ const summary = `${a.kind === "series" ? "Sonarr" : "Radarr"} started a search for ${item.title}; ${rows === 0 ? "nothing is downloading for it yet" : `${rows} download${rows === 1 ? " is" : "s are"} in its queue`}.`
1114
+ return { result: "search_started", kind: a.kind, service_id: item.id, title: item.title, command, queue, summary }
1115
+ }
1116
+
1117
+ // Whether a download may be removed without the owner naming it. A download that has never
1118
+ // started is dead once past the stall window. A partial one is dead only when observed with no
1119
+ // ETA and no progress across 30 minutes: age alone is not enough (a 75.9% pack with no seeders
1120
+ // today can finish when one returns), and anything with an ETA is still moving.
1121
+ const hasEta = (row) => row.timeleft !== undefined && row.timeleft !== null && row.timeleft !== "00:00:00"
1122
+ export function removalVerdict(row, nowMs, previous) {
1123
+ if (hasEta(row)) return "still_downloading"
1124
+ const left = row.sizeleft ?? 0
1125
+ if ((row.size ?? 0) > 0 && left >= row.size) return isStalledRow(row, nowMs) ? "dead" : "not_started_yet"
1126
+ if (row.status === "failed") return "dead"
1127
+ const unchanged = previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS
1128
+ return unchanged ? "dead" : "stall_unconfirmed"
1129
+ }
1130
+
1131
+ export async function mediaBlocklistStalled(a) {
1132
+ if (a.kind !== "series" && a.kind !== "movie") return { result: "invalid_kind", message: "kind must be 'series' or 'movie'." }
1133
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1134
+ const serviceId = Number(a.service_id)
1135
+ const rows = await itemQueue(a.kind, serviceId)
1136
+ const now = Date.now()
1137
+ let targets
1138
+ if (Array.isArray(a.queue_ids) && a.queue_ids.length) {
1139
+ const own = new Set(rows.map((r) => r.id))
1140
+ const foreign = a.queue_ids.filter((id) => !own.has(id))
1141
+ if (foreign.length) return { result: "queue_id_not_for_item", foreign_queue_ids: foreign, queue: queueReport(rows, a.kind) }
1142
+ targets = rows.filter((r) => a.queue_ids.includes(r.id))
1143
+ } else {
1144
+ // Candidates only: removalVerdict below confirms a no-ETA partial against the progress memory.
1145
+ targets = rows.filter((r) => stallReason(r, now, undefined) !== null)
1146
+ }
1147
+ // A season pack is many queue rows sharing one downloadId; deleting one removes
1148
+ // the download for all, so delete once per download.
1149
+ const seen = new Set()
1150
+ targets = targets.filter((r) => {
1151
+ const key = r.downloadId ? `d:${r.downloadId}` : `q:${r.id}`
1152
+ if (seen.has(key)) return false
1153
+ seen.add(key)
1154
+ return true
1155
+ })
1156
+ // Removing a download deletes its progress. Unless the owner asked for this download to go,
1157
+ // only a download confirmed dead is removed: one still moving, or stalled without a second
1158
+ // observation 30 minutes apart, may yet finish (2026-10-05: a 75.9% pack, the only copy, was
1159
+ // deleted on "yes please get them").
1160
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
1161
+ if (ownerWords && !(Array.isArray(a.queue_ids) && a.queue_ids.length)) {
1162
+ return { result: "owner_words_need_queue_ids", message: "owner_words removes only downloads the owner named: pass their queue_ids too.", queue: queueReport(rows, a.kind) }
1163
+ }
1164
+ const kept = []
1165
+ if (!ownerWords) {
1166
+ targets = targets.filter((r) => {
1167
+ const verdict = removalVerdict(r, now, observeProgress(progressKey(r, a.kind), r.sizeleft ?? 0, now))
1168
+ if (verdict === "dead") return true
1169
+ kept.push({ queue_id: r.id, title: r.title ?? null, percent: pct(r), reason: verdict })
1170
+ return false
1171
+ })
1172
+ }
1173
+ if (!targets.length && kept.length) {
1174
+ return { result: "kept_downloads", kept, queue: queueReport(rows, a.kind),
1175
+ message: "Nothing removed. These downloads are not confirmed dead, and removing one deletes its progress. A partial download counts as dead only after two calls at least 30 minutes apart see no progress and no ETA; call again later to confirm. For missing episodes call media_fill_missing instead: it replaces a stalled download only when a seeded alternative exists. Pass owner_words only with the owner's own words asking to remove, clear or cancel this download; 'get them' is not that." }
1176
+ }
1177
+ if (!targets.length) return { result: "nothing_to_blocklist", queue: queueReport(rows, a.kind) }
1178
+ // A dry run returns the plan: no DELETE, no blocklist entry, no new search.
1179
+ if (a.dry_run === true) {
1180
+ return { result: "dry_run", would_remove: targets.map((r) => ({ queue_id: r.id, title: r.title ?? null, percent: pct(r) })), would_search_again: a.research !== false,
1181
+ ...(kept.length ? { kept } : {}), ...(ownerWords ? { owner_words: ownerWords } : {}), queue: queueReport(rows, a.kind) }
1182
+ }
1183
+ const removed = []
1184
+ const failed = []
1185
+ for (const row of targets) {
1186
+ try {
1187
+ await arrFor(a.kind)(`/queue/${row.id}`, { method: "DELETE", query: { removeFromClient: true, blocklist: true, skipRedownload: true } })
1188
+ removed.push(row.id)
1189
+ } catch (e) {
1190
+ // 404: the row went away (finished or removed with its pack); not a failure to retry.
1191
+ if (/_http_404$/.test(e.code ?? "")) removed.push(row.id)
1192
+ else failed.push({ queue_id: row.id, error: e.message })
1193
+ }
1194
+ }
1195
+ const command = a.research === false ? null : await runSearch(a.kind, serviceId)
1196
+ return { removed, ...(failed.length ? { failed } : {}), ...(kept.length ? { kept } : {}), ...(ownerWords ? { removed_on_owner_words: ownerWords } : {}), command, queue: queueReport(await itemQueue(a.kind, serviceId), a.kind) }
1197
+ }
1198
+
1199
+ // ------------------------------- tools: episodes / releases / blocklist / import
1200
+
1201
+ // When an automatic search finds nothing, the Butler works the release by hand:
1202
+ // list the episodes, read what the indexers offer and how Sonarr parsed it, grab
1203
+ // the right one with an explicit episode mapping, and map downloaded files by title.
1204
+ // All scoped to series/movies already in the library; nothing here adds one.
1205
+
1206
+ const kindOk = (a) => a.kind === "series" || a.kind === "movie"
1207
+ const invalidKind = () => ({ result: "invalid_kind", message: "kind must be 'series' or 'movie'." })
1208
+ const idKeyOf = (kind) => (kind === "series" ? "seriesId" : "movieId")
1209
+ const code2 = (n) => String(n).padStart(2, "0")
1210
+ const sxe = (e) => `S${code2(e.seasonNumber)}E${code2(e.episodeNumber)}`
1211
+
1212
+ async function seriesEpisodes(seriesId, seasonNumber) {
1213
+ const list = await sonarr("/episode", { query: { seriesId, seasonNumber } })
1214
+ return Array.isArray(list) ? list : []
1215
+ }
1216
+
1217
+ export async function mediaEpisodes(a) {
1218
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1219
+ const seriesId = Number(a.service_id)
1220
+ const eps = await seriesEpisodes(seriesId, a.season_number)
1221
+ return {
1222
+ series_id: seriesId,
1223
+ season_number: a.season_number ?? null,
1224
+ count: eps.length,
1225
+ episodes: eps.map((e) => ({ episode_id: e.id, code: sxe(e), season: e.seasonNumber, episode: e.episodeNumber, title: e.title ?? null,
1226
+ air_date: e.airDate ?? null, has_file: Boolean(e.hasFile), monitored: Boolean(e.monitored),
1227
+ // Release names follow scene (often streaming) numbering; Sonarr's own mapping, when it has one.
1228
+ scene_code: Number.isInteger(e.sceneSeasonNumber) && Number.isInteger(e.sceneEpisodeNumber)
1229
+ ? `S${String(e.sceneSeasonNumber).padStart(2, "0")}E${String(e.sceneEpisodeNumber).padStart(2, "0")}` : null })),
1230
+ }
1231
+ }
1232
+
1233
+ // Season and episode monitoring: what Sonarr searches for on its own. A season's flag lives on the series;
1234
+ // its episodes carry their own flags, so both are set to match.
1235
+ export async function mediaMonitor(a) {
1236
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1237
+ const seasons = Array.isArray(a.season_numbers) ? a.season_numbers.map(Number) : []
1238
+ const picked = Array.isArray(a.episode_ids) ? a.episode_ids.map(Number) : []
1239
+ if (!seasons.length && !picked.length) return { result: "seasons_or_episodes_required" }
1240
+ if (typeof a.monitored !== "boolean") return { result: "monitored_required" }
1241
+ const seriesId = Number(a.service_id)
1242
+ const episodeIds = [...picked]
1243
+ if (seasons.length) {
1244
+ const series = await sonarr(`/series/${seriesId}`)
1245
+ const has = (series.seasons ?? []).map((x) => x.seasonNumber)
1246
+ const unknown = seasons.filter((n) => !has.includes(n))
1247
+ if (unknown.length) return { result: "unknown_season", series_id: seriesId, seasons: unknown, has }
1248
+ await sonarr(`/series/${seriesId}`, { method: "PUT", body: { ...series, seasons: series.seasons.map((x) => seasons.includes(x.seasonNumber) ? { ...x, monitored: a.monitored } : x) } })
1249
+ for (const e of await seriesEpisodes(seriesId)) if (seasons.includes(e.seasonNumber) && !episodeIds.includes(e.id)) episodeIds.push(e.id)
1250
+ }
1251
+ if (episodeIds.length) await sonarr("/episode/monitor", { method: "PUT", body: { episodeIds, monitored: a.monitored } })
1252
+ const searched = []
1253
+ if (a.search && a.monitored) {
1254
+ for (const seasonNumber of seasons) {
1255
+ await sonarr("/command", { method: "POST", body: { name: "SeasonSearch", seriesId, seasonNumber } })
1256
+ searched.push(`season ${seasonNumber}`)
1257
+ }
1258
+ if (picked.length) {
1259
+ await sonarr("/command", { method: "POST", body: { name: "EpisodeSearch", episodeIds: picked } })
1260
+ searched.push(`episodes ${picked.join(", ")}`)
1261
+ }
1262
+ }
1263
+ return { result: "monitoring_changed", series_id: seriesId, monitored: a.monitored, seasons, episode_ids: episodeIds, searched }
1264
+ }
1265
+
1266
+ const WATCH_STATES = ["all", "played", "in_progress"]
1267
+ const jellyfin = (path, opts = {}) => req(JELLYFIN.url, path, { key: JELLYFIN.apiKey, header: "X-Emby-Token", ...opts })
1268
+
1269
+ // One Jellyfin user's watched and half-watched items, newest first.
1270
+ export async function mediaWatchHistory(a) {
1271
+ if (!JELLYFIN.url || !JELLYFIN.apiKey) return { result: "jellyfin_not_configured" }
1272
+ const state = a.state ?? "all"
1273
+ if (!WATCH_STATES.includes(state)) return { result: "bad_state", states: WATCH_STATES }
1274
+ const users = (await jellyfin("/Users")) ?? []
1275
+ const names = users.map((u) => u.Name)
1276
+ if (!a.user) return { result: "user_required", users: names }
1277
+ const wanted = String(a.user).toLowerCase()
1278
+ const user = users.find((u) => u.Id === a.user || String(u.Name).toLowerCase() === wanted)
1279
+ if (!user) return { result: "unknown_user", users: names }
1280
+ const filters = state === "all" ? ["IsResumable", "IsPlayed"] : [state === "played" ? "IsPlayed" : "IsResumable"]
1281
+ const pages = await Promise.all(filters.map((Filters) => jellyfin(`/Users/${user.Id}/Items`, { query: {
1282
+ Filters, Recursive: true, IncludeItemTypes: "Episode,Movie", Fields: "UserData", SortBy: "DatePlayed", SortOrder: "Descending", Limit: 500 } })))
1283
+ const title = a.title ? normalizeTitle(String(a.title)) : null
1284
+ const items = pages.flatMap((page) => page?.Items ?? [])
1285
+ .filter((i) => !title || [i.Name, i.SeriesName].some((n) => n && normalizeTitle(n).includes(title)))
1286
+ .map((i) => {
1287
+ const d = i.UserData ?? {}
1288
+ const episode = i.Type === "Episode"
1289
+ return { kind: episode ? "episode" : "movie", title: i.Name, series: i.SeriesName ?? null,
1290
+ code: episode && Number.isInteger(i.ParentIndexNumber) && Number.isInteger(i.IndexNumber) ? sxe({ seasonNumber: i.ParentIndexNumber, episodeNumber: i.IndexNumber }) : null,
1291
+ played: Boolean(d.Played), percent: d.Played ? 100 : Math.round(d.PlayedPercentage ?? 0), play_count: d.PlayCount ?? 0, last_played: d.LastPlayedDate ?? null }
1292
+ })
1293
+ .sort((x, y) => String(y.last_played ?? "").localeCompare(String(x.last_played ?? "")))
1294
+ .slice(0, Number(a.limit) > 0 ? Number(a.limit) : 50)
1295
+ return { result: "watch_history", user: user.Name, count: items.length, items }
1296
+ }
1297
+
1298
+ // Free-text search across every Prowlarr indexer: discovery only, it grabs nothing.
1299
+ // Sonarr's own search only asks for the season/episode codes it expects; this finds
1300
+ // what exists under any name (another numbering, a "Season 2 (2020)" pack, an episode title).
1301
+ export async function mediaIndexerSearch(a) {
1302
+ const query = typeof a.query === "string" ? a.query.trim() : ""
1303
+ if (!query) return { result: "query_required" }
1304
+ const raw = await prowlarr("/search", { query: { query, type: "search", limit: 100 }, timeoutMs: SEARCH_TIMEOUT_MS })
1305
+ const limit = Math.min(Math.max(Number(a.limit) || 25, 1), 50)
1306
+ const rows = (Array.isArray(raw) ? raw : [])
1307
+ .map((r) => ({ indexer: r.indexer ?? null, title: r.title ?? null, size_bytes: r.size ?? null, seeders: r.seeders ?? null,
1308
+ age_days: r.age ?? null, protocol: r.protocol ?? null }))
1309
+ .sort((x, y) => (y.seeders ?? -1) - (x.seeders ?? -1))
1310
+ return { query, count: rows.length, releases: rows.slice(0, limit),
1311
+ note: "Discovery only. To grab, run media_release_search for the item so Sonarr/Radarr caches the release, then media_release_grab with an explicit episode mapping." }
1312
+ }
1313
+
1314
+ // The last search's compact rows, keyed by kind + guid, so a grab can check what Sonarr parsed.
1315
+ // Sonarr/Radarr forget a search's releases after about 30 minutes; expire ours a little sooner.
1316
+ const releaseCache = new Map()
1317
+ const RELEASE_CACHE_TTL_MS = 25 * 60_000
1318
+ const RELEASE_CACHE_MAX = 500
1319
+ const MAX_EPISODE_SEARCHES = 6
1320
+
1321
+ function cacheRelease(key, row, nowMs = Date.now()) {
1322
+ for (const [k, v] of releaseCache) if (nowMs - v.at > RELEASE_CACHE_TTL_MS) releaseCache.delete(k)
1323
+ releaseCache.delete(key)
1324
+ releaseCache.set(key, { ...row, at: nowMs })
1325
+ while (releaseCache.size > RELEASE_CACHE_MAX) releaseCache.delete(releaseCache.keys().next().value)
1326
+ }
1327
+
1328
+ function releaseRow(kind, r) {
1329
+ const rejections = Array.isArray(r.rejections) ? r.rejections.map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) : []
1330
+ const row = {
1331
+ guid: r.guid, indexer_id: r.indexerId ?? null, indexer: r.indexer ?? null, title: r.title ?? null, size_bytes: r.size ?? null,
1332
+ seeders: r.seeders ?? null, age_days: r.age ?? null, quality: r.quality?.quality?.name ?? null, protocol: r.protocol ?? null,
1333
+ rejected: Boolean(r.rejected), rejections, blocklisted: rejections.some((x) => /blocklist/i.test(x)),
1334
+ }
1335
+ if (kind === "series") {
1336
+ return { ...row, full_season: Boolean(r.fullSeason), parsed_season: r.seasonNumber ?? null, parsed_episodes: r.episodeNumbers ?? [],
1337
+ mapped_episodes: (r.mappedEpisodeInfo ?? []).map((e) => ({ episode_id: e.id ?? null, code: sxe(e), title: e.title ?? null })),
1338
+ mapped_series_id: r.mappedSeriesId ?? null }
1339
+ }
1340
+ return { ...row, mapped_movie_id: r.mappedMovieId ?? null }
1341
+ }
1342
+
1343
+ export async function mediaReleaseSearch(a) {
1344
+ if (!kindOk(a)) return invalidKind()
1345
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1346
+ const serviceId = Number(a.service_id)
1347
+ let raw = []
1348
+ if (a.kind === "movie") {
1349
+ raw = await radarr("/release", { query: { movieId: serviceId }, timeoutMs: SEARCH_TIMEOUT_MS })
1350
+ } else if (Array.isArray(a.episode_ids) && a.episode_ids.length) {
1351
+ // Sonarr searches one episode per call.
1352
+ if (a.episode_ids.length > MAX_EPISODE_SEARCHES) return { result: "too_many_episode_ids", max: MAX_EPISODE_SEARCHES, message: "Search the season instead, or fewer episodes at a time." }
1353
+ for (const id of a.episode_ids) raw.push(...await sonarr("/release", { query: { episodeId: id }, timeoutMs: SEARCH_TIMEOUT_MS }))
1354
+ } else if (a.season_number !== undefined && a.season_number !== null) {
1355
+ raw = await sonarr("/release", { query: { seriesId: serviceId, seasonNumber: a.season_number }, timeoutMs: SEARCH_TIMEOUT_MS })
1356
+ } else return { result: "season_number_or_episode_ids_required" }
1357
+ const seen = new Set()
1358
+ const unique = (Array.isArray(raw) ? raw : []).filter((r) => (seen.has(r.guid) ? false : seen.add(r.guid)))
1359
+ // Sonarr's override grab needs the release's own quality and languages objects back.
1360
+ const rawByGuid = new Map(unique.map((r) => [r.guid, r]))
1361
+ let rows = unique.map((r) => releaseRow(a.kind, r))
1362
+ const total = rows.length
1363
+ if (a.query) {
1364
+ const q = String(a.query).toLowerCase()
1365
+ rows = rows.filter((r) => (r.title ?? "").toLowerCase().includes(q))
1366
+ }
1367
+ rows.sort((x, y) => Number(y.seeders ?? 0) - Number(x.seeders ?? 0))
1368
+ const limit = Math.min(Math.max(Number(a.limit) || 40, 1), 100)
1369
+ for (const r of rows) {
1370
+ const source = rawByGuid.get(r.guid)
1371
+ cacheRelease(`${a.kind}:${r.guid}`, { ...r, service_id: serviceId, season_number: a.season_number ?? null,
1372
+ quality_raw: source?.quality ?? null, languages_raw: source?.languages ?? null })
1373
+ }
1374
+ return { kind: a.kind, service_id: serviceId, total_found: total, matched: rows.length, releases: rows.slice(0, limit) }
1375
+ }
1376
+
1377
+ export async function mediaReleaseGrab(a) {
1378
+ if (!kindOk(a)) return invalidKind()
1379
+ if (!a.guid || a.indexer_id === undefined || a.indexer_id === null) return { result: "guid_and_indexer_id_required" }
1380
+ const cached = releaseCache.get(`${a.kind}:${a.guid}`)
1381
+ if (!cached || Date.now() - cached.at > RELEASE_CACHE_TTL_MS) {
1382
+ return { result: "search_first", message: "Run media_release_search first; a release can only be grabbed from a recent search (within 25 minutes)." }
1383
+ }
1384
+ if (cached.indexer_id !== null && Number(a.indexer_id) !== Number(cached.indexer_id)) return { result: "indexer_mismatch", expected_indexer_id: cached.indexer_id }
1385
+ const body = { guid: a.guid, indexerId: Number(a.indexer_id) }
1386
+ const hasEpisodes = Array.isArray(a.episode_ids) && a.episode_ids.length > 0
1387
+ if (a.kind === "series") {
1388
+ if (!hasEpisodes) {
1389
+ // A pack Sonarr parsed as another season would be mapped to the wrong episodes.
1390
+ const target = a.season_number ?? cached.season_number
1391
+ if (cached.full_season && (target === undefined || target === null || Number(target) !== Number(cached.parsed_season))) {
1392
+ return { result: "season_pack_mismatch", parsed_season: cached.parsed_season, target_season: target ?? null, title: cached.title,
1393
+ message: "Sonarr parsed this season pack as a different season than the target. Pass series_id and episode_ids to say which episodes it holds." }
1394
+ }
1395
+ } else {
1396
+ if (a.series_id === undefined || a.series_id === null) return { result: "series_id_required_with_episode_ids" }
1397
+ const seriesId = Number(a.series_id)
1398
+ if (seriesId !== Number(cached.service_id)) return { result: "series_mismatch", searched_series_id: cached.service_id, message: "This release came from a search for another series." }
1399
+ const own = new Set((await seriesEpisodes(seriesId)).map((e) => e.id))
1400
+ const foreign = a.episode_ids.filter((id) => !own.has(id))
1401
+ if (foreign.length) return { result: "episode_id_not_for_series", foreign_episode_ids: foreign }
1402
+ // Sonarr v4 refuses an override without quality and languages (ArgumentNullException, HTTP 500).
1403
+ if (!cached.quality_raw) return { result: "release_quality_unknown", message: "Sonarr's search did not report this release's quality; search again." }
1404
+ Object.assign(body, { seriesId, episodeIds: a.episode_ids.map(Number), shouldOverride: true,
1405
+ quality: cached.quality_raw, languages: Array.isArray(cached.languages_raw) ? cached.languages_raw : [] })
1406
+ if (a.download_client_id !== undefined && a.download_client_id !== null) body.downloadClientId = Number(a.download_client_id)
1407
+ }
1408
+ }
1409
+ const res = await arrFor(a.kind)("/release", { method: "POST", body })
1410
+ return { result: "grabbed", kind: a.kind, title: cached.title, request: body,
1411
+ response: { approved: res?.approved ?? null, rejected: res?.rejected ?? null, rejections: res?.rejections ?? [], download_id: res?.downloadId ?? null } }
1412
+ }
1413
+
1414
+ const BLOCKLIST_PAGE_SIZE = 100
1415
+ const BLOCKLIST_MAX_PAGES = 20
1416
+
1417
+ async function itemBlocklist(kind, serviceId) {
1418
+ const idKey = idKeyOf(kind)
1419
+ const filter = kind === "series" ? { seriesIds: serviceId } : { movieIds: serviceId }
1420
+ const rows = []
1421
+ for (let page = 1; page <= BLOCKLIST_MAX_PAGES; page++) {
1422
+ const q = await arrFor(kind)("/blocklist", { query: { ...filter, page, pageSize: BLOCKLIST_PAGE_SIZE } })
1423
+ const records = q?.records ?? []
1424
+ rows.push(...records)
1425
+ if (!records.length || !(Number(q?.totalRecords) > page * BLOCKLIST_PAGE_SIZE)) return rows.filter((r) => r[idKey] === serviceId)
1426
+ }
1427
+ const own = rows.filter((r) => r[idKey] === serviceId)
1428
+ own.truncated = true
1429
+ return own
1430
+ }
1431
+
1432
+ const blocklistReport = (rows) => rows.map((r) => ({ blocklist_id: r.id, title: r.sourceTitle ?? null, date: r.date ?? null, indexer: r.indexer ?? null,
1433
+ quality: r.quality?.quality?.name ?? null, episode_ids: r.episodeIds ?? [], message: r.message ?? null }))
1434
+
1435
+ export async function mediaBlocklist(a) {
1436
+ if (!kindOk(a)) return invalidKind()
1437
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1438
+ const serviceId = Number(a.service_id)
1439
+ const rows = await itemBlocklist(a.kind, serviceId)
1440
+ if (!Array.isArray(a.remove_ids) || !a.remove_ids.length) {
1441
+ return { kind: a.kind, service_id: serviceId, count: rows.length, ...(rows.truncated ? { truncated: true } : {}), entries: blocklistReport(rows) }
1442
+ }
1443
+ const own = new Set(rows.map((r) => r.id))
1444
+ const foreign = a.remove_ids.filter((id) => !own.has(id))
1445
+ if (foreign.length) return { result: "blocklist_id_not_for_item", foreign_blocklist_ids: foreign, entries: blocklistReport(rows) }
1446
+ await arrFor(a.kind)("/blocklist/bulk", { method: "DELETE", body: { ids: a.remove_ids.map(Number) } })
1447
+ const left = await itemBlocklist(a.kind, serviceId)
1448
+ return { result: "removed", removed: a.remove_ids, count: left.length, entries: blocklistReport(left) }
1449
+ }
1450
+
1451
+ async function previewRows(seriesId, downloadId) {
1452
+ const rows = await sonarr("/manualimport", { query: { downloadId, seriesId, filterExistingFiles: false } })
1453
+ return Array.isArray(rows) ? rows : []
1454
+ }
1455
+
1456
+ const previewReport = (rows) => rows.map((r) => ({ path: r.path, name: r.name ?? null, parsed_season: r.seasonNumber ?? null,
1457
+ mapped_episodes: (r.episodes ?? []).map((e) => ({ episode_id: e.id ?? null, code: sxe(e), title: e.title ?? null })),
1458
+ quality: r.quality?.quality?.name ?? null, rejections: (r.rejections ?? []).map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) }))
1459
+
1460
+ export async function mediaManualImport(a) {
1461
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1462
+ if (!a.download_id) return { result: "download_id_required" }
1463
+ const seriesId = Number(a.service_id)
1464
+ const rows = await previewRows(seriesId, a.download_id)
1465
+ if (a.mode !== "import") return { mode: "preview", series_id: seriesId, download_id: a.download_id, files: previewReport(rows) }
1466
+ if (!Array.isArray(a.files) || !a.files.length || a.files.some((f) => !f || typeof f.path !== "string")) return { result: "files_required" }
1467
+ const paths = a.files.map((f) => f.path)
1468
+ if (new Set(paths).size !== paths.length) return { result: "duplicate_path" }
1469
+ const byPath = new Map(rows.map((r) => [r.path, r]))
1470
+ const unknown = a.files.filter((f) => !byPath.has(f.path)).map((f) => f.path)
1471
+ if (unknown.length) return { result: "path_not_in_preview", paths: unknown, files: previewReport(rows) }
1472
+ const seriesEps = await seriesEpisodes(seriesId)
1473
+ const own = new Set(seriesEps.map((e) => e.id))
1474
+ const foreign = a.files.flatMap((f) => (f.episode_ids ?? []).filter((id) => !own.has(id)))
1475
+ if (foreign.length) return { result: "episode_id_not_for_series", foreign_episode_ids: foreign }
1476
+ const empty = a.files.filter((f) => !Array.isArray(f.episode_ids) || !f.episode_ids.length).map((f) => f.path)
1477
+ if (empty.length) return { result: "episode_ids_required", paths: empty }
1478
+ const targets = a.files.flatMap((f) => f.episode_ids.map(Number))
1479
+ if (new Set(targets).size !== targets.length) return { result: "episode_id_on_two_files" }
1480
+ const files = a.files.map((f) => {
1481
+ const r = byPath.get(f.path)
1482
+ return { path: f.path, seriesId, episodeIds: f.episode_ids.map(Number), quality: r.quality, languages: r.languages, releaseGroup: r.releaseGroup ?? "",
1483
+ indexerFlags: r.indexerFlags ?? 0, releaseType: r.releaseType ?? "unknown", downloadId: a.download_id }
1484
+ })
1485
+ // Episodes that already had a file: Sonarr treats these imports as replacements, which is family-only (spec R12). The harness
1486
+ // guard stamps caller_rung; a call with no stamp (run outside the harness) is treated as family, as before.
1487
+ const replacing = seriesEps.filter((e) => e.hasFile && targets.includes(e.id)).map((e) => ({ episode_id: e.id, code: sxe(e) }))
1488
+ if (a.caller_rung === "friend" && replacing.length) return { result: "family_only", tool: "media_manual_import", argument: "files", replacing }
1489
+ const c = await sonarr("/command", { method: "POST", body: { name: "ManualImport", files, importMode: "auto" } })
1490
+ return { mode: "import", imported: a.files.map((f) => ({ path: f.path, episode_ids: f.episode_ids })), ...(replacing.length ? { replacing } : {}), command: { id: c?.id ?? null, name: c?.name ?? "ManualImport", status: c?.status ?? null } }
1491
+ }
1492
+
1493
+ // ------------------------------------------------------- tool: fill missing
1494
+ //
1495
+ // The whole "get the missing episodes" job as one deterministic pass, so a long
1496
+ // request no longer depends on the model chaining a dozen calls correctly
1497
+ // (2026-10-03: The Chef Show took an owner hint, a wrong pack, an invented
1498
+ // parameter and the step cap). Each call re-reads Sonarr, so it is safe to call
1499
+ // again: in-flight grabs are never repeated, and once nothing is missing it says
1500
+ // stop. Release names follow streaming numbering, so a release is matched to
1501
+ // episodes only on evidence: an episode title, a season plus the air year, or a
1502
+ // Sonarr parse whose own numbering agrees with the episode's TVDB or scene code.
1503
+
1504
+ const FILL_MAX_GRABS = 3
1505
+ // One call runs up to FILL_MAX_PASSES passes inside FILL_BUDGET_MS; with the action grace that stays inside the 240 s tool timeout.
1506
+ const FILL_BUDGET_MS = 180_000
1507
+ const FILL_MAX_PASSES = 3
1508
+ // A later pass starts only with at least this much of the budget left.
1509
+ const FILL_MIN_PASS_MS = 20_000
1510
+ const FILL_RECENT_GRAB_MS = 15 * 60_000
1511
+ const FILL_EVIDENCE_ROWS = 5
1512
+ // A torrent with no ETA is called stalled only after its remaining size has not moved for this long.
1513
+ const FILL_STALL_CONFIRM_MS = 30 * 60_000
1514
+
1515
+ // Years in a release name, ignoring resolutions such as 1920x1080 and 2160p.
1516
+ const yearsIn = (title) => new Set((String(title ?? "").match(/(?<![0-9x])(?:19|20)[0-9]{2}(?![0-9px])/gi) ?? []).map(Number))
1517
+ const airYear = (e) => (e.airDate ? Number(String(e.airDate).slice(0, 4)) : null)
1518
+ const hasWord = (haystack, needle) => needle.length > 0 && ` ${haystack} `.includes(` ${needle} `)
1519
+ const rejectionTexts = (r) => (Array.isArray(r.rejections) ? r.rejections.map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) : [])
1520
+ // "Doctor Who (2005)" and "The Office (US)" are named without the suffix in most releases.
1521
+ export const seriesBaseTitle = (title) => normalizeTitle(String(title ?? "").replace(/\s*\((?:19|20)[0-9]{2}\)\s*$/, "").replace(/\s*\((?:us|uk|au|nz|ca)\)\s*$/i, ""))
1522
+
1523
+ // An episode title is evidence only when it is distinctive enough not to appear by chance:
1524
+ // several words, or one long word that is not a generic release term.
1525
+ const GENERIC_TITLE_WORDS = new Set(["special", "specials", "episode", "finale", "premiere", "extended", "complete", "unknown", "untitled", "trailer", "preview", "bonus"])
1526
+ function episodeTitleIn(releaseNorm, episode) {
1527
+ const t = normalizeTitle(episode.title)
1528
+ const distinctive = t.includes(" ") ? t.length >= 6 : t.length >= 7 && !GENERIC_TITLE_WORDS.has(t) && !/^[0-9]+$/.test(t)
1529
+ return distinctive && hasWord(releaseNorm, t)
1530
+ }
1531
+
1532
+ // Season named in a release title: "Season 2", "Temporada 2", "S02" (not "S02E01").
1533
+ export function seasonInTitle(title) {
1534
+ const s = String(title ?? "")
1535
+ const word = s.match(/\b(?:season|temporada|saison|staffel)\s*0*([0-9]{1,2})\b/i)
1536
+ if (word) return Number(word[1])
1537
+ const code = s.match(/\bS0*([0-9]{1,2})(?![0-9]|\s*E[0-9])\b/i)
1538
+ return code ? Number(code[1]) : null
1539
+ }
1540
+
1541
+ // Sonarr's mapping is trusted only when the numbering in the name is the episode's own or scene code.
1542
+ function parseAgrees(release, episode) {
1543
+ const season = release.seasonNumber
1544
+ const numbers = Array.isArray(release.episodeNumbers) ? release.episodeNumbers : []
1545
+ const codes = [[episode.seasonNumber, episode.episodeNumber], [episode.sceneSeasonNumber, episode.sceneEpisodeNumber]]
1546
+ return codes.some(([s, e]) => Number.isInteger(s) && s === season && (numbers.length ? numbers.includes(e) : Boolean(release.fullSeason)))
1547
+ }
1548
+
1549
+ // Which wanted episodes one release really holds, and on what evidence; or why it is unusable.
1550
+ // A blocklisted release is still rejected, but says which wanted episodes it would hold, so a
1551
+ // release blocklisted by mistake can be offered back to the owner.
1552
+ export function matchReleaseToEpisodes(release, ctx) {
1553
+ const rejections = rejectionTexts(release)
1554
+ if (!rejections.some((x) => /blocklist/i.test(x))) return matchUnblocked(release, ctx, rejections)
1555
+ const m = matchUnblocked(release, ctx, rejections.filter((x) => !/blocklist/i.test(x)))
1556
+ if (m.reject === "other_series") return m
1557
+ return { reject: "blocklisted", ...(m.episode_ids ? { would_match: { episode_ids: m.episode_ids, basis: m.basis } } : {}) }
1558
+ }
1559
+
1560
+ function matchUnblocked(release, { seriesId, seriesTitle, seriesYear, wanted, have }, rejections) {
1561
+ const title = release.title ?? ""
1562
+ const norm = normalizeTitle(title)
1563
+ const base = seriesBaseTitle(seriesTitle)
1564
+ if (!hasWord(norm, base)) return { reject: "other_series" }
1565
+ if (release.mappedSeriesId && seriesId && release.mappedSeriesId !== seriesId) return { reject: "other_series" }
1566
+ if (rejections.some((x) => /not wanted in profile|below .*minimum|custom format/i.test(x))) return { reject: "quality_not_wanted" }
1567
+ const wantedYears = new Set(wanted.map(airYear).filter(Boolean))
1568
+ // The series' own premiere year ("Show (2019) Season 2") says nothing about which season it is,
1569
+ // unless the missing episodes aired that year too.
1570
+ const years = new Set([...yearsIn(title)].filter((y) => y !== seriesYear || wantedYears.has(y)))
1571
+ if (years.size && ![...years].some((y) => wantedYears.has(y))) return { reject: "year_mismatch", years: [...years] }
1572
+ // Episode titles are looked for in the name with the series name taken out.
1573
+ const rest = ` ${norm} `.replace(` ${base} `, " ").trim()
1574
+ const byTitle = wanted.filter((e) => episodeTitleIn(rest, e))
1575
+ if (byTitle.length) return { episode_ids: byTitle.map((e) => e.id), basis: "episode_title" }
1576
+ if (have.some((e) => episodeTitleIn(rest, e))) return { reject: "holds_episodes_we_have" }
1577
+ const wantedById = new Map(wanted.map((e) => [e.id, e]))
1578
+ const mapped = (release.mappedEpisodeInfo ?? []).map((e) => e.id).filter((id) => id !== undefined && id !== null)
1579
+ const mappedWanted = mapped.filter((id) => wantedById.has(id))
1580
+ if (mappedWanted.length) {
1581
+ if (mappedWanted.every((id) => parseAgrees(release, wantedById.get(id)))) return { episode_ids: mappedWanted, basis: "sonarr_parse" }
1582
+ return { reject: "parse_disagrees_with_numbering" }
1583
+ }
1584
+ // A season pack named with the season and the air year of the missing episodes
1585
+ // ("The Chef Show [Season 2] (2020)"), whatever Sonarr's scene mapping says it holds.
1586
+ const season = seasonInTitle(title) ?? (release.fullSeason ? release.seasonNumber ?? null : null)
1587
+ if (season !== null && years.size && !/\bE[0-9]{1,3}\b/i.test(title)) {
1588
+ const covered = wanted.filter((e) => e.seasonNumber === season && years.has(airYear(e)))
1589
+ if (covered.length) return { episode_ids: covered.map((e) => e.id), basis: "season_and_air_year" }
1590
+ }
1591
+ return { reject: mapped.length ? "holds_episodes_we_have" : "no_episode_match" }
1592
+ }
1593
+
1594
+ // Why a download is not going to finish on its own, or null while it may still be moving.
1595
+ // `confirmed` is false when the only sign is a missing ETA not yet seen to persist; such a
1596
+ // download is reported but never replaced.
1597
+ export function stallReason(row, nowMs, previous) {
1598
+ const left = row.sizeleft ?? 0
1599
+ const noEta = row.timeleft === undefined || row.timeleft === null || row.timeleft === "00:00:00"
1600
+ const unchangedFor30 = Boolean(previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS)
1601
+ if (isStalledRow(row, nowMs)) {
1602
+ if (left >= (row.size ?? 0)) return { stall: "never_started", confirmed: true }
1603
+ // Old and unfinished is not dead by age alone: a slow torrent with a real ETA is still moving.
1604
+ return noEta || unchangedFor30 ? { stall: "unfinished_for_days", confirmed: true } : null
1605
+ }
1606
+ const ageHours = row.added ? (nowMs - Date.parse(row.added)) / 3_600_000 : 0
1607
+ const moving = row.status === "downloading" || row.status === "warning"
1608
+ if (!(moving && left > 0 && noEta && ageHours >= STALL_AFTER_HOURS)) return null
1609
+ const unchanged = previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS
1610
+ return { stall: "no_peers", confirmed: Boolean(unchanged) }
1611
+ }
1612
+
1613
+ // Remaining size per download, as first seen at that size, so a later call can tell stopped from slow.
1614
+ // Kept on disk: every Butler restart starts a new MCP process, and an observation lost with it
1615
+ // would leave a dead download unconfirmable (or make a fresh one look confirmed too early).
1616
+ const PROGRESS_FORGET_MS = 14 * 24 * 3_600_000
1617
+ // Observations further apart than this are not continuous: the download may have been paused
1618
+ // and resumed in between, so the older one stops counting.
1619
+ const PROGRESS_CONTINUITY_MS = 6 * 3_600_000
1620
+ const progressPath = () => process.env.SANCTUARY_MEDIA_STATE ?? "/home/ouro/AgentBundles/sanctuary.ouro/state/media/download-progress.json"
1621
+ let progressSeen = null
1622
+ function readProgressFile() {
1623
+ const out = new Map()
1624
+ try {
1625
+ for (const [k, v] of Object.entries(JSON.parse(readFileSync(progressPath(), "utf8")))) {
1626
+ if (typeof v?.sizeleft === "number" && typeof v?.at === "number") out.set(k, { sizeleft: v.sizeleft, at: v.at, seen: typeof v.seen === "number" ? v.seen : v.at })
1627
+ }
1628
+ } catch { /* first run, or unreadable: start empty */ }
1629
+ return out
1630
+ }
1631
+ function loadProgress() {
1632
+ if (!progressSeen) progressSeen = readProgressFile()
1633
+ return progressSeen
1634
+ }
1635
+ // Merge with what another process (an overlapping restart) may have saved, keeping the
1636
+ // later sighting per download, then replace the file atomically so a crash cannot truncate it.
1637
+ function saveProgress(nowMs) {
1638
+ try {
1639
+ for (const [k, v] of readProgressFile()) {
1640
+ const mine = progressSeen.get(k)
1641
+ if (nowMs - v.seen <= PROGRESS_FORGET_MS && (!mine || v.seen > mine.seen)) progressSeen.set(k, v)
1642
+ }
1643
+ mkdirSync(dirname(progressPath()), { recursive: true, mode: 0o700 })
1644
+ const tmp = `${progressPath()}.tmp-${process.pid}`
1645
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(progressSeen)), { mode: 0o600 })
1646
+ renameSync(tmp, progressPath())
1647
+ } catch (e) {
1648
+ // Best effort: confirmation then waits for a later observation in this process.
1649
+ process.stderr.write(`media-mcp: download progress not saved: ${e.message}\n`)
1650
+ }
1651
+ }
1652
+ // Read-only look at the memory: what observeProgress would return, without recording a sighting.
1653
+ function peekProgress(key, sizeleft, nowMs) {
1654
+ const previous = loadProgress().get(key)
1655
+ return previous && nowMs - previous.seen <= PROGRESS_CONTINUITY_MS ? previous : undefined
1656
+ }
1657
+ export const progressKey = (row, kind = "series") => `${kind}:${row.downloadId ?? `row:${row.id}`}`.toUpperCase()
1658
+ function observeProgress(downloadId, sizeleft, nowMs) {
1659
+ const seen = loadProgress()
1660
+ for (const [k, v] of seen) if (nowMs - v.seen > PROGRESS_FORGET_MS) seen.delete(k)
1661
+ let previous = seen.get(downloadId)
1662
+ if (previous && nowMs - previous.seen > PROGRESS_CONTINUITY_MS) previous = undefined
1663
+ if (!previous || previous.sizeleft !== sizeleft) seen.set(downloadId, { sizeleft, at: nowMs, seen: nowMs })
1664
+ else seen.set(downloadId, { ...previous, seen: nowMs })
1665
+ saveProgress(nowMs)
1666
+ return previous
1667
+ }
1668
+
1669
+ const importDone = (row) => (row.sizeleft ?? 0) === 0 || row.status === "completed"
1670
+ const importNeeded = (row) => importDone(row) && ["importPending", "importBlocked", "importFailed"].includes(row.trackedDownloadState)
1671
+
1672
+ async function seriesGrabHistory(seriesId) {
1673
+ const list = await sonarr("/history/series", { query: { seriesId, eventType: "grabbed" } })
1674
+ return Array.isArray(list) ? list : []
1675
+ }
1676
+
1677
+ async function runningImportFor(downloadId) {
1678
+ const list = await sonarr("/command")
1679
+ return (Array.isArray(list) ? list : []).some((c) => c.name === "ManualImport" && ["queued", "started"].includes(c.status)
1680
+ && (c.body?.files ?? []).some((f) => String(f.downloadId ?? "").toUpperCase() === String(downloadId).toUpperCase()))
1681
+ }
1682
+
1683
+ // Map a finished download's files to the wanted episodes by title. Only a file whose name
1684
+ // holds exactly one wanted episode title, and the only file holding it, is imported.
1685
+ async function importByTitle(seriesId, seriesTitle, downloadId, wantedEps) {
1686
+ if (await runningImportFor(downloadId)) return { action: "import_already_running", download_id: downloadId }
1687
+ const rows = await previewRows(seriesId, downloadId)
1688
+ const base = seriesBaseTitle(seriesTitle)
1689
+ const picks = []
1690
+ const unmatched = []
1691
+ for (const r of rows) {
1692
+ const rest = ` ${normalizeTitle(`${r.name ?? ""} ${r.relativePath ?? ""}`)} `.replace(` ${base} `, " ").trim()
1693
+ const ids = wantedEps.filter((e) => episodeTitleIn(rest, e)).map((e) => e.id)
1694
+ if (ids.length === 1) picks.push({ row: r, ids })
1695
+ else unmatched.push(r.name ?? r.path)
1696
+ }
1697
+ const counts = new Map()
1698
+ for (const p of picks) counts.set(p.ids[0], (counts.get(p.ids[0]) ?? 0) + 1)
1699
+ const unique = picks.filter((p) => counts.get(p.ids[0]) === 1)
1700
+ for (const p of picks) if (!unique.includes(p)) unmatched.push(p.row.name ?? p.row.path)
1701
+ if (!unique.length) {
1702
+ return { action: "import_needs_mapping", download_id: downloadId, unmatched_files: unmatched,
1703
+ note: "No file names an episode title. Map them with media_manual_import (preview, then import by title from media_episodes)." }
1704
+ }
1705
+ const files = unique.map(({ row: r, ids }) => ({ path: r.path, seriesId, episodeIds: ids, quality: r.quality, languages: r.languages, releaseGroup: r.releaseGroup ?? "",
1706
+ indexerFlags: r.indexerFlags ?? 0, releaseType: r.releaseType ?? "unknown", downloadId }))
1707
+ const c = await sonarr("/command", { method: "POST", body: { name: "ManualImport", files, importMode: "auto" } })
1708
+ return { action: "imported_by_title", download_id: downloadId, command_id: c?.id ?? null,
1709
+ files: unique.map(({ row: r, ids }) => ({ file: r.name ?? r.path, episode_ids: ids })), ...(unmatched.length ? { unmatched_files: unmatched } : {}) }
1710
+ }
1711
+
1712
+ const pct = (row) => ((row.size ?? 0) > 0 ? Math.round((((row.size ?? 0) - (row.sizeleft ?? 0)) / row.size) * 1000) / 10 : null)
1713
+ const fillRunning = new Set()
1714
+ // When each season or episode of a series was last searched, so repeat calls reach the ones a deadline cut off.
1715
+ const lastSearched = new Map()
1716
+ const FILL_ACTION_GRACE_MS = 45_000
1717
+
1718
+ export async function mediaFillMissing(a, opts = {}) {
1719
+ const found = await resolveLibraryItem({ kind: "series", service_id: a.service_id, title: a.series })
1720
+ if (!found.item) return { result: found.result, candidates: found.candidates, message: "Name the series by its Sonarr service_id or exact title." }
1721
+ const seriesId = found.item.id
1722
+ // One pass per series at a time: a retry after a timeout must not grab beside a pass still running.
1723
+ if (fillRunning.has(seriesId)) return { result: "already_running", series_id: seriesId, message: "A media_fill_missing call for this series is still running; its result covers this request." }
1724
+ fillRunning.add(seriesId)
1725
+ try {
1726
+ const budgetMs = opts.deadlineMs ?? FILL_BUDGET_MS
1727
+ const startedAt = Date.now()
1728
+ const actions = []
1729
+ // What earlier passes grabbed counts as in flight in later ones, even before Sonarr's queue and history show it.
1730
+ const held = []
1731
+ let out
1732
+ let passes = 0
1733
+ while (passes < FILL_MAX_PASSES) {
1734
+ const leftMs = budgetMs - (Date.now() - startedAt)
1735
+ if (passes > 0 && leftMs < FILL_MIN_PASS_MS) break
1736
+ out = await fillPass(a, seriesId, found.item.title, { ...opts, deadlineMs: leftMs, held })
1737
+ passes += 1
1738
+ actions.push(...out.actions)
1739
+ held.push(...(out.held ?? []))
1740
+ // Another pass helps only when this one ran out of time or grab room; a failed step is reported, not retried.
1741
+ if (!out.incomplete || out.errors) break
1742
+ }
1743
+ const { held: _held, ...result } = out
1744
+ return { ...result, actions, passes }
1745
+ } finally {
1746
+ fillRunning.delete(seriesId)
1747
+ }
1748
+ }
1749
+
1750
+ async function fillPass(a, seriesId, seriesTitle, { nowMs = Date.now(), deadlineMs, held = [] }) {
1751
+ const startedAt = Date.now()
1752
+ const remainingMs = () => deadlineMs - (Date.now() - startedAt)
1753
+ const timeLeft = () => remainingMs() > 0
1754
+ // Grabs and imports may run a little past the search deadline, never past the harness timeout.
1755
+ const mayAct = () => remainingMs() > -FILL_ACTION_GRACE_MS
1756
+ const errors = []
1757
+ // Each step after the first reads is isolated: one failure is reported, the rest of the pass and its record survive.
1758
+ const attempt = async (step, fn) => {
1759
+ try { return await fn() } catch (e) { errors.push({ step, error: e.code ?? "failed", message: e.message }); return undefined }
1760
+ }
1761
+ const seriesYear = Number((await attempt("read series", () => sonarr(`/series/${seriesId}`)))?.year) || null
1762
+ const season = a.season_number === undefined || a.season_number === null ? null : Number(a.season_number)
1763
+ const scope = (await seriesEpisodes(seriesId, season ?? undefined)).filter((e) => (season === null ? e.seasonNumber > 0 : true))
1764
+ const aired = (e) => Boolean(e.airDateUtc ?? e.airDate) && Date.parse(e.airDateUtc ?? e.airDate) <= nowMs
1765
+ const missing = scope.filter((e) => !e.hasFile && aired(e))
1766
+ const wanted = missing.filter((e) => e.monitored)
1767
+ const have = scope.filter((e) => e.hasFile)
1768
+ const code = (e) => ({ episode_id: e.id, code: sxe(e), title: e.title ?? null, air_date: e.airDate ?? null })
1769
+ const base = { series_id: seriesId, series: seriesTitle, season_number: season, checked_at: new Date(nowMs).toISOString(),
1770
+ on_shelf: { count: have.length, of: scope.filter(aired).length },
1771
+ ...(missing.length > wanted.length ? { not_monitored_missing: missing.filter((e) => !e.monitored).map(code) } : {}) }
1772
+ if (!wanted.length) {
1773
+ return { ...base, goal_met: true, in_flight: [], not_found: [], actions: [],
1774
+ summary: `Nothing monitored is missing: ${have.length} of ${base.on_shelf.of} aired episodes are on the shelf.`,
1775
+ next_step: "Goal met: nothing is left to get." }
1776
+ }
1777
+
1778
+ const actions = []
1779
+ const byId = new Map(wanted.map((e) => [e.id, e]))
1780
+ const queue = await itemQueue("series", seriesId)
1781
+ const history = await seriesGrabHistory(seriesId)
1782
+ const grabbedFor = new Map()
1783
+ for (const h of history) {
1784
+ // A client without download ids (e.g. a blackhole) is tracked by release title instead.
1785
+ const key = h.downloadId ? String(h.downloadId).toUpperCase() : h.sourceTitle ? `TITLE:${normalizeTitle(h.sourceTitle)}` : null
1786
+ if (!key) continue
1787
+ if (!grabbedFor.has(key)) grabbedFor.set(key, { ids: new Set(), date: h.date, title: h.sourceTitle })
1788
+ grabbedFor.get(key).ids.add(h.episodeId)
1789
+ }
1790
+ // Sonarr re-parses a tracked download's name, so its queue rows can point at the
1791
+ // wrong episodes; the grab history keeps the mapping the grab was made with.
1792
+ const downloads = new Map()
1793
+ for (const r of queue) {
1794
+ const key = String(r.downloadId ?? `row:${r.id}`).toUpperCase()
1795
+ if (!downloads.has(key)) downloads.set(key, { key, row: r, ids: new Set(grabbedFor.get(key)?.ids ?? []) })
1796
+ if (!grabbedFor.has(key)) downloads.get(key).ids.add(r.episodeId)
1797
+ }
1798
+ const queuedTitles = new Set(queue.map((r) => normalizeTitle(r.title)))
1799
+ for (const [key, g] of grabbedFor) {
1800
+ const recent = nowMs - Date.parse(g.date) < FILL_RECENT_GRAB_MS
1801
+ if (recent && !downloads.has(key) && !queuedTitles.has(normalizeTitle(g.title))) downloads.set(key, { key, row: null, ids: g.ids, title: g.title })
1802
+ }
1803
+
1804
+ let cutShort = false
1805
+ const covered = new Set()
1806
+ const stalled = []
1807
+ const inFlight = []
1808
+ for (const d of downloads.values()) {
1809
+ const ids = wanted.map((e) => e.id).filter((id) => d.ids.has(id))
1810
+ if (!ids.length) continue
1811
+ const entry = { title: d.row?.title ?? d.title ?? null, download_id: d.row?.downloadId ?? d.key, episodes: ids.map((id) => sxe(byId.get(id))) }
1812
+ if (!d.row) { inFlight.push({ ...entry, state: "just_grabbed" }); ids.forEach((id) => covered.add(id)); continue }
1813
+ if (importNeeded(d.row)) {
1814
+ const done = mayAct() ? await attempt(`import ${d.row.downloadId}`, () => importByTitle(seriesId, seriesTitle, d.row.downloadId, ids.map((id) => byId.get(id)))) : undefined
1815
+ if (done) actions.push(done)
1816
+ inFlight.push({ ...entry, state: done?.action === "import_needs_mapping" ? "downloaded_needs_mapping" : done ? "importing" : mayAct() ? "downloaded_import_failed" : "downloaded_import_next_call" })
1817
+ if (!done) cutShort = true
1818
+ ids.forEach((id) => covered.add(id))
1819
+ continue
1820
+ }
1821
+ const why = stallReason(d.row, nowMs, observeProgress(progressKey(d.row), d.row.sizeleft ?? 0, nowMs))
1822
+ const info = { ...entry, percent: pct(d.row), queue_id: d.row.id, added: d.row.added ?? null }
1823
+ if (why) stalled.push({ ...info, ids, ...why })
1824
+ else { inFlight.push({ ...info, state: importDone(d.row) ? "importing" : "downloading" }); ids.forEach((id) => covered.add(id)) }
1825
+ }
1826
+
1827
+ for (const h of held) {
1828
+ const ids = wanted.map((e) => e.id).filter((id) => h.ids.includes(id) && !covered.has(id))
1829
+ if (!ids.length) continue
1830
+ inFlight.push({ title: h.title, download_id: h.download_id, episodes: ids.map((id) => sxe(byId.get(id))), state: "just_grabbed" })
1831
+ ids.forEach((id) => covered.add(id))
1832
+ }
1833
+ const passHeld = []
1834
+ // Search for everything not covered by a moving download, stalled ones included.
1835
+ const need = wanted.filter((e) => !covered.has(e.id))
1836
+ const searched = []
1837
+ const searchedSeasons = new Set()
1838
+ const searchedEpisodes = new Set()
1839
+ const candidates = new Map()
1840
+ const rejected = new Map()
1841
+ const blockedMatches = new Map()
1842
+ const inFlightTitles = new Set([...downloads.values()].map((d) => normalizeTitle(d.row?.title ?? d.title)).filter(Boolean))
1843
+ const consider = (raw) => {
1844
+ for (const r of Array.isArray(raw) ? raw : []) {
1845
+ if (!r?.guid || candidates.has(r.guid) || rejected.has(r.guid)) continue
1846
+ const m = matchReleaseToEpisodes(r, { seriesId, seriesTitle, seriesYear, wanted: need, have })
1847
+ const sameAsInFlight = inFlightTitles.has(normalizeTitle(r.title))
1848
+ if (m.would_match && !sameAsInFlight) blockedMatches.set(r.guid, { raw: r, ids: m.would_match.episode_ids, basis: m.would_match.basis })
1849
+ if (m.reject || sameAsInFlight) { rejected.set(r.guid, { title: r.title ?? null, seeders: r.seeders ?? null, reason: sameAsInFlight ? "same_release_as_stalled_download" : m.reject }); continue }
1850
+ cacheRelease(`series:${r.guid}`, { ...releaseRow("series", r), service_id: seriesId, season_number: null, quality_raw: r.quality ?? null, languages_raw: r.languages ?? null })
1851
+ candidates.set(r.guid, { raw: r, ids: m.episode_ids, basis: m.basis })
1852
+ }
1853
+ }
1854
+ const searchTimeout = () => Math.max(5_000, Math.min(SEARCH_TIMEOUT_MS, remainingMs()))
1855
+ const hasSeededCandidate = (e) => [...candidates.values()].some((c) => (c.raw.seeders ?? 0) > 0 && c.ids.includes(e.id))
1856
+ const searchedAt = (key) => lastSearched.get(`${seriesId}:${key}`) ?? 0
1857
+ const markSearched = (key) => lastSearched.set(`${seriesId}:${key}`, Date.now())
1858
+ // Least recently searched first, so a deadline never starves the same seasons on every call.
1859
+ const seasons = [...new Set(need.map((e) => e.seasonNumber))].sort((x, y) => searchedAt(`s${x}`) - searchedAt(`s${y}`) || x - y)
1860
+ for (const s of seasons) {
1861
+ if (!timeLeft()) break
1862
+ searchedSeasons.add(s)
1863
+ markSearched(`s${s}`)
1864
+ searched.push(`Sonarr season search S${code2(s)}`)
1865
+ consider(await attempt(`season search S${code2(s)}`, () => sonarr("/release", { query: { seriesId, seasonNumber: s }, timeoutMs: searchTimeout() })))
1866
+ }
1867
+ const episodeOrder = need.filter((x) => !hasSeededCandidate(x)).sort((x, y) => searchedAt(`e${x.id}`) - searchedAt(`e${y.id}`))
1868
+ for (const e of episodeOrder.slice(0, MAX_EPISODE_SEARCHES)) {
1869
+ if (!timeLeft()) break
1870
+ searchedEpisodes.add(e.id)
1871
+ markSearched(`e${e.id}`)
1872
+ searched.push(`Sonarr episode search ${sxe(e)}`)
1873
+ consider(await attempt(`episode search ${sxe(e)}`, () => sonarr("/release", { query: { episodeId: e.id }, timeoutMs: searchTimeout() })))
1874
+ }
1875
+
1876
+ // Episodes whose only matching releases are on the blocklist. With the owner's words such a
1877
+ // release joins the candidates and its blocklist entry is lifted only once it is actually being
1878
+ // grabbed (an unseeded one then waits for peers and is kept); without, it is reported.
1879
+ const covers = (id) => [...candidates.values()].some((c) => c.ids.includes(id))
1880
+ const blockedOnly = [...blockedMatches.values()].filter((b) => b.ids.some((id) => !covers(id)))
1881
+ const ownerRetry = typeof a.retry_blocklisted === "string" ? a.retry_blocklisted.trim() : ""
1882
+ const blockedLeft = new Map()
1883
+ if (blockedOnly.length) {
1884
+ const entries = (await attempt("read blocklist", () => itemBlocklist("series", seriesId))) ?? []
1885
+ for (const b of blockedOnly) {
1886
+ const ids = entries.filter((x) => normalizeTitle(x.sourceTitle) === normalizeTitle(b.raw.title)).map((x) => x.id)
1887
+ blockedLeft.set(b.raw.guid, { b, blocklist_ids: ids })
1888
+ if (ownerRetry && ids.length) {
1889
+ cacheRelease(`series:${b.raw.guid}`, { ...releaseRow("series", b.raw), service_id: seriesId, season_number: null, quality_raw: b.raw.quality ?? null, languages_raw: b.raw.languages ?? null })
1890
+ candidates.set(b.raw.guid, { ...b, blocklistIds: ids })
1891
+ }
1892
+ }
1893
+ }
1894
+ const lifted = new Set()
1895
+ const liftFor = async (c) => {
1896
+ const ids = c.blocklistIds.filter((id) => !lifted.has(id))
1897
+ if (ids.length && !(await attempt("remove from blocklist", async () => { await sonarr("/blocklist/bulk", { method: "DELETE", body: { ids } }); return true }))) return false
1898
+ ids.forEach((id) => lifted.add(id))
1899
+ if (ids.length) actions.push({ action: "removed_from_blocklist", title: c.raw.title ?? null, owner_words: ownerRetry })
1900
+ return true
1901
+ }
1902
+
1903
+ // Seeded releases first, then the ones that cover the most, then the best seeded.
1904
+ const ranked = [...candidates.values()].sort((x, y) =>
1905
+ Number((y.raw.seeders ?? 0) > 0) - Number((x.raw.seeders ?? 0) > 0) || y.ids.length - x.ids.length || (y.raw.seeders ?? 0) - (x.raw.seeders ?? 0))
1906
+ const remaining = new Set(need.map((e) => e.id))
1907
+ const stalledIds = new Set(stalled.flatMap((s) => s.ids))
1908
+ // Until a stall is confirmed on a later call, its episodes are not fetched a second time.
1909
+ const unconfirmedIds = new Set(stalled.filter((s) => !s.confirmed).flatMap((s) => s.ids))
1910
+ for (const s of stalled.filter((x) => !x.confirmed)) {
1911
+ s.alternative = ranked.some((c) => (c.raw.seeders ?? 0) > 0 && s.ids.every((id) => c.ids.includes(id)))
1912
+ }
1913
+ const deferred = new Set()
1914
+ let grabs = 0
1915
+ for (const c of ranked) {
1916
+ const seeded = (c.raw.seeders ?? 0) > 0
1917
+ // An unseeded release is no better than a stalled download: never fetch those episodes twice that way.
1918
+ const ids = c.ids.filter((id) => remaining.has(id) && !unconfirmedIds.has(id) && (seeded || !stalledIds.has(id)))
1919
+ if (!ids.length || !c.raw.quality) continue
1920
+ if (grabs >= FILL_MAX_GRABS || !mayAct()) { ids.forEach((id) => deferred.add(id)); cutShort ||= !mayAct(); continue }
1921
+ const body = { guid: c.raw.guid, indexerId: c.raw.indexerId, seriesId, episodeIds: ids, shouldOverride: true, quality: c.raw.quality, languages: Array.isArray(c.raw.languages) ? c.raw.languages : [] }
1922
+ const post = async () => (await sonarr("/release", { method: "POST", body })) ?? {}
1923
+ let res
1924
+ if (c.blocklistIds) {
1925
+ // Grab first; lift the entry after it succeeds, or before one retry if Sonarr refused it as blocklisted.
1926
+ try { res = await post() } catch { res = undefined }
1927
+ const liftedOk = await liftFor(c)
1928
+ if (!res && liftedOk) res = await attempt(`grab ${c.raw.title}`, post)
1929
+ if (!res) continue
1930
+ blockedLeft.delete(c.raw.guid)
1931
+ for (const [g, x] of blockedLeft) if (normalizeTitle(x.b.raw.title) === normalizeTitle(c.raw.title)) blockedLeft.delete(g)
1932
+ } else {
1933
+ res = await attempt(`grab ${c.raw.title}`, post)
1934
+ }
1935
+ if (!res) continue
1936
+ grabs += 1
1937
+ ids.forEach((id) => remaining.delete(id))
1938
+ actions.push({ action: "grabbed", title: c.raw.title ?? null, indexer: c.raw.indexer ?? null, seeders: c.raw.seeders ?? null, matched_by: c.basis,
1939
+ episodes: ids.map((id) => sxe(byId.get(id))), download_id: res.downloadId ?? null, ...(seeded ? {} : { may_never_finish: true }) })
1940
+ inFlight.push({ title: c.raw.title ?? null, download_id: res.downloadId ?? null, episodes: ids.map((id) => sxe(byId.get(id))), state: "just_grabbed" })
1941
+ passHeld.push({ title: c.raw.title ?? null, download_id: res.downloadId ?? null, ids })
1942
+ // Only after the replacement is grabbed, and only for a confirmed stall it fully covers with a seeded release.
1943
+ if (!seeded) continue
1944
+ for (const s of stalled.filter((x) => !x.replaced && x.confirmed && x.ids.every((id) => ids.includes(id)))) {
1945
+ const removed = await attempt(`blocklist ${s.title}`, async () => { await sonarr(`/queue/${s.queue_id}`, { method: "DELETE", query: { removeFromClient: true, blocklist: true, skipRedownload: true } }); return true })
1946
+ if (!removed) continue
1947
+ s.replaced = true
1948
+ actions.push({ action: "blocklisted_stalled", title: s.title, percent: s.percent, stall: s.stall })
1949
+ }
1950
+ }
1951
+ for (const s of stalled.filter((x) => !x.replaced)) {
1952
+ const alsoGrabbed = s.ids.every((id) => !remaining.has(id))
1953
+ inFlight.push({ title: s.title, download_id: s.download_id, episodes: s.episodes, percent: s.percent, queue_id: s.queue_id, added: s.added, state: "stalled", stall: s.stall,
1954
+ ...(s.confirmed ? {} : { stall_confirmed: false }),
1955
+ note: !s.confirmed && s.alternative ? "A seeded alternative exists; a later call replaces this download once the stall is confirmed (no progress for 30 minutes)."
1956
+ : alsoGrabbed ? "Releases for some of these episodes were grabbed; this download was kept for the rest."
1957
+ : "No other usable release was found, so this download was kept in case peers return." })
1958
+ s.ids.forEach((id) => remaining.delete(id))
1959
+ }
1960
+
1961
+ const open = need.filter((e) => remaining.has(e.id) && !deferred.has(e.id))
1962
+ const unsearched = open.filter((e) => !searchedSeasons.has(e.seasonNumber) && !searchedEpisodes.has(e.id))
1963
+ const notFound = open.filter((e) => !unsearched.includes(e)).map(code)
1964
+ const stuck = inFlight.filter((x) => x.state === "stalled")
1965
+ let evidence
1966
+ if ((notFound.length || stuck.length) && timeLeft()) {
1967
+ // What exists on the indexers under any name, so a "can't find it" is backed by a listing. Best effort.
1968
+ evidence = []
1969
+ const target = notFound.length ? need.filter((e) => notFound.some((n) => n.episode_id === e.id)) : wanted
1970
+ const ys = [...new Set(target.map((e) => e.airDate?.slice(0, 4)).filter(Boolean))].slice(0, 2)
1971
+ const scene = [...new Set(target.map((e) => e.sceneSeasonNumber).filter((n) => Number.isInteger(n)))].slice(0, 1)
1972
+ const queries = [...(ys.length ? ys : [""]).map((y) => `${seriesTitle} ${y}`.trim()), ...scene.map((n) => `${seriesTitle} S${code2(n)}`)]
1973
+ for (const q of queries) {
1974
+ if (!timeLeft()) break
1975
+ const raw = await attempt(`indexer evidence "${q}"`, () => prowlarr("/search", { query: { query: q, type: "search", limit: 100 }, timeoutMs: searchTimeout() }))
1976
+ if (!Array.isArray(raw)) continue
1977
+ // Indexers answer free text loosely ("Vegas Chef Prizefight"); keep only releases named for this series.
1978
+ const own = raw.filter((r) => hasWord(normalizeTitle(r.title), seriesBaseTitle(seriesTitle)))
1979
+ const rows = own.sort((x, y) => (y.seeders ?? -1) - (x.seeders ?? -1)).slice(0, FILL_EVIDENCE_ROWS)
1980
+ evidence.push({ query: q, results: own.length, top: rows.map((r) => ({ title: r.title ?? null, seeders: r.seeders ?? null, indexer: r.indexer ?? null })) })
1981
+ }
1982
+ }
1983
+ const blockedReport = []
1984
+ for (const { b, blocklist_ids } of blockedLeft.values()) {
1985
+ if (blockedReport.some((x) => normalizeTitle(x.title) === normalizeTitle(b.raw.title))) continue
1986
+ blockedReport.push({ title: b.raw.title ?? null, seeders: b.raw.seeders ?? null, episodes: b.ids.map((id) => sxe(byId.get(id))), blocklist_ids })
1987
+ }
1988
+ const incomplete = cutShort || deferred.size > 0 || unsearched.length > 0 || !timeLeft() || errors.length > 0
1989
+ const moving = inFlight.filter((x) => x.state !== "stalled").length
1990
+ const unseeded = actions.filter((x) => x.action === "grabbed" && x.may_never_finish)
1991
+ const summary = [
1992
+ `${have.length} of ${base.on_shelf.of} aired episodes are on the shelf; ${wanted.length} monitored ${wanted.length === 1 ? "episode is" : "episodes are"} missing.`,
1993
+ grabs ? `Grabbed ${grabs} release${grabs === 1 ? "" : "s"} now.` : "",
1994
+ unseeded.length ? `${unseeded.map((x) => x.title).join("; ")} ${unseeded.length === 1 ? "has no seeders: it waits" : "have no seeders: they wait"} for peers and may not finish.` : "",
1995
+ moving ? `${moving} download(s) in progress.` : "",
1996
+ stuck.length ? `${stuck.length} download(s) stalled with no peers and no other usable release (${stuck.map((s) => `${s.title} at ${s.percent}%`).join("; ")}).` : "",
1997
+ notFound.length ? `No usable release found for ${notFound.map((e) => e.code).join(", ")}.` : "",
1998
+ blockedReport.length ? `The only matching release${blockedReport.length === 1 ? " is" : "s are"} on the blocklist: ${blockedReport.map((x) => `${x.title} (${x.seeders ?? 0} seeders)`).join("; ")}.` : "",
1999
+ deferred.size || unsearched.length ? `${deferred.size + unsearched.length} episode(s) not handled yet in this pass.` : "",
2000
+ errors.length ? `${errors.length} step(s) failed: ${errors.map((x) => x.step).join("; ")}.` : "",
2001
+ ].filter(Boolean).join(" ")
2002
+ const nextStep = incomplete && errors.length
2003
+ ? "Some steps failed (listed in errors); calling media_fill_missing again retries them."
2004
+ : incomplete
2005
+ ? "Time ran out before every episode was handled; calling media_fill_missing again continues from the ones listed as deferred or unsearched."
2006
+ : stuck.length || notFound.length
2007
+ ? "Everything findable is requested; what is still missing is listed with why. Calling media_fill_missing later retries those."
2008
+ : unseeded.length
2009
+ ? "Everything findable is requested; the unseeded grab waits for peers and may not finish. An await_condition watch can bring this back to media_fill_missing later."
2010
+ : "Work is in progress: everything findable is requested and downloading. Calling media_fill_missing later imports and confirms it."
2011
+ const blockedHint = !blockedReport.length ? ""
2012
+ : ownerRetry ? " The owner's retry could not take the blocklisted release back (see errors and blocklisted_matches)."
2013
+ : " The only matching release is on the blocklist; media_fill_missing with retry_blocklisted set to the asker's own words takes it off and grabs it."
2014
+ return { ...base, goal_met: false, in_flight: inFlight, not_found: notFound, actions,
2015
+ ...(deferred.size ? { deferred: need.filter((e) => deferred.has(e.id)).map(code) } : {}), ...(unsearched.length ? { unsearched: unsearched.map(code) } : {}),
2016
+ searched, ...(blockedReport.length ? { blocklisted_matches: blockedReport } : {}), ...(rejected.size ? { rejected_releases: [...rejected.values()].slice(0, 12) } : {}), ...(evidence ? { indexer_evidence: evidence } : {}),
2017
+ ...(errors.length ? { errors } : {}), ...(incomplete ? { incomplete: true } : {}), summary, next_step: nextStep + blockedHint, held: passHeld }
2018
+ }
2019
+
2020
+ // ------------------------------------------------- tool: quality profiles
2021
+
2022
+ // Radarr and Sonarr keep the upgrade rules (whether a better release may replace a file, and the quality at which they
2023
+ // stop) in a quality profile. The Butler once told the owner this was "config-screen-only"; it is an ordinary API, so it
2024
+ // is a typed tool: read profiles, set cutoff and upgradeAllowed, and put a movie or series on a profile. Writes are a
2025
+ // dry run unless dry_run is false, and return before, after and applied_at like media_diagnose_and_fix.
2026
+
2027
+ const itemQualityId = (i) => i.quality?.id ?? i.id
2028
+ const itemQualityName = (i) => i.quality?.name ?? i.name
2029
+
2030
+ function profileView(p) {
2031
+ const items = p.items ?? []
2032
+ const cutoffItem = items.find((i) => itemQualityId(i) === p.cutoff)
2033
+ return { id: p.id, name: p.name, upgrade_allowed: Boolean(p.upgradeAllowed), cutoff: p.cutoff ?? null,
2034
+ cutoff_name: cutoffItem ? itemQualityName(cutoffItem) : null,
2035
+ qualities: items.map((i) => ({ id: itemQualityId(i), name: itemQualityName(i), allowed: Boolean(i.allowed), ...(i.items?.length ? { group: true } : {}) })) }
2036
+ }
2037
+
2038
+ const profileNotFound = (id) => ({ result: "no_such_profile", profile_id: id, message: "No quality profile has that id; call media_quality_profile with action read to list them." })
2039
+ const isHttp404 = (e) => /_http_404$/.test(e?.code ?? "")
2040
+
2041
+ async function getProfile(kind, id) {
2042
+ try { return await arrFor(kind)(`/qualityprofile/${id}`) } catch (e) { if (isHttp404(e)) return null; throw e }
2043
+ }
2044
+
2045
+ async function getItem(kind, serviceId) {
2046
+ try { return await arrFor(kind)(`/${kind === "series" ? "series" : "movie"}/${serviceId}`) } catch (e) { if (isHttp404(e)) return null; throw e }
2047
+ }
2048
+
2049
+ // One line per applied change: what changed, the owner's words that asked for it, who called, and when.
2050
+ const qualityAuditPath = () => process.env.SANCTUARY_MEDIA_AUDIT ?? "/home/ouro/AgentBundles/sanctuary.ouro/state/media/quality-profile-audit.ndjson"
2051
+ function auditQualityChange(entry) {
2052
+ try {
2053
+ mkdirSync(dirname(qualityAuditPath()), { recursive: true })
2054
+ appendFileSync(qualityAuditPath(), `${JSON.stringify(entry)}\n`)
2055
+ return null
2056
+ } catch (e) { return `${e.code ?? e.message}` }
2057
+ }
2058
+ const titlesUsing = async (kind, profileId) => (await arrFor(kind)(kind === "series" ? "/series" : "/movie")).filter((t) => t.qualityProfileId === profileId).length
2059
+ const OWNER_WORDS_NOTE = "owner_words is logged as the caller's claim in the audit file; the tool cannot verify the owner said it."
2060
+ const OWNER_WORDS_NOTE_AUDIT = "claimed by the caller; not verified"
2061
+ const OWNER_WORDS_REQUIRED = { result: "owner_words_required", message: "Pass owner_words with the owner's own words asking for this change (a verbatim quote), or leave dry_run true. Nothing was changed." }
2062
+
2063
+ const itemView = (item) => ({ service_id: item.id, title: item.title ?? null, quality_profile_id: item.qualityProfileId ?? null })
2064
+ const UPGRADE_NEXT_STEP = "The profile now allows the upgrade. Call media_search_now (or media_release_search) for the item so Radarr/Sonarr looks for a better release; there is no settings page left for the owner to open."
2065
+
2066
+ // Release profiles are the apps' own rules for which releases to take: a release whose title holds an ignored term is never
2067
+ // grabbed, and one missing a required term is skipped. Writes follow media_quality_profile: dry run first, owner_words to apply.
2068
+ const releaseProfileView = (p) => ({ id: p.id, name: p.name ?? null, enabled: p.enabled !== false,
2069
+ ignored: [].concat(p.ignored ?? []), required: [].concat(p.required ?? []) })
2070
+ const termList = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map((x) => String(x).trim()).filter(Boolean)
2071
+
2072
+ export async function mediaReleaseProfile(a) {
2073
+ if (!kindOk(a)) return invalidKind()
2074
+ const action = a.action ?? "read"
2075
+ const client = arrFor(a.kind)
2076
+ const profiles = await client("/releaseprofile")
2077
+ if (action === "read") return { kind: a.kind, result: "release_profiles", profiles: profiles.map(releaseProfileView) }
2078
+ if (action !== "set") return { result: "invalid_action", message: "action must be 'read' or 'set'." }
2079
+ const name = typeof a.name === "string" ? a.name.trim() : ""
2080
+ if (!name) return { result: "name_required", message: "Pass name: the release profile to create or change (matched case-insensitively)." }
2081
+ const ignored = termList(a.ignored)
2082
+ const required = termList(a.required)
2083
+ if (!ignored.length && !required.length && a.enabled === undefined) {
2084
+ return { result: "no_change_requested", message: "Pass ignored terms, required terms or enabled." }
2085
+ }
2086
+ const current = profiles.find((p) => String(p.name ?? "").toLowerCase() === name.toLowerCase())
2087
+ const before = current ? releaseProfileView(current) : null
2088
+ const next = { ...(current ?? { name, indexerId: 0, tags: [] }),
2089
+ enabled: a.enabled ?? current?.enabled ?? true,
2090
+ ignored: a.ignored !== undefined ? ignored : [].concat(current?.ignored ?? []),
2091
+ required: a.required !== undefined ? required : [].concat(current?.required ?? []) }
2092
+ const after = releaseProfileView({ ...next, id: current?.id ?? null })
2093
+ if (a.dry_run !== false) return { kind: a.kind, result: "dry_run", before, after, message: "Nothing changed. Pass dry_run false with owner_words to apply." }
2094
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
2095
+ if (!ownerWords) return OWNER_WORDS_REQUIRED
2096
+ const saved = current
2097
+ ? await client(`/releaseprofile/${current.id}`, { method: "PUT", body: next })
2098
+ : await client("/releaseprofile", { method: "POST", body: next })
2099
+ const failed = auditQualityChange({ at: new Date().toISOString(), tool: "media_release_profile", action, kind: a.kind, owner_words: ownerWords,
2100
+ owner_words_note: OWNER_WORDS_NOTE_AUDIT, caller: typeof a.caller === "string" ? a.caller : "unknown", before, after })
2101
+ return { kind: a.kind, result: current ? "updated" : "created", before, after: releaseProfileView({ ...next, ...(saved ?? {}) }),
2102
+ applied_at: new Date().toISOString(), owner_words_note: OWNER_WORDS_NOTE, ...(failed ? { audit_error: failed } : {}) }
2103
+ }
2104
+
2105
+ export async function mediaQualityProfile(a) {
2106
+ if (!kindOk(a)) return invalidKind()
2107
+ const action = a.action ?? "read"
2108
+ const dryRun = a.dry_run !== false
2109
+ const hasProfileId = a.profile_id !== undefined && a.profile_id !== null
2110
+ const hasServiceId = a.service_id !== undefined && a.service_id !== null
2111
+ const client = arrFor(a.kind)
2112
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
2113
+ if (!dryRun && action !== "read" && !ownerWords) return OWNER_WORDS_REQUIRED
2114
+ const audit = (entry) => {
2115
+ const failed = auditQualityChange({ at: new Date().toISOString(), tool: "media_quality_profile", action, kind: a.kind, owner_words: ownerWords, owner_words_note: OWNER_WORDS_NOTE_AUDIT, caller: typeof a.caller === "string" ? a.caller : "unknown", ...entry })
2116
+ return failed ? { audit_error: failed, owner_words_note: OWNER_WORDS_NOTE } : { owner_words_note: OWNER_WORDS_NOTE }
2117
+ }
2118
+
2119
+ if (action === "read") {
2120
+ let profiles
2121
+ if (hasProfileId) {
2122
+ const one = await getProfile(a.kind, Number(a.profile_id))
2123
+ if (!one) return profileNotFound(Number(a.profile_id))
2124
+ profiles = [one]
2125
+ } else {
2126
+ profiles = await client("/qualityprofile")
2127
+ }
2128
+ const out = { kind: a.kind, result: "profiles", profiles: profiles.map(profileView) }
2129
+ if (hasServiceId) {
2130
+ const item = await getItem(a.kind, Number(a.service_id))
2131
+ if (!item) return { result: "no_such_item", kind: a.kind, service_id: Number(a.service_id) }
2132
+ out.item = itemView(item)
2133
+ }
2134
+ return out
2135
+ }
2136
+
2137
+ if (action === "set_upgrade") {
2138
+ if (!hasProfileId) return { result: "profile_id_required" }
2139
+ const wantsCutoff = a.cutoff !== undefined || a.cutoff_name !== undefined
2140
+ if (!wantsCutoff && a.upgrade_allowed === undefined) {
2141
+ return { result: "no_change_requested", message: "Pass upgrade_allowed and/or cutoff (a quality id) or cutoff_name." }
2142
+ }
2143
+ const current = await getProfile(a.kind, Number(a.profile_id))
2144
+ if (!current) return profileNotFound(Number(a.profile_id))
2145
+ const next = { ...current }
2146
+ if (wantsCutoff) {
2147
+ const wanted = (current.items ?? []).find((i) => (a.cutoff !== undefined ? itemQualityId(i) === Number(a.cutoff) : String(itemQualityName(i)).toLowerCase() === String(a.cutoff_name).toLowerCase()))
2148
+ if (!wanted) return { result: "cutoff_not_in_profile", profile_id: current.id, qualities: profileView(current).qualities }
2149
+ next.cutoff = itemQualityId(wanted)
2150
+ }
2151
+ if (a.upgrade_allowed !== undefined) next.upgradeAllowed = Boolean(a.upgrade_allowed)
2152
+ const before = profileView(current)
2153
+ const after = profileView(next)
2154
+ if (before.cutoff === after.cutoff && before.upgrade_allowed === after.upgrade_allowed) return { action, dry_run: dryRun, result: "unchanged", before, after: before }
2155
+ if (dryRun) {
2156
+ const shared = await titlesUsing(a.kind, current.id)
2157
+ return { action, dry_run: true, result: "would_apply", before, after, titles_using_profile: shared,
2158
+ warning: `This profile is used by ${shared} ${a.kind === "series" ? "series" : "movie"} title(s) and the change applies to all of them. To change one title only, use action assign with that title's service_id and another profile.`,
2159
+ would_do: `Set ${a.kind === "series" ? "Sonarr" : "Radarr"} profile "${current.name}" to upgrade_allowed=${after.upgrade_allowed} with cutoff ${after.cutoff_name ?? after.cutoff}. Call again with dry_run false to apply.` }
2160
+ }
2161
+ const saved = await client(`/qualityprofile/${current.id}`, { method: "PUT", body: next })
2162
+ const appliedAfter = profileView(saved ?? next)
2163
+ return { action, dry_run: false, applied_at: new Date().toISOString(), result: "applied", before, after: appliedAfter, ...audit({ profile_id: current.id, before, after: appliedAfter }), next_step: UPGRADE_NEXT_STEP }
2164
+ }
2165
+
2166
+ if (action === "assign") {
2167
+ if (!hasServiceId) return { result: "service_id_required" }
2168
+ if (!hasProfileId) return { result: "profile_id_required" }
2169
+ const item = await getItem(a.kind, Number(a.service_id))
2170
+ if (!item) return { result: "no_such_item", kind: a.kind, service_id: Number(a.service_id) }
2171
+ const profile = await getProfile(a.kind, Number(a.profile_id))
2172
+ if (!profile) return profileNotFound(Number(a.profile_id))
2173
+ const before = itemView(item)
2174
+ const after = itemView({ ...item, qualityProfileId: profile.id })
2175
+ if (before.quality_profile_id === profile.id) return { action, dry_run: dryRun, result: "unchanged", before, after: before }
2176
+ if (dryRun) {
2177
+ return { action, dry_run: true, result: "would_apply", before, after, profile: profileView(profile),
2178
+ would_do: `Put "${item.title ?? item.id}" on the "${profile.name}" profile. Call again with dry_run false to apply.` }
2179
+ }
2180
+ const saved = await client(`/${a.kind === "series" ? "series" : "movie"}/${item.id}`, { method: "PUT", body: { ...item, qualityProfileId: profile.id } })
2181
+ const assignedAfter = itemView(saved ?? { ...item, qualityProfileId: profile.id })
2182
+ return { action, dry_run: false, applied_at: new Date().toISOString(), result: "applied", before, after: assignedAfter,
2183
+ ...audit({ service_id: item.id, profile_id: profile.id, before, after: assignedAfter }), profile: profileView(profile), next_step: UPGRADE_NEXT_STEP }
2184
+ }
2185
+
2186
+ return { result: "invalid_action", message: "action must be read, set_upgrade or assign." }
2187
+ }
2188
+
2189
+ // ------------------------------------------------------------------- schema
2190
+
2191
+ // The harness waits 30 s for a tool call unless the tool declares longer; indexer searches can take minutes.
2192
+ const TIMEOUT_META_KEY = "ouro.bot/timeoutMs"
2193
+
2194
+ const TOOL_LIST = [
2195
+ {
2196
+ name: "media_search",
2197
+ annotations: { readOnlyHint: true },
2198
+ description: "Search or browse the household media catalogue. Use `query` for a title lookup: partial and misspelled titles are matched against the library first (Sonarr, Radarr, Jellyfin) and returned as `library_matches` with their kind and service id, and when nothing in the library matches, `lookup_candidates` (TVDB/TMDB) cover titles not in the library. Whether a title is on the shelf, or exists at all, comes from a lookup made this turn, not from memory or an earlier reply; a title is missing only when both library_matches and lookup_candidates are empty. Use `genres`/`keywords`/`year_range` to browse by mood (e.g. keywords ['autumn','thanksgiving'] for cozy fall films). `on_shelf: true` restricts to what is already downloaded, `false` to what is not, omit for both. Every item says whether it is on the shelf and carries its tmdb_id so a follow-up media_request needs no second lookup.",
2199
+ inputSchema: { type: "object", properties: {
2200
+ query: { type: "string", description: "Title or free text. Omit to browse by filters." },
2201
+ kind: { type: "string", enum: ["movie", "series", "any"], description: "Default any." },
2202
+ year_range: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "[minYear, maxYear]" },
2203
+ genres: { type: "array", items: { type: "string" }, description: "TMDB genre names, e.g. ['Romance','Drama']." },
2204
+ keywords: { type: "array", items: { type: "string" }, description: "TMDB keywords, e.g. ['autumn','small town']. Best lever for mood/vibe requests." },
2205
+ on_shelf: { type: "boolean", description: "true = only what we already have; false = only what we don't; omit = both." },
2206
+ limit: { type: "number", description: "1-20, default 12." },
2207
+ sort: { type: "string", enum: ["relevance", "release_year"] },
2208
+ } },
2209
+ },
2210
+ {
2211
+ name: "media_request",
2212
+ description: "Request a film or series so it gets downloaded. Give tmdb_id when known (from media_search), otherwise title plus optional year. Idempotent: if it was already requested you get approval_state 'already_requested' and duplicate_of instead of a second request. Returns the downstream sonarr_id/radarr_id so media_request_status needs no re-resolution. Someone asking is the request: this call makes it, and the reply says what happened, so nobody needs Jellyseerr or another screen to ask for it themselves.",
2213
+ inputSchema: { type: "object", properties: {
2214
+ tmdb_id: { type: "number" },
2215
+ title: { type: "string" },
2216
+ year: { type: "number" },
2217
+ kind: { type: "string", enum: ["movie", "series"] },
2218
+ season_number: { type: "number", description: "Series only. Omit to request all seasons." },
2219
+ } },
2220
+ },
2221
+ {
2222
+ name: "media_request_status",
2223
+ annotations: { readOnlyHint: true },
2224
+ description: "One call, every stage: request, indexer search, download, file on disk, plus acquisition-chain health and a deterministic `diagnosis` block naming what is stuck, why, and the fix. Use this for any 'is it here yet?' or 'why hasn't X downloaded?' question. A queue row is not proof of progress: a release sitting at zero bytes comes back as stalled, not as downloading. diagnosis.summary names the cause from what each stage reports.",
2225
+ inputSchema: { type: "object", properties: {
2226
+ request_id: { type: "string", description: "e.g. jellyseerr:42" },
2227
+ tmdb_id: { type: "number" },
2228
+ title: { type: "string" },
2229
+ } },
2230
+ },
2231
+ {
2232
+ name: "media_diagnose_and_fix",
2233
+ description: "Act on a stuck request. Omit `action` to apply the fix that media_request_status already identified, including 'blocklist_and_research' for a release that has stalled at zero bytes. Returns 'rejected_fix_unsafe' without acting when the acquisition chain itself is down, because re-searching does nothing then. dry_run shows the fix without acting.",
2234
+ inputSchema: { type: "object", properties: {
2235
+ request_id: { type: "string" }, tmdb_id: { type: "number" }, title: { type: "string" },
2236
+ action: { type: "string", enum: ["rescan", "enable_monitoring", "force_import_scan", "blocklist_and_research", "report_only"] },
2237
+ dry_run: { type: "boolean" },
2238
+ } },
2239
+ },
2240
+ {
2241
+ name: "media_chain_health",
2242
+ annotations: { readOnlyHint: true },
2243
+ description: "Health of the whole acquisition chain: Prowlarr indexers, their failure state, and whether Prowlarr is syncing to Sonarr/Radarr. Call this when several things are stuck at once, or before telling anyone a specific title is the problem — a dead chain blocks everything and is the single most likely cause. An empty queue is not evidence that all is well; check the chain before blaming a title or the indexer provider's credit.",
2244
+ inputSchema: { type: "object", properties: {} },
2245
+ },
2246
+ {
2247
+ name: "media_play_or_resolve",
2248
+ description: "Resolve something on the shelf to a playable link plus what is actually on disk (episode counts, size, path). If it is not playable you get the same diagnosis block explaining why.",
2249
+ inputSchema: { type: "object", properties: {
2250
+ request_id: { type: "string" }, tmdb_id: { type: "number" }, title: { type: "string" },
2251
+ } },
2252
+ },
2253
+ {
2254
+ name: "media_queue",
2255
+ description: "View of the Sonarr/Radarr download queue, torrent and usenet alike: for each row the title, status, trackedDownloadState, percent, timeleft, size left, download client and whether it is stalled. Use this to see whether a series or movie download is progressing (this is the tool for torrent downloads; sanctuary_get_download_queue only sees the usenet/SABnzbd queue). Give service_id, tmdb_id or title for one item, or omit them for the whole queue of that kind. It grabs nothing. Its one write is the household's standing rule: a download that is a program rather than a video (.exe, .scr, .bat, .msi, .cmd, .com, .vbs, .ps1, .lnk, .zip, or flagged by Sonarr/Radarr as an executable) is a fake release, so it is removed, blocklisted and listed in cleared_fakes; that needs no one's decision. Seeders and peers are not reported by Sonarr/Radarr; use media_indexer_search for a release's seeders. While a watched download is in the queue and media_fill_missing has not reported goal_met, answer each ticking check with resolve_await verdict 'no'.",
2256
+ inputSchema: { type: "object", properties: {
2257
+ kind: { type: "string", enum: ["series", "movie"] },
2258
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2259
+ tmdb_id: { type: "number" },
2260
+ title: { type: "string", description: "Exact or near-exact library title." },
2261
+ }, required: ["kind"] },
2262
+ },
2263
+ {
2264
+ name: "media_search_now",
2265
+ description: "Asks Sonarr or Radarr to search again for a series or movie already in the library (by service_id, tmdb_id or title) and returns what it started and the item's queue.",
2266
+ inputSchema: { type: "object", properties: {
2267
+ kind: { type: "string", enum: ["series", "movie"] },
2268
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2269
+ title: { type: "string" },
2270
+ tmdb_id: { type: "number" },
2271
+ }, required: ["kind"] },
2272
+ },
2273
+ {
2274
+ name: "media_blocklist_stalled",
2275
+ description: "Clear stuck downloads for a series or movie already in Sonarr/Radarr: remove stalled queue rows from the download client, blocklist those releases so they are not grabbed again, then search again (research, default true). Use this to clear stuck or stalled downloads; no Jellyseerr request id is needed. Without queue_ids it targets the item's stalled rows; with queue_ids only those, and each must belong to the item. A download still moving, or stalled but not yet confirmed dead, is kept (result kept_downloads) because removing it deletes its progress: a partial download counts as dead only after two calls at least 30 minutes apart see no ETA and no progress. Pass owner_words, with queue_ids, only when the owner's own message asked to remove, clear or cancel those downloads. For missing episodes use media_fill_missing instead. Rows of one season pack are removed once; a delete that fails is reported in `failed` and the re-search still runs.",
2276
+ inputSchema: { type: "object", properties: {
2277
+ kind: { type: "string", enum: ["series", "movie"] },
2278
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id (media_search_now returns it)." },
2279
+ queue_ids: { type: "array", items: { type: "number" } },
2280
+ research: { type: "boolean", description: "Search again afterwards. Default true." },
2281
+ owner_words: { type: "string", description: "The owner's exact words asking to remove, clear or cancel these downloads; requires queue_ids. Not for 'get them'." },
2282
+ dry_run: { type: "boolean", description: "true returns the plan (would_remove) and changes nothing. Default false." },
2283
+ }, required: ["kind", "service_id"] },
2284
+ },
2285
+ {
2286
+ name: "media_fill_missing",
2287
+ _meta: { [TIMEOUT_META_KEY]: 240_000 },
2288
+ description: "Gets a series' missing episodes in one call: it re-reads Sonarr, searches the indexers, grabs the best seeded release for each monitored aired episode (matched by episode title and air year as well as Sonarr's numbering), imports finished downloads, and replaces a stalled download it keeps by itself once a seeded alternative exists, over up to 3 passes in 3 minutes. It leaves what is already in flight alone. Returns on_shelf, in_flight, not_found, actions, indexer_evidence, summary and next_step; goal_met is true when nothing is left to get, and blocklisted_matches lists episodes whose only release is blocklisted.",
2289
+ inputSchema: { type: "object", properties: {
2290
+ series: { type: "string", description: "Series title as the owner said it." },
2291
+ service_id: { type: "number", description: "Sonarr series id, when known." },
2292
+ season_number: { type: "number", description: "Limit to one season. Omit for the whole series (specials excluded)." },
2293
+ retry_blocklisted: { type: "string", description: "The asker's words asking for the episodes whose only matching release is on the blocklist (reported in blocklisted_matches). Takes those releases off the blocklist and grabs them." },
2294
+ } },
2295
+ },
2296
+ {
2297
+ name: "media_episodes",
2298
+ annotations: { readOnlyHint: true },
2299
+ description: "List a Sonarr series' episodes (optionally one season): episode_id, SxxEyy code, scene_code (the numbering release names use, when Sonarr has a mapping), title, air date, has_file. Use it to see what the TVDB numbering calls each episode before searching for releases by hand. Episode state comes from this tool this turn, not from an earlier reply.",
2300
+ inputSchema: { type: "object", properties: {
2301
+ service_id: { type: "number", description: "Sonarr series id." },
2302
+ season_number: { type: "number" },
2303
+ }, required: ["service_id"] },
2304
+ },
2305
+ {
2306
+ name: "media_monitor",
2307
+ annotations: { readOnlyHint: false },
2308
+ description: "Turn Sonarr monitoring on or off for whole seasons (season_numbers) or single episodes (episode_ids, from media_episodes). Monitored is what Sonarr searches for on its own. search: true also searches what was just monitored.",
2309
+ inputSchema: { type: "object", properties: {
2310
+ service_id: { type: "number", description: "Sonarr series id." },
2311
+ season_numbers: { type: "array", items: { type: "number" } },
2312
+ episode_ids: { type: "array", items: { type: "number" } },
2313
+ monitored: { type: "boolean" },
2314
+ search: { type: "boolean" },
2315
+ }, required: ["service_id", "monitored"] },
2316
+ },
2317
+ {
2318
+ name: "media_watch_history",
2319
+ annotations: { readOnlyHint: true },
2320
+ description: "What a Jellyfin user has watched or is partway through: episodes and movies with completion percent, play count and last played, newest first. Filter by title (a series or movie) and state (all, played, in_progress).",
2321
+ inputSchema: { type: "object", properties: {
2322
+ user: { type: "string", description: "Jellyfin user name or id." },
2323
+ title: { type: "string" },
2324
+ state: { type: "string", enum: WATCH_STATES },
2325
+ limit: { type: "number" },
2326
+ }, required: [] },
2327
+ },
2328
+ {
2329
+ name: "media_indexer_search",
2330
+ annotations: { readOnlyHint: true },
2331
+ _meta: { [TIMEOUT_META_KEY]: 200_000 },
2332
+ description: "Free-text search across every indexer (Prowlarr), sorted by seeders. Discovery only, it grabs nothing. Use it when Sonarr/Radarr's own search finds nothing: try the scene code from media_episodes, 'Season N', the year, or an episode title, to learn whether any release exists and how it is named. Zero seeders means it cannot download right now.",
2333
+ inputSchema: { type: "object", properties: {
2334
+ query: { type: "string" },
2335
+ limit: { type: "number", description: "1-50, default 25." },
2336
+ }, required: ["query"] },
2337
+ },
2338
+ {
2339
+ name: "media_release_search",
2340
+ annotations: { readOnlyHint: true },
2341
+ _meta: { [TIMEOUT_META_KEY]: 240_000 },
2342
+ description: "Interactive release search for a series or movie already in the library: what the indexers offer and how Sonarr/Radarr parsed each release (full_season, parsed_season, parsed_episodes, mapped_episodes), whether it is rejected and why, and whether it is blocklisted. Series: give season_number or episode_ids. Can take a minute or more. `query` filters returned titles. Use it when the automatic search found nothing: compare each release title with its parse, the scene_code from media_episodes and the blocklist, then grab with media_release_grab.",
2343
+ inputSchema: { type: "object", properties: {
2344
+ kind: { type: "string", enum: ["series", "movie"] },
2345
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2346
+ season_number: { type: "number" },
2347
+ episode_ids: { type: "array", items: { type: "number" } },
2348
+ query: { type: "string", description: "Case-insensitive text the release title must contain." },
2349
+ limit: { type: "number", description: "1-100, default 40." },
2350
+ }, required: ["kind", "service_id"] },
2351
+ },
2352
+ {
2353
+ name: "media_release_grab",
2354
+ description: "Grab one release from the last media_release_search by guid and indexer_id. For a release Sonarr mis-parsed (streaming numbering vs TVDB), pass series_id plus episode_ids to override the mapping; episode_ids must belong to the series. Without episode_ids, a season pack that Sonarr parsed as a different season than season_number returns 'season_pack_mismatch'. A release with zero seeders may still be grabbed; say plainly that it will not download until it has seeders. Returns the exact request sent and Sonarr's answer.",
2355
+ inputSchema: { type: "object", properties: {
2356
+ kind: { type: "string", enum: ["series", "movie"] },
2357
+ guid: { type: "string" },
2358
+ indexer_id: { type: "number" },
2359
+ series_id: { type: "number", description: "Required with episode_ids." },
2360
+ episode_ids: { type: "array", items: { type: "number" }, description: "Episodes this release really holds." },
2361
+ season_number: { type: "number", description: "Target season, checked against a season pack's parsed season when episode_ids is omitted." },
2362
+ download_client_id: { type: "number" },
2363
+ }, required: ["kind", "guid", "indexer_id"] },
2364
+ },
2365
+ {
2366
+ name: "media_blocklist",
2367
+ description: "List the blocklist for a series or movie in Sonarr/Radarr, and optionally remove entries (remove_ids) so the release can be grabbed again. Each id must belong to the item; a foreign id removes nothing.",
2368
+ inputSchema: { type: "object", properties: {
2369
+ kind: { type: "string", enum: ["series", "movie"] },
2370
+ service_id: { type: "number" },
2371
+ remove_ids: { type: "array", items: { type: "number" } },
2372
+ }, required: ["kind", "service_id"] },
2373
+ },
2374
+ {
2375
+ name: "media_quality_profile",
2376
+ description: "Read and change the Radarr/Sonarr quality profiles that decide whether a better release may replace a file ('Quality Profile does not allow upgrades'). It works through the apps' API, with no settings screen for the owner to click through. action read (default) lists the profiles for the kind with their cutoff, upgrade flag and ordered qualities, or one profile with profile_id; add service_id to also see which profile a movie or series is on. action set_upgrade changes upgrade_allowed and/or the cutoff (a quality id from the profile, or cutoff_name) of profile_id. action assign puts the movie or series service_id on profile_id. Both writes are a dry run that shows before and after and changes nothing until dry_run is false; a change to a shared profile affects every title on it, so prefer assign to move one title when the owner asked about one title. When the owner's words ask for the change, apply it, then report the before and after in one line. Applying takes owner_words, the owner's words asking for the change. After an applied change, call media_search_now so the upgrade is searched for.",
2377
+ inputSchema: { type: "object", properties: {
2378
+ kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
2379
+ action: { type: "string", enum: ["read", "set_upgrade", "assign"], description: "Default read." },
2380
+ profile_id: { type: "number", description: "Quality profile id (from action read)." },
2381
+ service_id: { type: "number", description: "Radarr movie id or Sonarr series id (media_search returns it)." },
2382
+ upgrade_allowed: { type: "boolean", description: "set_upgrade: whether a better release may replace the file." },
2383
+ cutoff: { type: "number", description: "set_upgrade: quality id from the profile at which upgrades stop." },
2384
+ cutoff_name: { type: "string", description: "set_upgrade: the same, by quality name (for example Bluray-1080p)." },
2385
+ dry_run: { type: "boolean", description: "Writes only. Default true: report before and after without changing anything. Pass false to apply." },
2386
+ owner_words: { type: "string", description: "Required to apply (dry_run false): the owner's exact words asking for this change. Quoted as the owner wrote them." },
2387
+ caller: { type: "string", description: "Filled in by the runtime for the audit line; leave it out." },
2388
+ }, required: ["kind"] },
2389
+ },
2390
+ {
2391
+ name: "media_release_profile",
2392
+ description: "Read and set the Radarr/Sonarr release profiles: the apps' own standing rules for which releases to take. A release whose title holds an ignored term isn't grabbed; one missing a required term is skipped. Use it for household rules such as turning down fake releases that are programs (ignored: a regex like /\\.(exe|scr|bat|msi)$/i, end-anchored so titles like Scream or Batman stay fine). action read (default) lists them. action set creates or changes the profile called name; ignored and required replace that list when given. A set is a dry run showing before and after until dry_run is false; applying takes owner_words, the owner's words asking for it. The fake-release rule in media_queue runs regardless; this keeps such releases from being grabbed at all.",
2393
+ inputSchema: { type: "object", properties: {
2394
+ kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
2395
+ action: { type: "string", enum: ["read", "set"], description: "Default read." },
2396
+ name: { type: "string", description: "set: the release profile's name; an existing one is changed, otherwise it is created." },
2397
+ ignored: { type: "array", items: { type: "string" }, description: "set: terms or /regex/ that a release title must not contain." },
2398
+ required: { type: "array", items: { type: "string" }, description: "set: terms or /regex/ that a release title must contain." },
2399
+ enabled: { type: "boolean", description: "set: whether the profile is in force. Default: unchanged, or true for a new one." },
2400
+ dry_run: { type: "boolean", description: "Default true: report before and after without changing anything. Pass false to apply." },
2401
+ owner_words: { type: "string", description: "Required to apply: the owner's exact words asking for this change." },
2402
+ caller: { type: "string", description: "Filled in by the runtime for the audit line; leave it out." },
2403
+ }, required: ["kind"] },
2404
+ },
2405
+ {
2406
+ name: "media_manual_import",
2407
+ description: "Map downloaded files to episodes by hand when their names carry the wrong numbering (Sonarr only). mode 'preview' lists the files of a download with the parsed and mapped episodes and rejections. mode 'import' takes files [{path, episode_ids}]: paths must come from that download's preview and episode_ids must belong to the series; quality and languages come from the preview. Match files to episodes by title using media_episodes.",
2408
+ inputSchema: { type: "object", properties: {
2409
+ mode: { type: "string", enum: ["preview", "import"], description: "Default preview." },
2410
+ service_id: { type: "number", description: "Sonarr series id." },
2411
+ download_id: { type: "string", description: "Download client id of the completed download (queue row downloadId)." },
2412
+ files: { type: "array", items: { type: "object", properties: { path: { type: "string" }, episode_ids: { type: "array", items: { type: "number" } } }, required: ["path", "episode_ids"] } },
2413
+ caller_rung: { type: "string", enum: ["family", "friend"], description: "Filled in by the runtime from who is asking; leave it out. An import that replaces a file is for family." },
2414
+ }, required: ["service_id", "download_id"] },
2415
+ },
2416
+ ]
2417
+
2418
+ // Every schema is closed: an argument the tool does not define (an invented dry_run,
2419
+ // a misspelled id) is refused with its name, never silently ignored.
2420
+ function closeSchema(schema) {
2421
+ if (!schema || typeof schema !== "object" || schema.type !== "object") return schema
2422
+ const properties = Object.fromEntries(Object.entries(schema.properties ?? {}).map(([k, v]) => [k, v?.type === "array" && v.items ? { ...v, items: closeSchema(v.items) } : closeSchema(v)]))
2423
+ return { ...schema, properties, additionalProperties: false }
2424
+ }
2425
+
2426
+ export const TOOLS = TOOL_LIST.map((t) => ({ ...t, inputSchema: closeSchema(t.inputSchema) }))
2427
+
2428
+ // The same check inside the server, for any caller that does not validate against the schema.
2429
+ export function unknownArguments(toolName, args) {
2430
+ const tool = TOOLS.find((t) => t.name === toolName)
2431
+ const allowed = Object.keys(tool?.inputSchema?.properties ?? {})
2432
+ const unknown = Object.keys(args ?? {}).filter((k) => !allowed.includes(k))
2433
+ return unknown.length ? { error: "unknown_parameter", unknown, allowed,
2434
+ message: `${toolName} does not take ${unknown.map((k) => `'${k}'`).join(", ")}. It accepts only: ${allowed.join(", ") || "no parameters"}. Call it again without the unknown parameter.` } : null
2435
+ }
2436
+
2437
+ const HANDLERS = {
2438
+ media_search: mediaSearch,
2439
+ media_request: mediaRequest,
2440
+ media_request_status: mediaRequestStatus,
2441
+ media_diagnose_and_fix: mediaDiagnoseAndFix,
2442
+ media_chain_health: mediaChainHealth,
2443
+ media_play_or_resolve: mediaPlayOrResolve,
2444
+ media_search_now: mediaSearchNow,
2445
+ media_queue: mediaQueue,
2446
+ media_blocklist_stalled: mediaBlocklistStalled,
2447
+ media_episodes: mediaEpisodes,
2448
+ media_monitor: mediaMonitor,
2449
+ media_watch_history: mediaWatchHistory,
2450
+ media_fill_missing: mediaFillMissing,
2451
+ media_indexer_search: mediaIndexerSearch,
2452
+ media_release_search: mediaReleaseSearch,
2453
+ media_release_grab: mediaReleaseGrab,
2454
+ media_blocklist: mediaBlocklist,
2455
+ media_manual_import: mediaManualImport,
2456
+ media_quality_profile: mediaQualityProfile,
2457
+ media_release_profile: mediaReleaseProfile,
2458
+ }
2459
+
2460
+ // ------------------------------------------------------------ jsonrpc stdio
2461
+
2462
+ function send(msg) { process.stdout.write(JSON.stringify(msg) + "\n") }
2463
+
2464
+ async function handle(msg) {
2465
+ const { id, method, params } = msg
2466
+ if (method === "initialize") {
2467
+ return send({ jsonrpc: "2.0", id, result: {
2468
+ protocolVersion: "2024-11-05",
2469
+ capabilities: { tools: {} },
2470
+ serverInfo: { name: "sanctuary-media", version: "1.0.0" },
2471
+ } })
2472
+ }
2473
+ if (method === "initialized" || method === "notifications/initialized") return
2474
+ if (method === "tools/list") return send({ jsonrpc: "2.0", id, result: { tools: TOOLS } })
2475
+ if (method === "tools/call") {
2476
+ const fn = HANDLERS[params?.name]
2477
+ if (!fn) return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: `Unknown tool: ${params?.name}` }] } })
2478
+ if (credError) {
2479
+ const payload = { error: "credentials_unavailable", message: credError, human_action_required: true,
2480
+ human_action_reason: credError }
2481
+ return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(payload, null, 1) }] } })
2482
+ }
2483
+ const unknown = unknownArguments(params.name, params.arguments)
2484
+ if (unknown) return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(unknown, null, 1) }] } })
2485
+ try {
2486
+ const out = await fn(params.arguments ?? {})
2487
+ return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out, null, 1) }] } })
2488
+ } catch (e) {
2489
+ const payload = { error: e.code ?? "tool_failed", message: e.message,
2490
+ human_action_required: true,
2491
+ human_action_reason: `The media tool could not complete: ${e.message}. Report this failure rather than guessing the answer.` }
2492
+ return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(payload, null, 1) }] } })
2493
+ }
2494
+ }
2495
+ if (id !== undefined) send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } })
2496
+ }
2497
+
2498
+ let buf = ""
2499
+ let inFlight = 0
2500
+ let stdinClosed = false
2501
+
2502
+ // Exit only when stdin is closed AND nothing is still running. Exiting on 'end'
2503
+ // alone drops in-flight tool calls, which silently truncates a slow answer.
2504
+ function exitWhenIdle() {
2505
+ if (stdinClosed && inFlight === 0) process.exit(0)
2506
+ }
2507
+
2508
+ // Only run the stdio server when invoked directly (node media-mcp.mjs, exactly
2509
+ // how agent.json launches it). Guarding this lets the test suite import the
2510
+ // module for computeDownloadState/diagnose without attaching to stdin or exiting
2511
+ // the test process. The launch is a plain node <abs-path>, so argv[1] is the
2512
+ // file's own path and this comparison holds.
2513
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
2514
+ process.stdin.setEncoding("utf8")
2515
+ process.stdin.on("data", (chunk) => {
2516
+ buf += chunk
2517
+ let nl
2518
+ while ((nl = buf.indexOf("\n")) >= 0) {
2519
+ const line = buf.slice(0, nl).trim()
2520
+ buf = buf.slice(nl + 1)
2521
+ if (!line) continue
2522
+ let msg
2523
+ try { msg = JSON.parse(line) } catch { continue }
2524
+ inFlight += 1
2525
+ handle(msg)
2526
+ .catch((e) => {
2527
+ if (msg.id !== undefined) send({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: e.message } })
2528
+ })
2529
+ .finally(() => { inFlight -= 1; exitWhenIdle() })
2530
+ }
2531
+ })
2532
+ process.stdin.on("end", () => { stdinClosed = true; exitWhenIdle() })
2533
+ }