@ouro.bot/cli 0.1.0-alpha.123 → 0.1.0-alpha.1231

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 (995) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +197 -30
  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 +7352 -23
  16. package/deploy/unraid/Dockerfile +85 -0
  17. package/deploy/unraid/INSTALL.md +64 -0
  18. package/deploy/unraid/README.txt +3032 -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 +727 -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-sync-ssh +98 -0
  33. package/deploy/unraid/ouro-sync.sudoers +3 -0
  34. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  35. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  36. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  37. package/deploy/unraid/sanctuary-authority-installation.json +36 -0
  38. package/deploy/unraid/sanctuary-authority-service.sh +30 -0
  39. package/deploy/unraid/sanctuary-butler-upgrade.mjs +1523 -0
  40. package/deploy/unraid/sanctuary-deployment-target.mjs +710 -0
  41. package/deploy/unraid/sanctuary-replay-gate.mjs +2562 -0
  42. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  43. package/deploy/unraid/sanctuary-sync-cutover.sh +1039 -0
  44. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2088 -0
  45. package/deploy/unraid/sanctuary-unit16-run.sh +570 -0
  46. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  47. package/deploy/unraid/sanctuary.ouro/agent.json +73 -0
  48. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  49. package/deploy/unraid/sanctuary.ouro/awaiting/house-care-sweep.md +17 -0
  50. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  51. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  52. package/deploy/unraid/sanctuary.ouro/mcp/media-mcp.mjs +2489 -0
  53. package/deploy/unraid/sanctuary.ouro/product/PRODUCT.md +13 -0
  54. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  55. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  56. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +7 -0
  57. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +7 -0
  58. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +15 -0
  59. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +3 -0
  60. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  61. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +253 -0
  62. package/deploy/unraid/sanctuary.xml +30 -0
  63. package/dist/a2a/card.js +57 -0
  64. package/dist/a2a/client.js +290 -0
  65. package/dist/a2a/config.js +50 -0
  66. package/dist/a2a/delegated-command-grants.js +93 -0
  67. package/dist/a2a/delegated-command.js +197 -0
  68. package/dist/a2a/delegation-stores.js +56 -0
  69. package/dist/a2a/did-resolution.js +205 -0
  70. package/dist/a2a/escalation-grants.js +84 -0
  71. package/dist/a2a/escalation-wiring.js +60 -0
  72. package/dist/a2a/identity.js +258 -0
  73. package/dist/a2a/inbound-share.js +131 -0
  74. package/dist/a2a/mission-result-wire.js +265 -0
  75. package/dist/a2a/onboarding.js +133 -0
  76. package/dist/a2a/operator-trust.js +399 -0
  77. package/dist/a2a/outbox-client.js +59 -0
  78. package/dist/a2a/outbox-store.js +245 -0
  79. package/dist/a2a/outbox-wire.js +106 -0
  80. package/dist/a2a/pin-store.js +167 -0
  81. package/dist/a2a/refusals.js +53 -0
  82. package/dist/a2a/relay-client.js +106 -0
  83. package/dist/a2a/relay-config-vault.js +64 -0
  84. package/dist/a2a/relay-contacts.js +120 -0
  85. package/dist/a2a/relay-inbox.js +360 -0
  86. package/dist/a2a/relay-retirements.js +89 -0
  87. package/dist/a2a/replay-grant-holders.js +33 -0
  88. package/dist/a2a/replay-harness.js +188 -0
  89. package/dist/a2a/resolution-proof.js +53 -0
  90. package/dist/a2a/sealed-chat.js +114 -0
  91. package/dist/a2a/seen-ledger.js +214 -0
  92. package/dist/a2a/server.js +804 -0
  93. package/dist/a2a/task-store.js +69 -0
  94. package/dist/a2a/transport.js +100 -0
  95. package/dist/a2a/trust-commands.js +203 -0
  96. package/dist/a2a/trusted-files.js +185 -0
  97. package/dist/a2a/types.js +3 -0
  98. package/dist/arc/attention-types.js +8 -0
  99. package/dist/arc/cares.js +360 -0
  100. package/dist/arc/episodes.js +118 -0
  101. package/dist/arc/evolution.js +490 -0
  102. package/dist/arc/flight-recorder.js +1030 -0
  103. package/dist/arc/intentions.js +134 -0
  104. package/dist/arc/json-store.js +117 -0
  105. package/dist/arc/obligations.js +386 -0
  106. package/dist/arc/packets.js +336 -0
  107. package/dist/arc/presence.js +185 -0
  108. package/dist/arc/task-lifecycle.js +57 -0
  109. package/dist/commerce/store.js +755 -0
  110. package/dist/commerce/types.js +3 -0
  111. package/dist/gateway/keys.js +117 -0
  112. package/dist/gateway/server.js +429 -0
  113. package/dist/heart/active-work.js +431 -44
  114. package/dist/heart/agent-entry.js +253 -3
  115. package/dist/heart/approval-files.js +94 -0
  116. package/dist/heart/approval-store.js +957 -0
  117. package/dist/heart/atomic-file.js +115 -0
  118. package/dist/heart/attachments/downloaded-store.js +89 -0
  119. package/dist/heart/attachments/image-normalize.js +201 -0
  120. package/dist/heart/attachments/materialize.js +97 -0
  121. package/dist/heart/attachments/originals.js +102 -0
  122. package/dist/heart/attachments/render.js +29 -0
  123. package/dist/heart/attachments/sources/bluebubbles.js +155 -0
  124. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  125. package/dist/heart/attachments/sources/downloaded.js +76 -0
  126. package/dist/heart/attachments/sources/index.js +19 -0
  127. package/dist/heart/attachments/store.js +132 -0
  128. package/dist/heart/attachments/transcribe-audio.js +172 -0
  129. package/dist/heart/attachments/types.js +93 -0
  130. package/dist/heart/attachments/understand.js +195 -0
  131. package/dist/heart/auth/auth-flow.js +589 -0
  132. package/dist/heart/auth/github-device-login.js +104 -0
  133. package/dist/heart/autonomy-budget.js +478 -0
  134. package/dist/heart/awaiting/a2a-await-delivery.js +109 -0
  135. package/dist/heart/awaiting/await-alert.js +152 -0
  136. package/dist/heart/awaiting/await-expiry.js +143 -0
  137. package/dist/heart/awaiting/await-loader.js +91 -0
  138. package/dist/heart/awaiting/await-parser.js +152 -0
  139. package/dist/heart/awaiting/await-runtime-state.js +130 -0
  140. package/dist/heart/awaiting/await-scheduler.js +403 -0
  141. package/dist/heart/background-operations.js +281 -0
  142. package/dist/heart/bluebubbles-host-account.js +78 -0
  143. package/dist/heart/bridges/manager.js +137 -17
  144. package/dist/heart/bridges/store.js +14 -2
  145. package/dist/heart/bundle-state.js +168 -0
  146. package/dist/heart/chat-interaction.js +38 -0
  147. package/dist/heart/commitments.js +44 -14
  148. package/dist/heart/config-registry.js +331 -0
  149. package/dist/heart/config.js +194 -140
  150. package/dist/heart/context-loss-gauntlet.js +387 -0
  151. package/dist/heart/context-loss-sentinel.js +1200 -0
  152. package/dist/heart/core.js +2554 -611
  153. package/dist/heart/cross-chat-delivery.js +29 -22
  154. package/dist/heart/daemon/agent-config-check.js +494 -0
  155. package/dist/heart/daemon/agent-discovery.js +304 -3
  156. package/dist/heart/daemon/agent-home.js +409 -0
  157. package/dist/heart/daemon/agent-service.js +542 -0
  158. package/dist/heart/daemon/agentic-repair.js +548 -0
  159. package/dist/heart/daemon/await-private-wake.js +59 -0
  160. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  161. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  162. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  163. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  164. package/dist/heart/daemon/boot-sync-probe.js +223 -0
  165. package/dist/heart/daemon/cadence.js +180 -0
  166. package/dist/heart/daemon/cli-arg-redaction.js +26 -0
  167. package/dist/heart/daemon/cli-defaults.js +956 -0
  168. package/dist/heart/daemon/cli-desk.js +331 -0
  169. package/dist/heart/daemon/cli-exec.js +9619 -0
  170. package/dist/heart/daemon/cli-gate.js +170 -0
  171. package/dist/heart/daemon/cli-help.js +793 -0
  172. package/dist/heart/daemon/cli-manifest.js +127 -0
  173. package/dist/heart/daemon/cli-parse.js +3536 -0
  174. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  175. package/dist/heart/daemon/cli-render.js +823 -0
  176. package/dist/heart/daemon/cli-types.js +8 -0
  177. package/dist/heart/daemon/compile-cache.js +69 -0
  178. package/dist/heart/daemon/connect-bay.js +323 -0
  179. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  180. package/dist/heart/daemon/container-healthcheck.js +112 -0
  181. package/dist/heart/daemon/container-runtime.js +97 -0
  182. package/dist/heart/daemon/container-spec-auditor-main.js +187 -0
  183. package/dist/heart/daemon/container-spec-auditor.js +257 -0
  184. package/dist/heart/daemon/daemon-bootstrap-startup.js +115 -0
  185. package/dist/heart/daemon/daemon-cli.js +29 -2400
  186. package/dist/heart/daemon/daemon-entry.js +1123 -11
  187. package/dist/heart/daemon/daemon-health.js +186 -0
  188. package/dist/heart/daemon/daemon-rollup.js +57 -0
  189. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  190. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  191. package/dist/heart/daemon/daemon.js +2087 -129
  192. package/dist/heart/daemon/desk-admin.js +420 -0
  193. package/dist/heart/daemon/dns-workflow.js +394 -0
  194. package/dist/heart/daemon/doctor-types.js +8 -0
  195. package/dist/heart/daemon/doctor.js +1890 -0
  196. package/dist/heart/daemon/freshness.js +345 -0
  197. package/dist/heart/daemon/habit-private-wake.js +61 -0
  198. package/dist/heart/daemon/health-monitor.js +209 -12
  199. package/dist/heart/daemon/home-filesystem.js +93 -0
  200. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  201. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  202. package/dist/heart/daemon/http-health-probe.js +80 -0
  203. package/dist/heart/daemon/human-command-screens.js +234 -0
  204. package/dist/heart/daemon/human-readiness.js +114 -0
  205. package/dist/heart/daemon/inner-status.js +78 -0
  206. package/dist/heart/daemon/interactive-repair.js +394 -0
  207. package/dist/heart/daemon/launchd.js +40 -8
  208. package/dist/heart/daemon/linux-service.js +366 -0
  209. package/dist/heart/daemon/log-tailer.js +79 -10
  210. package/dist/heart/daemon/logs-prune.js +132 -0
  211. package/dist/heart/daemon/mcp-canary.js +525 -0
  212. package/dist/heart/daemon/message-router.js +65 -5
  213. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  214. package/dist/heart/daemon/os-cron-deps.js +139 -0
  215. package/dist/heart/daemon/os-cron.js +45 -15
  216. package/dist/heart/daemon/ouro-bot-entry.js +8 -3
  217. package/dist/heart/daemon/ouro-entry.js +32 -11
  218. package/dist/heart/daemon/plugin-cli.js +432 -0
  219. package/dist/heart/daemon/portable-git-install.js +265 -0
  220. package/dist/heart/daemon/portable-git.js +179 -0
  221. package/dist/heart/daemon/presence-daemon.js +265 -0
  222. package/dist/heart/daemon/presence-roster.js +259 -0
  223. package/dist/heart/daemon/presence.js +462 -0
  224. package/dist/heart/daemon/process-manager.js +763 -61
  225. package/dist/heart/daemon/provider-discovery.js +171 -0
  226. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  227. package/dist/heart/daemon/prunable-bundle.js +144 -0
  228. package/dist/heart/daemon/pulse.js +511 -0
  229. package/dist/heart/daemon/readiness-repair.js +365 -0
  230. package/dist/heart/daemon/run-hooks.js +2 -0
  231. package/dist/heart/daemon/runtime-logging.js +48 -14
  232. package/dist/heart/daemon/runtime-metadata.js +2 -30
  233. package/dist/heart/daemon/runtime-mode.js +13 -2
  234. package/dist/heart/daemon/safe-mode.js +161 -0
  235. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2659 -0
  236. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1832 -0
  237. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  238. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +956 -0
  239. package/dist/heart/daemon/sanctuary-authority-codec.js +86 -0
  240. package/dist/heart/daemon/sanctuary-authority-epoch.js +291 -0
  241. package/dist/heart/daemon/sanctuary-authority-installation.js +161 -0
  242. package/dist/heart/daemon/sanctuary-authority-ledger.js +241 -0
  243. package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +1348 -0
  244. package/dist/heart/daemon/sanctuary-authority-vault-migration.js +79 -0
  245. package/dist/heart/daemon/sanctuary-bundle-migration.js +974 -0
  246. package/dist/heart/daemon/sanctuary-host-authority.js +1008 -0
  247. package/dist/heart/daemon/sanctuary-host-detached-supervisor.js +493 -0
  248. package/dist/heart/daemon/sanctuary-host-executor.js +670 -0
  249. package/dist/heart/daemon/sanctuary-host-linux-kernel.js +334 -0
  250. package/dist/heart/daemon/sanctuary-host-supervisor-entry.js +207 -0
  251. package/dist/heart/daemon/sanctuary-host-supervisor.js +95 -0
  252. package/dist/heart/daemon/sanctuary-package-management.js +113 -0
  253. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  254. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  255. package/dist/heart/daemon/sanctuary-telegram-authority-entry.js +478 -0
  256. package/dist/heart/daemon/sanctuary-telegram-authority-gateway.js +614 -0
  257. package/dist/heart/daemon/sanctuary-telegram-authority-service.js +763 -0
  258. package/dist/heart/daemon/sanctuary-telegram-test-driver-entry.js +94 -0
  259. package/dist/heart/daemon/sanctuary-telegram-test-driver.js +294 -0
  260. package/dist/heart/daemon/sense-manager.js +890 -58
  261. package/dist/heart/daemon/session-id-resolver.js +131 -0
  262. package/dist/heart/daemon/skill-management-installer.js +1 -1
  263. package/dist/heart/daemon/socket-client.js +180 -12
  264. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  265. package/dist/heart/daemon/startup-tui.js +339 -0
  266. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  267. package/dist/heart/daemon/task-scheduler.js +117 -39
  268. package/dist/heart/daemon/terminal-ui.js +503 -0
  269. package/dist/heart/daemon/thoughts.js +138 -54
  270. package/dist/heart/daemon/up-progress.js +366 -0
  271. package/dist/heart/daemon/vault-items.js +56 -0
  272. package/dist/heart/daemon/vault-outage.js +74 -0
  273. package/dist/heart/delegation.js +1 -4
  274. package/dist/heart/external-events/router.js +1556 -0
  275. package/dist/heart/failure-reports.js +398 -0
  276. package/dist/heart/file-lock.js +109 -0
  277. package/dist/heart/frontend-approval-runtime.js +506 -0
  278. package/dist/heart/frontend-journal.js +215 -0
  279. package/dist/heart/frontend-session-service.js +330 -0
  280. package/dist/heart/frontend-socket-client.js +173 -0
  281. package/dist/heart/frontend-socket.js +434 -0
  282. package/dist/heart/frontend-turn-errors.js +20 -0
  283. package/dist/heart/habits/habit-cancel.js +810 -0
  284. package/dist/heart/habits/habit-lifecycle.js +1324 -0
  285. package/dist/heart/habits/habit-migration.js +194 -0
  286. package/dist/heart/habits/habit-parser.js +278 -0
  287. package/dist/heart/habits/habit-runtime-state.js +93 -0
  288. package/dist/heart/habits/habit-scheduler.js +667 -0
  289. package/dist/heart/habits/habit-session-summary.js +318 -0
  290. package/dist/heart/habits/habit-session.js +636 -0
  291. package/dist/heart/{daemon → hatch}/hatch-flow.js +68 -62
  292. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  293. package/dist/heart/{daemon → hatch}/specialist-prompt.js +13 -9
  294. package/dist/heart/{daemon → hatch}/specialist-tools.js +100 -20
  295. package/dist/heart/identity.js +337 -60
  296. package/dist/heart/kept-notes.js +289 -0
  297. package/dist/heart/kicks.js +1 -1
  298. package/dist/heart/machine-identity.js +175 -0
  299. package/dist/heart/mail-import-discovery.js +356 -0
  300. package/dist/heart/mailbox/mailbox-http-hooks.js +99 -0
  301. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  302. package/dist/heart/mailbox/mailbox-http-routes.js +406 -0
  303. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  304. package/dist/heart/mailbox/mailbox-http-transport.js +272 -0
  305. package/dist/heart/mailbox/mailbox-http.js +99 -0
  306. package/dist/heart/mailbox/mailbox-read.js +41 -0
  307. package/dist/heart/mailbox/mailbox-supervision.js +131 -0
  308. package/dist/heart/mailbox/mailbox-types.js +27 -0
  309. package/dist/heart/mailbox/mailbox-view.js +197 -0
  310. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  311. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  312. package/dist/heart/mailbox/readers/mail.js +375 -0
  313. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  314. package/dist/heart/mailbox/readers/sessions.js +231 -0
  315. package/dist/heart/mailbox/readers/shared.js +111 -0
  316. package/dist/heart/mcp/mcp-server.js +760 -0
  317. package/dist/heart/migrate-config.js +100 -0
  318. package/dist/heart/model-capabilities.js +98 -16
  319. package/dist/heart/model-limits.js +49 -0
  320. package/dist/heart/optional-packages.js +77 -0
  321. package/dist/heart/orientation-frame.js +381 -0
  322. package/dist/heart/platform.js +81 -0
  323. package/dist/heart/primitives.js +1 -1
  324. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  325. package/dist/heart/private-runtime/index.js +18 -0
  326. package/dist/heart/private-runtime/ledger.js +212 -0
  327. package/dist/heart/private-runtime/policy.js +295 -0
  328. package/dist/heart/private-runtime/types.js +2 -0
  329. package/dist/heart/progress-story.js +1 -1
  330. package/dist/heart/provider-attempt.js +137 -0
  331. package/dist/heart/provider-binding-resolver.js +273 -0
  332. package/dist/heart/provider-credentials.js +449 -0
  333. package/dist/heart/provider-failover.js +260 -37
  334. package/dist/heart/provider-fallback.js +228 -0
  335. package/dist/heart/provider-models.js +96 -0
  336. package/dist/heart/provider-ping-child.js +125 -0
  337. package/dist/heart/provider-ping-entry.js +8 -0
  338. package/dist/heart/provider-ping.js +236 -89
  339. package/dist/heart/provider-readiness-cache.js +119 -0
  340. package/dist/heart/provider-visibility.js +188 -0
  341. package/dist/heart/providers/account-pool.js +717 -0
  342. package/dist/heart/providers/anthropic-token.js +131 -0
  343. package/dist/heart/providers/anthropic.js +308 -85
  344. package/dist/heart/providers/azure.js +20 -32
  345. package/dist/heart/providers/error-classification.js +129 -0
  346. package/dist/heart/providers/github-copilot.js +131 -36
  347. package/dist/heart/providers/minimax-vlm.js +189 -0
  348. package/dist/heart/providers/minimax.js +20 -28
  349. package/dist/heart/providers/openai-codex-token.js +349 -0
  350. package/dist/heart/providers/openai-codex.js +47 -58
  351. package/dist/heart/providers/openai-compatible.js +177 -0
  352. package/dist/heart/quota/fleet-readings.js +222 -0
  353. package/dist/heart/quota/tranche.js +59 -0
  354. package/dist/heart/reach-channel.js +85 -0
  355. package/dist/heart/reply-style.js +52 -0
  356. package/dist/heart/run-ledger.js +247 -0
  357. package/dist/heart/runtime-capability-check.js +170 -0
  358. package/dist/heart/runtime-credentials.js +647 -0
  359. package/dist/heart/runtime-cwd.js +87 -0
  360. package/dist/heart/sense-truth.js +26 -4
  361. package/dist/heart/session-activity.js +94 -24
  362. package/dist/heart/session-events.js +1600 -0
  363. package/dist/heart/session-playback-cli-main.js +5 -0
  364. package/dist/heart/session-playback-cli.js +36 -0
  365. package/dist/heart/session-playback.js +231 -0
  366. package/dist/heart/session-redaction-repair-cli-main.js +31 -0
  367. package/dist/heart/session-redaction-repair.js +552 -0
  368. package/dist/heart/session-stats-cli-main.js +5 -0
  369. package/dist/heart/session-stats.js +183 -0
  370. package/dist/heart/session-transcript.js +133 -0
  371. package/dist/heart/shelf-claims.js +124 -0
  372. package/dist/heart/shepherd/custody-types.js +2 -0
  373. package/dist/heart/shepherd/mandates.js +352 -0
  374. package/dist/heart/shepherd/operation-commands.js +19 -0
  375. package/dist/heart/shepherd/operations.js +137 -0
  376. package/dist/heart/shepherd/supervision.js +114 -0
  377. package/dist/heart/shepherd/types.js +2 -0
  378. package/dist/heart/shepherd-config.js +113 -0
  379. package/dist/heart/source-grounding.js +313 -0
  380. package/dist/heart/sqlite.js +18 -0
  381. package/dist/heart/start-of-turn-packet.js +372 -0
  382. package/dist/heart/steward-policy.js +656 -0
  383. package/dist/heart/streaming.js +634 -206
  384. package/dist/heart/structured-output.js +196 -0
  385. package/dist/heart/sync-classification.js +176 -0
  386. package/dist/heart/sync-health.js +152 -0
  387. package/dist/heart/sync-lock.js +431 -0
  388. package/dist/heart/sync.js +1579 -0
  389. package/dist/heart/target-resolution.js +11 -7
  390. package/dist/heart/tempo.js +93 -0
  391. package/dist/heart/temporal-view.js +41 -0
  392. package/dist/heart/timeouts.js +101 -0
  393. package/dist/heart/tool-activity-callbacks.js +59 -0
  394. package/dist/heart/tool-approval.js +382 -0
  395. package/dist/heart/tool-description.js +155 -0
  396. package/dist/heart/tool-friction.js +55 -0
  397. package/dist/heart/tool-images.js +42 -0
  398. package/dist/heart/tool-loop.js +13 -1
  399. package/dist/heart/tool-output-budget.js +41 -0
  400. package/dist/heart/turn-context.js +503 -0
  401. package/dist/heart/turn-execution-lease.js +30 -0
  402. package/dist/heart/versioning/host-self-update.js +118 -0
  403. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  404. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +3 -2
  405. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  406. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  407. package/dist/heart/versioning/ouro-version-manager.js +432 -0
  408. package/dist/heart/versioning/release-sources.js +185 -0
  409. package/dist/heart/versioning/self-update-defaults.js +397 -0
  410. package/dist/heart/versioning/self-update.js +241 -0
  411. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  412. package/dist/heart/{daemon → versioning}/update-checker.js +12 -35
  413. package/dist/heart/versioning/update-hooks.js +160 -0
  414. package/dist/heart/versioning/update-state.js +134 -0
  415. package/dist/heart/versioning/updater-launchd.js +150 -0
  416. package/dist/heart/versioning/version-intent.js +114 -0
  417. package/dist/heart/work-card.js +380 -0
  418. package/dist/mailbox-ui/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  419. package/dist/mailbox-ui/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  420. package/dist/mailbox-ui/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  421. package/dist/mailbox-ui/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  422. package/dist/mailbox-ui/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  423. package/dist/mailbox-ui/assets/index-B28tVtPs.css +1 -0
  424. package/dist/mailbox-ui/assets/index-BcAOsNsy.js +1 -0
  425. package/dist/mailbox-ui/assets/vendor-D_wlGdJf.js +65 -0
  426. package/dist/mailbox-ui/index.html +18 -0
  427. package/dist/mailroom/attention.js +167 -0
  428. package/dist/mailroom/autonomy.js +209 -0
  429. package/dist/mailroom/azure-sdk.js +27 -0
  430. package/dist/mailroom/blob-store.js +974 -0
  431. package/dist/mailroom/body-cache.js +61 -0
  432. package/dist/mailroom/cache-sync-cli.js +58 -0
  433. package/dist/mailroom/core.js +805 -0
  434. package/dist/mailroom/entry.js +160 -0
  435. package/dist/mailroom/file-store.js +568 -0
  436. package/dist/mailroom/hosted-cache-sync.js +384 -0
  437. package/dist/mailroom/mbox-import.js +393 -0
  438. package/dist/mailroom/migration.js +164 -0
  439. package/dist/mailroom/outbound.js +380 -0
  440. package/dist/mailroom/policy.js +263 -0
  441. package/dist/mailroom/reader.js +291 -0
  442. package/dist/mailroom/search-cache.js +513 -0
  443. package/dist/mailroom/search-relevance.js +319 -0
  444. package/dist/mailroom/smtp-ingress.js +176 -0
  445. package/dist/mailroom/source-state.js +176 -0
  446. package/dist/mailroom/sweep-orphans-cli.js +34 -0
  447. package/dist/mailroom/thread.js +109 -0
  448. package/dist/mailroom/travel-extract.js +89 -0
  449. package/dist/mind/bundle-manifest.js +25 -2
  450. package/dist/mind/context.js +328 -139
  451. package/dist/mind/desk-section.js +342 -0
  452. package/dist/mind/diary-integrity.js +60 -0
  453. package/dist/mind/{memory.js → diary.js} +68 -77
  454. package/dist/mind/embedding-provider.js +60 -0
  455. package/dist/mind/file-state.js +179 -0
  456. package/dist/mind/friend-link-codes.js +209 -0
  457. package/dist/mind/friend-merge.js +336 -0
  458. package/dist/mind/house-names.js +43 -0
  459. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  460. package/dist/mind/obligation-steering.js +15 -9
  461. package/dist/mind/outbound-record.js +168 -0
  462. package/dist/mind/pending.js +36 -10
  463. package/dist/mind/prompt-budget.js +511 -0
  464. package/dist/mind/prompt-refresh.js +3 -2
  465. package/dist/mind/prompt.js +986 -266
  466. package/dist/mind/provenance-trust.js +26 -0
  467. package/dist/mind/record-paths.js +312 -0
  468. package/dist/mind/scrutiny.js +121 -0
  469. package/dist/mind/session-transaction.js +642 -0
  470. package/dist/mind/token-estimate.js +17 -0
  471. package/dist/mind/where-am-i.js +147 -0
  472. package/dist/nerves/cli-logging.js +7 -1
  473. package/dist/nerves/coverage/audit-rules.js +15 -6
  474. package/dist/nerves/coverage/audit.js +28 -2
  475. package/dist/nerves/coverage/cli.js +1 -1
  476. package/dist/nerves/coverage/contract.js +5 -5
  477. package/dist/nerves/coverage/file-completeness.js +151 -5
  478. package/dist/nerves/coverage/run-artifacts.js +55 -35
  479. package/dist/nerves/coverage/source-scanner.js +4 -4
  480. package/dist/nerves/event-buffer.js +111 -0
  481. package/dist/nerves/index.js +293 -9
  482. package/dist/nerves/observation.js +20 -0
  483. package/dist/nerves/redact.js +79 -0
  484. package/dist/nerves/review/cli-main.js +5 -0
  485. package/dist/nerves/review/cli.js +156 -0
  486. package/dist/nerves/review/core.js +159 -0
  487. package/dist/nerves/runtime.js +17 -1
  488. package/dist/repertoire/ado-client.js +15 -56
  489. package/dist/repertoire/ado-semantic.js +19 -12
  490. package/dist/repertoire/api-client.js +97 -0
  491. package/dist/repertoire/auth-required.js +22 -0
  492. package/dist/repertoire/bitwarden-native.js +458 -0
  493. package/dist/repertoire/bitwarden-store.js +1296 -0
  494. package/dist/repertoire/bundle-templates.js +71 -0
  495. package/dist/repertoire/bw-installer.js +268 -0
  496. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  497. package/dist/repertoire/coding/context-pack.js +80 -3
  498. package/dist/repertoire/coding/feedback.js +26 -5
  499. package/dist/repertoire/coding/index.js +15 -3
  500. package/dist/repertoire/coding/manager.js +19 -11
  501. package/dist/repertoire/coding/spawner.js +22 -5
  502. package/dist/repertoire/coding/tools.js +116 -16
  503. package/dist/repertoire/coding/workbench-client.js +272 -0
  504. package/dist/repertoire/coding/workbench-manager.js +346 -0
  505. package/dist/repertoire/commerce-errors.js +109 -0
  506. package/dist/repertoire/commerce-self-test.js +156 -0
  507. package/dist/repertoire/credential-access.js +183 -0
  508. package/dist/repertoire/deferred-tools.js +117 -0
  509. package/dist/repertoire/desk/classifier.js +362 -0
  510. package/dist/repertoire/duffel-client.js +185 -0
  511. package/dist/repertoire/github-client.js +14 -55
  512. package/dist/repertoire/graph-client.js +11 -52
  513. package/dist/repertoire/guardrails.js +1040 -69
  514. package/dist/repertoire/house-sweep.js +471 -0
  515. package/dist/repertoire/mcp-client.js +58 -5
  516. package/dist/repertoire/mcp-manager.js +427 -139
  517. package/dist/repertoire/mcp-tools.js +148 -0
  518. package/dist/repertoire/mcp-write-guard.js +46 -0
  519. package/dist/repertoire/plugin-mcp.js +175 -0
  520. package/dist/repertoire/plugins.js +253 -0
  521. package/dist/repertoire/relationship-authorization.js +322 -0
  522. package/dist/repertoire/sanctuary-container-policy.js +50 -0
  523. package/dist/repertoire/shell-sessions.js +135 -0
  524. package/dist/repertoire/skill-summaries.js +108 -0
  525. package/dist/repertoire/skills.js +48 -4
  526. package/dist/repertoire/stripe-client.js +163 -0
  527. package/dist/repertoire/tool-arguments.js +180 -0
  528. package/dist/repertoire/tool-limits.js +20 -0
  529. package/dist/repertoire/tool-results.js +29 -0
  530. package/dist/repertoire/tools-a2a.js +742 -0
  531. package/dist/repertoire/tools-app-sessions.js +188 -0
  532. package/dist/repertoire/tools-attachments.js +278 -0
  533. package/dist/repertoire/tools-awaiting.js +904 -0
  534. package/dist/repertoire/tools-base.js +83 -1378
  535. package/dist/repertoire/tools-bridge.js +144 -0
  536. package/dist/repertoire/tools-bundle.js +917 -0
  537. package/dist/repertoire/tools-chat.js +166 -0
  538. package/dist/repertoire/tools-commerce.js +253 -0
  539. package/dist/repertoire/tools-config.js +186 -0
  540. package/dist/repertoire/tools-continuity.js +602 -0
  541. package/dist/repertoire/tools-credential.js +383 -0
  542. package/dist/repertoire/tools-escalation.js +92 -0
  543. package/dist/repertoire/tools-evolution.js +527 -0
  544. package/dist/repertoire/tools-files.js +463 -0
  545. package/dist/repertoire/tools-flight.js +290 -0
  546. package/dist/repertoire/tools-flow.js +119 -0
  547. package/dist/repertoire/tools-friend-link.js +57 -0
  548. package/dist/repertoire/tools-github.js +7 -10
  549. package/dist/repertoire/tools-habits.js +103 -0
  550. package/dist/repertoire/tools-house-care.js +174 -0
  551. package/dist/repertoire/tools-mail.js +1842 -0
  552. package/dist/repertoire/tools-notes.js +501 -0
  553. package/dist/repertoire/tools-obligations.js +182 -0
  554. package/dist/repertoire/tools-orientation.js +31 -0
  555. package/dist/repertoire/tools-record.js +482 -0
  556. package/dist/repertoire/tools-rsvp.js +139 -0
  557. package/dist/repertoire/tools-runtime.js +238 -0
  558. package/dist/repertoire/tools-sanctuary-host.js +202 -0
  559. package/dist/repertoire/tools-session.js +1162 -0
  560. package/dist/repertoire/tools-shell.js +248 -0
  561. package/dist/repertoire/tools-shepherd-guidance.js +171 -0
  562. package/dist/repertoire/tools-shepherd.js +325 -0
  563. package/dist/repertoire/tools-steward-policy.js +147 -0
  564. package/dist/repertoire/tools-stripe.js +224 -0
  565. package/dist/repertoire/tools-surface.js +393 -0
  566. package/dist/repertoire/tools-teams.js +19 -45
  567. package/dist/repertoire/tools-telegram-contacts.js +37 -0
  568. package/dist/repertoire/tools-travel.js +125 -0
  569. package/dist/repertoire/tools-trip.js +982 -0
  570. package/dist/repertoire/tools-unraid.js +559 -0
  571. package/dist/repertoire/tools-user-profile.js +146 -0
  572. package/dist/repertoire/tools-vault.js +40 -0
  573. package/dist/repertoire/tools-voice-local.js +198 -0
  574. package/dist/repertoire/tools-voice.js +145 -0
  575. package/dist/repertoire/tools-web.js +230 -0
  576. package/dist/repertoire/tools.js +536 -157
  577. package/dist/repertoire/travel-api-client.js +360 -0
  578. package/dist/repertoire/unraid-client.js +155 -0
  579. package/dist/repertoire/unraid-restart.js +342 -0
  580. package/dist/repertoire/user-profile.js +131 -0
  581. package/dist/repertoire/vault-setup.js +298 -0
  582. package/dist/repertoire/vault-unlock.js +816 -0
  583. package/dist/rsvp/aisleplanner-client.js +354 -0
  584. package/dist/rsvp/cli.js +936 -0
  585. package/dist/rsvp/config.js +327 -0
  586. package/dist/rsvp/cutover.js +453 -0
  587. package/dist/rsvp/diagnostics.js +232 -0
  588. package/dist/rsvp/diff-renderer.js +176 -0
  589. package/dist/rsvp/habit-policy.js +110 -0
  590. package/dist/rsvp/habit-stage.js +123 -0
  591. package/dist/rsvp/incident-bundle.js +97 -0
  592. package/dist/rsvp/migration.js +204 -0
  593. package/dist/rsvp/native-habit-runner.js +630 -0
  594. package/dist/rsvp/outbound-state.js +628 -0
  595. package/dist/rsvp/query.js +118 -0
  596. package/dist/rsvp/replay.js +233 -0
  597. package/dist/rsvp/snapshot.js +232 -0
  598. package/dist/rsvp/spend-ledger.js +175 -0
  599. package/dist/scripts/claude-code-hook.js +41 -0
  600. package/dist/scripts/claude-code-stop-hook.js +47 -0
  601. package/dist/senses/a2a-entry.js +140 -0
  602. package/dist/senses/acp-server.js +386 -0
  603. package/dist/senses/app-sessions/client.js +128 -0
  604. package/dist/senses/app-sessions/digest-cards.js +187 -0
  605. package/dist/senses/app-sessions/digest-push.js +108 -0
  606. package/dist/senses/app-sessions/digest-sources.js +204 -0
  607. package/dist/senses/app-sessions/digest.js +284 -0
  608. package/dist/senses/app-sessions/run-command.js +51 -0
  609. package/dist/senses/app-sessions/sense.js +252 -0
  610. package/dist/senses/app-sessions/shepherd-cli.js +166 -0
  611. package/dist/senses/app-sessions/shepherd-rows.js +67 -0
  612. package/dist/senses/app-sessions/store.js +149 -0
  613. package/dist/senses/app-sessions/waiting-prompts.js +137 -0
  614. package/dist/senses/app-sessions/waiting-status.js +23 -0
  615. package/dist/senses/app-sessions-entry.js +86 -0
  616. package/dist/senses/attention-queue.js +186 -0
  617. package/dist/senses/await-turn-message.js +65 -0
  618. package/dist/senses/bluebubbles/active-turns.js +216 -0
  619. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  620. package/dist/senses/bluebubbles/attachment-download.js +143 -0
  621. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +373 -43
  622. package/dist/senses/bluebubbles/context-packet.js +207 -0
  623. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  624. package/dist/senses/bluebubbles/entry.js +90 -0
  625. package/dist/senses/bluebubbles/host-account-verifier.js +88 -0
  626. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +21 -3
  627. package/dist/senses/bluebubbles/index.js +4070 -0
  628. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  629. package/dist/senses/bluebubbles/media.js +256 -0
  630. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +147 -30
  631. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +24 -13
  632. package/dist/senses/bluebubbles/outbound-state.js +335 -0
  633. package/dist/senses/bluebubbles/processed-log.js +133 -0
  634. package/dist/senses/bluebubbles/reactions.js +18 -0
  635. package/dist/senses/bluebubbles/replay.js +284 -0
  636. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  637. package/dist/senses/bluebubbles/semantic-receipts.js +1983 -0
  638. package/dist/senses/bluebubbles/send-file.js +20 -0
  639. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  640. package/dist/senses/bluebubbles/webhook-registration.js +257 -0
  641. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  642. package/dist/senses/chat-file.js +75 -0
  643. package/dist/senses/cli/bracketed-paste.js +82 -0
  644. package/dist/senses/cli/image-paste.js +287 -0
  645. package/dist/senses/cli/image-ref-navigation.js +75 -0
  646. package/dist/senses/cli/ink-app.js +156 -0
  647. package/dist/senses/cli/inline-diff.js +64 -0
  648. package/dist/senses/cli/input-keys.js +174 -0
  649. package/dist/senses/cli/kill-ring.js +86 -0
  650. package/dist/senses/cli/message-list.js +51 -0
  651. package/dist/senses/cli/ouro-tui.js +607 -0
  652. package/dist/senses/cli/spinner-imperative.js +135 -0
  653. package/dist/senses/cli/spinner.js +101 -0
  654. package/dist/senses/cli/status-line.js +60 -0
  655. package/dist/senses/cli/streaming-markdown.js +526 -0
  656. package/dist/senses/cli/tool-display.js +85 -0
  657. package/dist/senses/cli/tool-render.js +85 -0
  658. package/dist/senses/cli/tui-store.js +252 -0
  659. package/dist/senses/cli/virtual-list.js +35 -0
  660. package/dist/senses/cli-entry.js +60 -8
  661. package/dist/senses/cli.js +607 -352
  662. package/dist/senses/commands.js +66 -3
  663. package/dist/senses/context-packet-ledger.js +367 -0
  664. package/dist/senses/context-packets.js +154 -0
  665. package/dist/senses/habit-lifecycle-guard.js +24 -0
  666. package/dist/senses/habit-turn-message.js +160 -0
  667. package/dist/senses/ingress-evidence.js +2 -0
  668. package/dist/senses/mail-entry.js +68 -0
  669. package/dist/senses/mail.js +524 -0
  670. package/dist/senses/ordinary-owner-decision.js +97 -0
  671. package/dist/senses/pipeline.js +1139 -273
  672. package/dist/senses/private-runtime-worker.js +857 -0
  673. package/dist/senses/private-runtime.js +1686 -0
  674. package/dist/senses/proactive-content-guard.js +51 -0
  675. package/dist/senses/repeat-while.js +36 -0
  676. package/dist/senses/root-host-approval-port.js +345 -0
  677. package/dist/senses/root-host-approval-runtime.js +393 -0
  678. package/dist/senses/sanctuary-authority-resident.js +102 -0
  679. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  680. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  681. package/dist/senses/sanctuary-grounding.js +118 -0
  682. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  683. package/dist/senses/sanctuary-health-acceptance-probe.js +786 -0
  684. package/dist/senses/sanctuary-health-runner.js +106 -0
  685. package/dist/senses/sanctuary-health.js +442 -0
  686. package/dist/senses/sanctuary-house.js +97 -0
  687. package/dist/senses/sanctuary-install-state-contract.js +169 -0
  688. package/dist/senses/sanctuary-interactive-control.js +410 -0
  689. package/dist/senses/sanctuary-media-catalog-contract.js +268 -0
  690. package/dist/senses/sanctuary-media-optimization.js +517 -0
  691. package/dist/senses/sanctuary-runtime.js +390 -0
  692. package/dist/senses/sanctuary-sab.js +85 -0
  693. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  694. package/dist/senses/shared-turn.js +827 -0
  695. package/dist/senses/shepherd/agent-presentation.js +88 -0
  696. package/dist/senses/shepherd/attention-page.js +166 -0
  697. package/dist/senses/shepherd/attention-sidebar.js +76 -0
  698. package/dist/senses/shepherd/attention.js +295 -0
  699. package/dist/senses/shepherd/checkin-config.js +76 -0
  700. package/dist/senses/shepherd/checkin-store.js +383 -0
  701. package/dist/senses/shepherd/client.js +196 -0
  702. package/dist/senses/shepherd/cmux.js +483 -0
  703. package/dist/senses/shepherd/composer.js +336 -0
  704. package/dist/senses/shepherd/conversation-hold.js +78 -0
  705. package/dist/senses/shepherd/feedback-reply.js +108 -0
  706. package/dist/senses/shepherd/feedback-source.js +20 -0
  707. package/dist/senses/shepherd/feedback-store.js +328 -0
  708. package/dist/senses/shepherd/feedback-submit.js +182 -0
  709. package/dist/senses/shepherd/feedback-worker.js +208 -0
  710. package/dist/senses/shepherd/guidance.js +273 -0
  711. package/dist/senses/shepherd/herdr.js +427 -0
  712. package/dist/senses/shepherd/host.js +14 -0
  713. package/dist/senses/shepherd/human-decision-guard.js +29 -0
  714. package/dist/senses/shepherd/judge-evaluation-command.js +183 -0
  715. package/dist/senses/shepherd/judge-evaluation-entry.js +13 -0
  716. package/dist/senses/shepherd/judge-evaluation.js +155 -0
  717. package/dist/senses/shepherd/judge.js +210 -0
  718. package/dist/senses/shepherd/notice-outbox.js +254 -0
  719. package/dist/senses/shepherd/observation-publisher.js +320 -0
  720. package/dist/senses/shepherd/operations-defaults.js +86 -0
  721. package/dist/senses/shepherd/operations.js +159 -0
  722. package/dist/senses/shepherd/owner-notice.js +496 -0
  723. package/dist/senses/shepherd/prompt-state.js +60 -0
  724. package/dist/senses/shepherd/recovery.js +543 -0
  725. package/dist/senses/shepherd/redact.js +66 -0
  726. package/dist/senses/shepherd/returns.js +79 -0
  727. package/dist/senses/shepherd/sense.js +862 -0
  728. package/dist/senses/shepherd/shepherd-judge-corpus-v1.json +170 -0
  729. package/dist/senses/shepherd/surface.js +125 -0
  730. package/dist/senses/shepherd/target-binding.js +13 -0
  731. package/dist/senses/shepherd/terminal-process.js +147 -0
  732. package/dist/senses/shepherd-entry.js +98 -0
  733. package/dist/senses/surface-tool.js +121 -0
  734. package/dist/senses/teams-attachments.js +68 -0
  735. package/dist/senses/teams-entry.js +78 -8
  736. package/dist/senses/teams-image.js +128 -0
  737. package/dist/senses/teams-off-turn.js +198 -0
  738. package/dist/senses/teams-outbox.js +242 -0
  739. package/dist/senses/teams.js +1167 -369
  740. package/dist/senses/telegram-admission.js +700 -0
  741. package/dist/senses/telegram-approval-runtime.js +793 -0
  742. package/dist/senses/telegram-attachments.js +128 -0
  743. package/dist/senses/telegram-audit-ledger.js +220 -0
  744. package/dist/senses/telegram-authority-transport.js +233 -0
  745. package/dist/senses/telegram-chat-actions.js +54 -0
  746. package/dist/senses/telegram-client.js +1799 -0
  747. package/dist/senses/telegram-effect-adapter.js +907 -0
  748. package/dist/senses/telegram-entry.js +86 -0
  749. package/dist/senses/telegram-handoff.js +150 -0
  750. package/dist/senses/telegram-identity-key.js +143 -0
  751. package/dist/senses/telegram.js +2370 -0
  752. package/dist/senses/terminal-handoff.js +44 -0
  753. package/dist/senses/trust-gate.js +104 -9
  754. package/dist/senses/voice/audio-playback.js +237 -0
  755. package/dist/senses/voice/audio-routing.js +119 -0
  756. package/dist/senses/voice/call-auth.js +250 -0
  757. package/dist/senses/voice/elevenlabs.js +202 -0
  758. package/dist/senses/voice/floor-control.js +431 -0
  759. package/dist/senses/voice/floor-controller.js +115 -0
  760. package/dist/senses/voice/golden-path.js +116 -0
  761. package/dist/senses/voice/index.js +29 -0
  762. package/dist/senses/voice/local-audio-control.js +344 -0
  763. package/dist/senses/voice/local-audio-devices.js +516 -0
  764. package/dist/senses/voice/local-audio-disclosure.js +174 -0
  765. package/dist/senses/voice/local-audio-identity.js +103 -0
  766. package/dist/senses/voice/local-audio-join.js +325 -0
  767. package/dist/senses/voice/local-audio-mute.js +199 -0
  768. package/dist/senses/voice/local-audio-notify.js +124 -0
  769. package/dist/senses/voice/local-audio-prompts.js +116 -0
  770. package/dist/senses/voice/local-audio-transport.js +427 -0
  771. package/dist/senses/voice/local-audio.js +281 -0
  772. package/dist/senses/voice/local-media-stream.js +145 -0
  773. package/dist/senses/voice/meeting.js +113 -0
  774. package/dist/senses/voice/outbound.js +190 -0
  775. package/dist/senses/voice/phone.js +33 -0
  776. package/dist/senses/voice/playback.js +139 -0
  777. package/dist/senses/voice/process-guards.js +51 -0
  778. package/dist/senses/voice/realtime-eval.js +496 -0
  779. package/dist/senses/voice/realtime-tool-schema.js +195 -0
  780. package/dist/senses/voice/realtime-trace.js +531 -0
  781. package/dist/senses/voice/transcript.js +70 -0
  782. package/dist/senses/voice/turn.js +191 -0
  783. package/dist/senses/voice/twilio-phone-runtime.js +836 -0
  784. package/dist/senses/voice/twilio-phone.js +5454 -0
  785. package/dist/senses/voice/types.js +2 -0
  786. package/dist/senses/voice/whisper.js +153 -0
  787. package/dist/senses/voice-entry.js +83 -0
  788. package/dist/senses/voice-realtime-eval-command.js +99 -0
  789. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  790. package/dist/senses/voice-twilio-entry.js +87 -0
  791. package/dist/trips/core.js +138 -0
  792. package/dist/trips/store.js +265 -0
  793. package/dist/util/frontmatter.js +69 -0
  794. package/node_modules/@ouro.bot/friends/LICENSE +201 -0
  795. package/node_modules/@ouro.bot/friends/README.md +674 -0
  796. package/node_modules/@ouro.bot/friends/changelog.json +125 -0
  797. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.d.ts +39 -0
  798. package/node_modules/@ouro.bot/friends/dist/a2a-client/a2a-message.js +54 -0
  799. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +117 -0
  800. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.js +202 -0
  801. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.d.ts +50 -0
  802. package/node_modules/@ouro.bot/friends/dist/a2a-client/agent-card.js +32 -0
  803. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.d.ts +38 -0
  804. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-key.js +120 -0
  805. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.d.ts +195 -0
  806. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-verifier.js +342 -0
  807. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.d.ts +26 -0
  808. package/node_modules/@ouro.bot/friends/dist/a2a-client/did-web.js +140 -0
  809. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +62 -0
  810. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +79 -0
  811. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.d.ts +26 -0
  812. package/node_modules/@ouro.bot/friends/dist/a2a-client/index.js +82 -0
  813. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.d.ts +5 -0
  814. package/node_modules/@ouro.bot/friends/dist/a2a-client/jcs.js +84 -0
  815. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.d.ts +22 -0
  816. package/node_modules/@ouro.bot/friends/dist/a2a-client/reachability.js +17 -0
  817. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.d.ts +15 -0
  818. package/node_modules/@ouro.bot/friends/dist/a2a-client/roster-verify.js +61 -0
  819. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.d.ts +47 -0
  820. package/node_modules/@ouro.bot/friends/dist/a2a-client/seal.js +95 -0
  821. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.d.ts +58 -0
  822. package/node_modules/@ouro.bot/friends/dist/a2a-client/sealed-envelope.js +113 -0
  823. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.d.ts +42 -0
  824. package/node_modules/@ouro.bot/friends/dist/a2a-client/sign.js +87 -0
  825. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.d.ts +5 -0
  826. package/node_modules/@ouro.bot/friends/dist/a2a-client/sodium.js +19 -0
  827. package/node_modules/@ouro.bot/friends/dist/account-roster.d.ts +52 -0
  828. package/node_modules/@ouro.bot/friends/dist/account-roster.js +108 -0
  829. package/node_modules/@ouro.bot/friends/dist/agent-peer.d.ts +26 -0
  830. package/node_modules/@ouro.bot/friends/dist/agent-peer.js +138 -0
  831. package/node_modules/@ouro.bot/friends/dist/audit.d.ts +42 -0
  832. package/node_modules/@ouro.bot/friends/dist/audit.js +86 -0
  833. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +11 -0
  834. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/channel.js +80 -3
  835. package/node_modules/@ouro.bot/friends/dist/connect-authority.d.ts +43 -0
  836. package/node_modules/@ouro.bot/friends/dist/connect-authority.js +84 -0
  837. package/node_modules/@ouro.bot/friends/dist/connect.d.ts +56 -0
  838. package/node_modules/@ouro.bot/friends/dist/connect.js +163 -0
  839. package/node_modules/@ouro.bot/friends/dist/consent.d.ts +34 -0
  840. package/node_modules/@ouro.bot/friends/dist/consent.js +65 -0
  841. package/node_modules/@ouro.bot/friends/dist/coordination.d.ts +116 -0
  842. package/node_modules/@ouro.bot/friends/dist/coordination.js +329 -0
  843. package/node_modules/@ouro.bot/friends/dist/delegation-grant.d.ts +21 -0
  844. package/node_modules/@ouro.bot/friends/dist/delegation-grant.js +39 -0
  845. package/node_modules/@ouro.bot/friends/dist/file-bundle.d.ts +17 -0
  846. package/node_modules/@ouro.bot/friends/dist/file-bundle.js +27 -0
  847. package/node_modules/@ouro.bot/friends/dist/friend-lookup.d.ts +9 -0
  848. package/node_modules/@ouro.bot/friends/dist/friend-lookup.js +69 -0
  849. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +16 -0
  850. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +136 -0
  851. package/node_modules/@ouro.bot/friends/dist/grant-store.d.ts +7 -0
  852. package/node_modules/@ouro.bot/friends/dist/grant-store.js +8 -0
  853. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +39 -0
  854. package/node_modules/@ouro.bot/friends/dist/grants.js +84 -0
  855. package/node_modules/@ouro.bot/friends/dist/group-context.d.ts +21 -0
  856. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/group-context.js +5 -4
  857. package/node_modules/@ouro.bot/friends/dist/identity.d.ts +17 -0
  858. package/node_modules/@ouro.bot/friends/dist/identity.js +68 -0
  859. package/node_modules/@ouro.bot/friends/dist/index.d.ts +73 -0
  860. package/node_modules/@ouro.bot/friends/dist/index.js +161 -0
  861. package/node_modules/@ouro.bot/friends/dist/link-identity.d.ts +14 -0
  862. package/node_modules/@ouro.bot/friends/dist/link-identity.js +157 -0
  863. package/node_modules/@ouro.bot/friends/dist/mailbox/index.d.ts +105 -0
  864. package/node_modules/@ouro.bot/friends/dist/mailbox/index.js +205 -0
  865. package/node_modules/@ouro.bot/friends/dist/mcp/bin.d.ts +2 -0
  866. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +16 -0
  867. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.d.ts +40 -0
  868. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +549 -0
  869. package/node_modules/@ouro.bot/friends/dist/mcp/index.d.ts +6 -0
  870. package/node_modules/@ouro.bot/friends/dist/mcp/index.js +14 -0
  871. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.d.ts +7 -0
  872. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +48 -0
  873. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.d.ts +10 -0
  874. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +445 -0
  875. package/node_modules/@ouro.bot/friends/dist/mcp/server.d.ts +30 -0
  876. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +194 -0
  877. package/node_modules/@ouro.bot/friends/dist/message.d.ts +75 -0
  878. package/node_modules/@ouro.bot/friends/dist/message.js +99 -0
  879. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +82 -0
  880. package/node_modules/@ouro.bot/friends/dist/mission-result.js +200 -0
  881. package/node_modules/@ouro.bot/friends/dist/mission-share.d.ts +94 -0
  882. package/node_modules/@ouro.bot/friends/dist/mission-share.js +232 -0
  883. package/node_modules/@ouro.bot/friends/dist/mission-store-file.d.ts +18 -0
  884. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +161 -0
  885. package/node_modules/@ouro.bot/friends/dist/mission-store.d.ts +10 -0
  886. package/node_modules/@ouro.bot/friends/dist/mission-store.js +9 -0
  887. package/node_modules/@ouro.bot/friends/dist/missions.d.ts +31 -0
  888. package/node_modules/@ouro.bot/friends/dist/missions.js +98 -0
  889. package/node_modules/@ouro.bot/friends/dist/notes.d.ts +11 -0
  890. package/node_modules/@ouro.bot/friends/dist/notes.js +90 -0
  891. package/node_modules/@ouro.bot/friends/dist/observability.d.ts +27 -0
  892. package/node_modules/@ouro.bot/friends/dist/observability.js +31 -0
  893. package/node_modules/@ouro.bot/friends/dist/outcomes.d.ts +9 -0
  894. package/node_modules/@ouro.bot/friends/dist/outcomes.js +51 -0
  895. package/node_modules/@ouro.bot/friends/dist/resolver.d.ts +59 -0
  896. package/node_modules/@ouro.bot/friends/dist/resolver.js +276 -0
  897. package/node_modules/@ouro.bot/friends/dist/results.d.ts +10 -0
  898. package/node_modules/@ouro.bot/friends/dist/results.js +2 -0
  899. package/node_modules/@ouro.bot/friends/dist/room.d.ts +22 -0
  900. package/node_modules/@ouro.bot/friends/dist/room.js +40 -0
  901. package/node_modules/@ouro.bot/friends/dist/roster-store-file.d.ts +16 -0
  902. package/node_modules/@ouro.bot/friends/dist/roster-store-file.js +125 -0
  903. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.d.ts +9 -0
  904. package/node_modules/@ouro.bot/friends/dist/roster-store-memory.js +20 -0
  905. package/node_modules/@ouro.bot/friends/dist/roster-store.d.ts +29 -0
  906. package/node_modules/@ouro.bot/friends/dist/roster-store.js +9 -0
  907. package/node_modules/@ouro.bot/friends/dist/roster-verifier.d.ts +23 -0
  908. package/node_modules/@ouro.bot/friends/dist/roster-verifier.js +47 -0
  909. package/node_modules/@ouro.bot/friends/dist/share.d.ts +108 -0
  910. package/node_modules/@ouro.bot/friends/dist/share.js +278 -0
  911. package/node_modules/@ouro.bot/friends/dist/standing.d.ts +83 -0
  912. package/node_modules/@ouro.bot/friends/dist/standing.js +111 -0
  913. package/node_modules/@ouro.bot/friends/dist/store-file.d.ts +82 -0
  914. package/node_modules/@ouro.bot/friends/dist/store-file.js +1074 -0
  915. package/node_modules/@ouro.bot/friends/dist/store.d.ts +43 -0
  916. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +8 -0
  917. package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/tokens.js +2 -2
  918. package/node_modules/@ouro.bot/friends/dist/trust-explanation.d.ts +22 -0
  919. package/node_modules/@ouro.bot/friends/dist/trust-explanation.js +90 -0
  920. package/node_modules/@ouro.bot/friends/dist/trust-mutation.d.ts +16 -0
  921. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +67 -0
  922. package/node_modules/@ouro.bot/friends/dist/types.d.ts +321 -0
  923. package/node_modules/@ouro.bot/friends/dist/types.js +55 -0
  924. package/node_modules/@ouro.bot/friends/dist/util/cap-string.d.ts +7 -0
  925. package/node_modules/@ouro.bot/friends/dist/util/cap-string.js +35 -0
  926. package/node_modules/@ouro.bot/friends/dist/verifier.d.ts +11 -0
  927. package/node_modules/@ouro.bot/friends/dist/verifier.js +29 -0
  928. package/node_modules/@ouro.bot/friends/dist/whoami.d.ts +7 -0
  929. package/node_modules/@ouro.bot/friends/dist/whoami.js +39 -0
  930. package/node_modules/@ouro.bot/friends/package.json +81 -0
  931. package/node_modules/libsodium/LICENSE +16 -0
  932. package/node_modules/libsodium/README.md +281 -0
  933. package/node_modules/libsodium/dist/modules/libsodium.js +1 -0
  934. package/node_modules/libsodium/dist/modules-esm/libsodium.mjs +1 -0
  935. package/node_modules/libsodium/package.json +54 -0
  936. package/node_modules/libsodium-wrappers/LICENSE +16 -0
  937. package/node_modules/libsodium-wrappers/README.md +281 -0
  938. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.d.ts +2155 -0
  939. package/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js +1 -0
  940. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.d.mts +2743 -0
  941. package/node_modules/libsodium-wrappers/dist/modules-esm/libsodium-wrappers.mjs +1 -0
  942. package/node_modules/libsodium-wrappers/package.json +74 -0
  943. package/npm-shrinkwrap.json +8789 -0
  944. package/package.json +92 -14
  945. package/skills/agent-commerce.md +113 -0
  946. package/skills/browser-navigation.md +117 -0
  947. package/skills/commerce-setup-guide.md +116 -0
  948. package/skills/commerce-setup.md +84 -0
  949. package/skills/configure-dev-tools.md +99 -0
  950. package/skills/sense-setup.md +56 -0
  951. package/skills/travel-planning.md +138 -0
  952. package/dist/heart/daemon/auth-flow.js +0 -430
  953. package/dist/heart/daemon/ouro-path-installer.js +0 -205
  954. package/dist/heart/daemon/ouro-version-manager.js +0 -171
  955. package/dist/heart/daemon/update-hooks.js +0 -138
  956. package/dist/heart/obligations.js +0 -197
  957. package/dist/heart/safe-workspace.js +0 -381
  958. package/dist/heart/session-recall.js +0 -216
  959. package/dist/mind/friends/resolver.js +0 -84
  960. package/dist/mind/friends/store-file.js +0 -190
  961. package/dist/mind/friends/trust-explanation.js +0 -74
  962. package/dist/mind/friends/types.js +0 -29
  963. package/dist/repertoire/tasks/board.js +0 -134
  964. package/dist/repertoire/tasks/index.js +0 -224
  965. package/dist/repertoire/tasks/lifecycle.js +0 -80
  966. package/dist/repertoire/tasks/middleware.js +0 -65
  967. package/dist/repertoire/tasks/parser.js +0 -173
  968. package/dist/repertoire/tasks/scanner.js +0 -132
  969. package/dist/repertoire/tasks/transitions.js +0 -144
  970. package/dist/repertoire/tools-bluebubbles.js +0 -93
  971. package/dist/senses/bluebubbles-entry.js +0 -13
  972. package/dist/senses/bluebubbles-media.js +0 -339
  973. package/dist/senses/bluebubbles.js +0 -1199
  974. package/dist/senses/debug-activity.js +0 -154
  975. package/dist/senses/inner-dialog-worker.js +0 -90
  976. package/dist/senses/inner-dialog.js +0 -536
  977. package/subagents/README.md +0 -7
  978. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  979. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  980. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  981. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  982. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  983. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  984. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  985. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  986. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  987. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  988. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  989. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  990. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  991. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  992. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  993. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  994. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
  995. /package/{dist/mind/friends → node_modules/@ouro.bot/friends/dist}/store.js +0 -0
@@ -0,0 +1,2489 @@
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(". ")}. Ask the owner whether to keep waiting, find another release, or give up; do not remove it on your own, because removing a partial download loses its progress.${neverStarted.length ? ` Separately, ${neverStarted.length} download(s) never started (${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. Do not promise an ETA.` : ""}` }
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 never landed 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 — it was never requested." }
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 do not 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
+ return { kind: a.kind, service_id: item.id, title: item.title, command, queue: queueReport(await itemQueue(a.kind, item.id), a.kind) }
1112
+ }
1113
+
1114
+ // Whether a download may be removed without the owner naming it. A download that has never
1115
+ // started is dead once past the stall window. A partial one is dead only when observed with no
1116
+ // ETA and no progress across 30 minutes: age alone is not enough (a 75.9% pack with no seeders
1117
+ // today can finish when one returns), and anything with an ETA is still moving.
1118
+ const hasEta = (row) => row.timeleft !== undefined && row.timeleft !== null && row.timeleft !== "00:00:00"
1119
+ export function removalVerdict(row, nowMs, previous) {
1120
+ if (hasEta(row)) return "still_downloading"
1121
+ const left = row.sizeleft ?? 0
1122
+ if ((row.size ?? 0) > 0 && left >= row.size) return isStalledRow(row, nowMs) ? "dead" : "not_started_yet"
1123
+ if (row.status === "failed") return "dead"
1124
+ const unchanged = previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS
1125
+ return unchanged ? "dead" : "stall_unconfirmed"
1126
+ }
1127
+
1128
+ export async function mediaBlocklistStalled(a) {
1129
+ if (a.kind !== "series" && a.kind !== "movie") return { result: "invalid_kind", message: "kind must be 'series' or 'movie'." }
1130
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1131
+ const serviceId = Number(a.service_id)
1132
+ const rows = await itemQueue(a.kind, serviceId)
1133
+ const now = Date.now()
1134
+ let targets
1135
+ if (Array.isArray(a.queue_ids) && a.queue_ids.length) {
1136
+ const own = new Set(rows.map((r) => r.id))
1137
+ const foreign = a.queue_ids.filter((id) => !own.has(id))
1138
+ if (foreign.length) return { result: "queue_id_not_for_item", foreign_queue_ids: foreign, queue: queueReport(rows, a.kind) }
1139
+ targets = rows.filter((r) => a.queue_ids.includes(r.id))
1140
+ } else {
1141
+ // Candidates only: removalVerdict below confirms a no-ETA partial against the progress memory.
1142
+ targets = rows.filter((r) => stallReason(r, now, undefined) !== null)
1143
+ }
1144
+ // A season pack is many queue rows sharing one downloadId; deleting one removes
1145
+ // the download for all, so delete once per download.
1146
+ const seen = new Set()
1147
+ targets = targets.filter((r) => {
1148
+ const key = r.downloadId ? `d:${r.downloadId}` : `q:${r.id}`
1149
+ if (seen.has(key)) return false
1150
+ seen.add(key)
1151
+ return true
1152
+ })
1153
+ // Removing a download deletes its progress. Unless the owner asked for this download to go,
1154
+ // only a download confirmed dead is removed: one still moving, or stalled without a second
1155
+ // observation 30 minutes apart, may yet finish (2026-10-05: a 75.9% pack, the only copy, was
1156
+ // deleted on "yes please get them").
1157
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
1158
+ if (ownerWords && !(Array.isArray(a.queue_ids) && a.queue_ids.length)) {
1159
+ 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) }
1160
+ }
1161
+ const kept = []
1162
+ if (!ownerWords) {
1163
+ targets = targets.filter((r) => {
1164
+ const verdict = removalVerdict(r, now, observeProgress(progressKey(r, a.kind), r.sizeleft ?? 0, now))
1165
+ if (verdict === "dead") return true
1166
+ kept.push({ queue_id: r.id, title: r.title ?? null, percent: pct(r), reason: verdict })
1167
+ return false
1168
+ })
1169
+ }
1170
+ if (!targets.length && kept.length) {
1171
+ return { result: "kept_downloads", kept, queue: queueReport(rows, a.kind),
1172
+ 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." }
1173
+ }
1174
+ if (!targets.length) return { result: "nothing_to_blocklist", queue: queueReport(rows, a.kind) }
1175
+ const removed = []
1176
+ const failed = []
1177
+ for (const row of targets) {
1178
+ try {
1179
+ await arrFor(a.kind)(`/queue/${row.id}`, { method: "DELETE", query: { removeFromClient: true, blocklist: true, skipRedownload: true } })
1180
+ removed.push(row.id)
1181
+ } catch (e) {
1182
+ // 404: the row went away (finished or removed with its pack); not a failure to retry.
1183
+ if (/_http_404$/.test(e.code ?? "")) removed.push(row.id)
1184
+ else failed.push({ queue_id: row.id, error: e.message })
1185
+ }
1186
+ }
1187
+ const command = a.research === false ? null : await runSearch(a.kind, serviceId)
1188
+ return { removed, ...(failed.length ? { failed } : {}), ...(kept.length ? { kept } : {}), ...(ownerWords ? { removed_on_owner_words: ownerWords } : {}), command, queue: queueReport(await itemQueue(a.kind, serviceId), a.kind) }
1189
+ }
1190
+
1191
+ // ------------------------------- tools: episodes / releases / blocklist / import
1192
+
1193
+ // When an automatic search finds nothing, the Butler works the release by hand:
1194
+ // list the episodes, read what the indexers offer and how Sonarr parsed it, grab
1195
+ // the right one with an explicit episode mapping, and map downloaded files by title.
1196
+ // All scoped to series/movies already in the library; nothing here adds one.
1197
+
1198
+ const kindOk = (a) => a.kind === "series" || a.kind === "movie"
1199
+ const invalidKind = () => ({ result: "invalid_kind", message: "kind must be 'series' or 'movie'." })
1200
+ const idKeyOf = (kind) => (kind === "series" ? "seriesId" : "movieId")
1201
+ const code2 = (n) => String(n).padStart(2, "0")
1202
+ const sxe = (e) => `S${code2(e.seasonNumber)}E${code2(e.episodeNumber)}`
1203
+
1204
+ async function seriesEpisodes(seriesId, seasonNumber) {
1205
+ const list = await sonarr("/episode", { query: { seriesId, seasonNumber } })
1206
+ return Array.isArray(list) ? list : []
1207
+ }
1208
+
1209
+ export async function mediaEpisodes(a) {
1210
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1211
+ const seriesId = Number(a.service_id)
1212
+ const eps = await seriesEpisodes(seriesId, a.season_number)
1213
+ return {
1214
+ series_id: seriesId,
1215
+ season_number: a.season_number ?? null,
1216
+ count: eps.length,
1217
+ episodes: eps.map((e) => ({ episode_id: e.id, code: sxe(e), season: e.seasonNumber, episode: e.episodeNumber, title: e.title ?? null,
1218
+ air_date: e.airDate ?? null, has_file: Boolean(e.hasFile), monitored: Boolean(e.monitored),
1219
+ // Release names follow scene (often streaming) numbering; Sonarr's own mapping, when it has one.
1220
+ scene_code: Number.isInteger(e.sceneSeasonNumber) && Number.isInteger(e.sceneEpisodeNumber)
1221
+ ? `S${String(e.sceneSeasonNumber).padStart(2, "0")}E${String(e.sceneEpisodeNumber).padStart(2, "0")}` : null })),
1222
+ }
1223
+ }
1224
+
1225
+ // Season and episode monitoring: what Sonarr searches for on its own. A season's flag lives on the series;
1226
+ // its episodes carry their own flags, so both are set to match.
1227
+ export async function mediaMonitor(a) {
1228
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1229
+ const seasons = Array.isArray(a.season_numbers) ? a.season_numbers.map(Number) : []
1230
+ const picked = Array.isArray(a.episode_ids) ? a.episode_ids.map(Number) : []
1231
+ if (!seasons.length && !picked.length) return { result: "seasons_or_episodes_required" }
1232
+ if (typeof a.monitored !== "boolean") return { result: "monitored_required" }
1233
+ const seriesId = Number(a.service_id)
1234
+ const episodeIds = [...picked]
1235
+ if (seasons.length) {
1236
+ const series = await sonarr(`/series/${seriesId}`)
1237
+ const has = (series.seasons ?? []).map((x) => x.seasonNumber)
1238
+ const unknown = seasons.filter((n) => !has.includes(n))
1239
+ if (unknown.length) return { result: "unknown_season", series_id: seriesId, seasons: unknown, has }
1240
+ await sonarr(`/series/${seriesId}`, { method: "PUT", body: { ...series, seasons: series.seasons.map((x) => seasons.includes(x.seasonNumber) ? { ...x, monitored: a.monitored } : x) } })
1241
+ for (const e of await seriesEpisodes(seriesId)) if (seasons.includes(e.seasonNumber) && !episodeIds.includes(e.id)) episodeIds.push(e.id)
1242
+ }
1243
+ if (episodeIds.length) await sonarr("/episode/monitor", { method: "PUT", body: { episodeIds, monitored: a.monitored } })
1244
+ const searched = []
1245
+ if (a.search && a.monitored) {
1246
+ for (const seasonNumber of seasons) {
1247
+ await sonarr("/command", { method: "POST", body: { name: "SeasonSearch", seriesId, seasonNumber } })
1248
+ searched.push(`season ${seasonNumber}`)
1249
+ }
1250
+ if (picked.length) {
1251
+ await sonarr("/command", { method: "POST", body: { name: "EpisodeSearch", episodeIds: picked } })
1252
+ searched.push(`episodes ${picked.join(", ")}`)
1253
+ }
1254
+ }
1255
+ return { result: "monitoring_changed", series_id: seriesId, monitored: a.monitored, seasons, episode_ids: episodeIds, searched }
1256
+ }
1257
+
1258
+ const WATCH_STATES = ["all", "played", "in_progress"]
1259
+ const jellyfin = (path, opts = {}) => req(JELLYFIN.url, path, { key: JELLYFIN.apiKey, header: "X-Emby-Token", ...opts })
1260
+
1261
+ // One Jellyfin user's watched and half-watched items, newest first.
1262
+ export async function mediaWatchHistory(a) {
1263
+ if (!JELLYFIN.url || !JELLYFIN.apiKey) return { result: "jellyfin_not_configured" }
1264
+ const state = a.state ?? "all"
1265
+ if (!WATCH_STATES.includes(state)) return { result: "bad_state", states: WATCH_STATES }
1266
+ const users = (await jellyfin("/Users")) ?? []
1267
+ const names = users.map((u) => u.Name)
1268
+ if (!a.user) return { result: "user_required", users: names }
1269
+ const wanted = String(a.user).toLowerCase()
1270
+ const user = users.find((u) => u.Id === a.user || String(u.Name).toLowerCase() === wanted)
1271
+ if (!user) return { result: "unknown_user", users: names }
1272
+ const filters = state === "all" ? ["IsResumable", "IsPlayed"] : [state === "played" ? "IsPlayed" : "IsResumable"]
1273
+ const pages = await Promise.all(filters.map((Filters) => jellyfin(`/Users/${user.Id}/Items`, { query: {
1274
+ Filters, Recursive: true, IncludeItemTypes: "Episode,Movie", Fields: "UserData", SortBy: "DatePlayed", SortOrder: "Descending", Limit: 500 } })))
1275
+ const title = a.title ? normalizeTitle(String(a.title)) : null
1276
+ const items = pages.flatMap((page) => page?.Items ?? [])
1277
+ .filter((i) => !title || [i.Name, i.SeriesName].some((n) => n && normalizeTitle(n).includes(title)))
1278
+ .map((i) => {
1279
+ const d = i.UserData ?? {}
1280
+ const episode = i.Type === "Episode"
1281
+ return { kind: episode ? "episode" : "movie", title: i.Name, series: i.SeriesName ?? null,
1282
+ code: episode && Number.isInteger(i.ParentIndexNumber) && Number.isInteger(i.IndexNumber) ? sxe({ seasonNumber: i.ParentIndexNumber, episodeNumber: i.IndexNumber }) : null,
1283
+ played: Boolean(d.Played), percent: d.Played ? 100 : Math.round(d.PlayedPercentage ?? 0), play_count: d.PlayCount ?? 0, last_played: d.LastPlayedDate ?? null }
1284
+ })
1285
+ .sort((x, y) => String(y.last_played ?? "").localeCompare(String(x.last_played ?? "")))
1286
+ .slice(0, Number(a.limit) > 0 ? Number(a.limit) : 50)
1287
+ return { result: "watch_history", user: user.Name, count: items.length, items }
1288
+ }
1289
+
1290
+ // Free-text search across every Prowlarr indexer: discovery only, it grabs nothing.
1291
+ // Sonarr's own search only asks for the season/episode codes it expects; this finds
1292
+ // what exists under any name (another numbering, a "Season 2 (2020)" pack, an episode title).
1293
+ export async function mediaIndexerSearch(a) {
1294
+ const query = typeof a.query === "string" ? a.query.trim() : ""
1295
+ if (!query) return { result: "query_required" }
1296
+ const raw = await prowlarr("/search", { query: { query, type: "search", limit: 100 }, timeoutMs: SEARCH_TIMEOUT_MS })
1297
+ const limit = Math.min(Math.max(Number(a.limit) || 25, 1), 50)
1298
+ const rows = (Array.isArray(raw) ? raw : [])
1299
+ .map((r) => ({ indexer: r.indexer ?? null, title: r.title ?? null, size_bytes: r.size ?? null, seeders: r.seeders ?? null,
1300
+ age_days: r.age ?? null, protocol: r.protocol ?? null }))
1301
+ .sort((x, y) => (y.seeders ?? -1) - (x.seeders ?? -1))
1302
+ return { query, count: rows.length, releases: rows.slice(0, limit),
1303
+ 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." }
1304
+ }
1305
+
1306
+ // The last search's compact rows, keyed by kind + guid, so a grab can check what Sonarr parsed.
1307
+ // Sonarr/Radarr forget a search's releases after about 30 minutes; expire ours a little sooner.
1308
+ const releaseCache = new Map()
1309
+ const RELEASE_CACHE_TTL_MS = 25 * 60_000
1310
+ const RELEASE_CACHE_MAX = 500
1311
+ const MAX_EPISODE_SEARCHES = 6
1312
+
1313
+ function cacheRelease(key, row, nowMs = Date.now()) {
1314
+ for (const [k, v] of releaseCache) if (nowMs - v.at > RELEASE_CACHE_TTL_MS) releaseCache.delete(k)
1315
+ releaseCache.delete(key)
1316
+ releaseCache.set(key, { ...row, at: nowMs })
1317
+ while (releaseCache.size > RELEASE_CACHE_MAX) releaseCache.delete(releaseCache.keys().next().value)
1318
+ }
1319
+
1320
+ function releaseRow(kind, r) {
1321
+ const rejections = Array.isArray(r.rejections) ? r.rejections.map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) : []
1322
+ const row = {
1323
+ guid: r.guid, indexer_id: r.indexerId ?? null, indexer: r.indexer ?? null, title: r.title ?? null, size_bytes: r.size ?? null,
1324
+ seeders: r.seeders ?? null, age_days: r.age ?? null, quality: r.quality?.quality?.name ?? null, protocol: r.protocol ?? null,
1325
+ rejected: Boolean(r.rejected), rejections, blocklisted: rejections.some((x) => /blocklist/i.test(x)),
1326
+ }
1327
+ if (kind === "series") {
1328
+ return { ...row, full_season: Boolean(r.fullSeason), parsed_season: r.seasonNumber ?? null, parsed_episodes: r.episodeNumbers ?? [],
1329
+ mapped_episodes: (r.mappedEpisodeInfo ?? []).map((e) => ({ episode_id: e.id ?? null, code: sxe(e), title: e.title ?? null })),
1330
+ mapped_series_id: r.mappedSeriesId ?? null }
1331
+ }
1332
+ return { ...row, mapped_movie_id: r.mappedMovieId ?? null }
1333
+ }
1334
+
1335
+ export async function mediaReleaseSearch(a) {
1336
+ if (!kindOk(a)) return invalidKind()
1337
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1338
+ const serviceId = Number(a.service_id)
1339
+ let raw = []
1340
+ if (a.kind === "movie") {
1341
+ raw = await radarr("/release", { query: { movieId: serviceId }, timeoutMs: SEARCH_TIMEOUT_MS })
1342
+ } else if (Array.isArray(a.episode_ids) && a.episode_ids.length) {
1343
+ // Sonarr searches one episode per call.
1344
+ 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." }
1345
+ for (const id of a.episode_ids) raw.push(...await sonarr("/release", { query: { episodeId: id }, timeoutMs: SEARCH_TIMEOUT_MS }))
1346
+ } else if (a.season_number !== undefined && a.season_number !== null) {
1347
+ raw = await sonarr("/release", { query: { seriesId: serviceId, seasonNumber: a.season_number }, timeoutMs: SEARCH_TIMEOUT_MS })
1348
+ } else return { result: "season_number_or_episode_ids_required" }
1349
+ const seen = new Set()
1350
+ const unique = (Array.isArray(raw) ? raw : []).filter((r) => (seen.has(r.guid) ? false : seen.add(r.guid)))
1351
+ // Sonarr's override grab needs the release's own quality and languages objects back.
1352
+ const rawByGuid = new Map(unique.map((r) => [r.guid, r]))
1353
+ let rows = unique.map((r) => releaseRow(a.kind, r))
1354
+ const total = rows.length
1355
+ if (a.query) {
1356
+ const q = String(a.query).toLowerCase()
1357
+ rows = rows.filter((r) => (r.title ?? "").toLowerCase().includes(q))
1358
+ }
1359
+ rows.sort((x, y) => Number(y.seeders ?? 0) - Number(x.seeders ?? 0))
1360
+ const limit = Math.min(Math.max(Number(a.limit) || 40, 1), 100)
1361
+ for (const r of rows) {
1362
+ const source = rawByGuid.get(r.guid)
1363
+ cacheRelease(`${a.kind}:${r.guid}`, { ...r, service_id: serviceId, season_number: a.season_number ?? null,
1364
+ quality_raw: source?.quality ?? null, languages_raw: source?.languages ?? null })
1365
+ }
1366
+ return { kind: a.kind, service_id: serviceId, total_found: total, matched: rows.length, releases: rows.slice(0, limit) }
1367
+ }
1368
+
1369
+ export async function mediaReleaseGrab(a) {
1370
+ if (!kindOk(a)) return invalidKind()
1371
+ if (!a.guid || a.indexer_id === undefined || a.indexer_id === null) return { result: "guid_and_indexer_id_required" }
1372
+ const cached = releaseCache.get(`${a.kind}:${a.guid}`)
1373
+ if (!cached || Date.now() - cached.at > RELEASE_CACHE_TTL_MS) {
1374
+ return { result: "search_first", message: "Run media_release_search first; a release can only be grabbed from a recent search (within 25 minutes)." }
1375
+ }
1376
+ if (cached.indexer_id !== null && Number(a.indexer_id) !== Number(cached.indexer_id)) return { result: "indexer_mismatch", expected_indexer_id: cached.indexer_id }
1377
+ const body = { guid: a.guid, indexerId: Number(a.indexer_id) }
1378
+ const hasEpisodes = Array.isArray(a.episode_ids) && a.episode_ids.length > 0
1379
+ if (a.kind === "series") {
1380
+ if (!hasEpisodes) {
1381
+ // A pack Sonarr parsed as another season would be mapped to the wrong episodes.
1382
+ const target = a.season_number ?? cached.season_number
1383
+ if (cached.full_season && (target === undefined || target === null || Number(target) !== Number(cached.parsed_season))) {
1384
+ return { result: "season_pack_mismatch", parsed_season: cached.parsed_season, target_season: target ?? null, title: cached.title,
1385
+ 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." }
1386
+ }
1387
+ } else {
1388
+ if (a.series_id === undefined || a.series_id === null) return { result: "series_id_required_with_episode_ids" }
1389
+ const seriesId = Number(a.series_id)
1390
+ 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." }
1391
+ const own = new Set((await seriesEpisodes(seriesId)).map((e) => e.id))
1392
+ const foreign = a.episode_ids.filter((id) => !own.has(id))
1393
+ if (foreign.length) return { result: "episode_id_not_for_series", foreign_episode_ids: foreign }
1394
+ // Sonarr v4 refuses an override without quality and languages (ArgumentNullException, HTTP 500).
1395
+ if (!cached.quality_raw) return { result: "release_quality_unknown", message: "Sonarr's search did not report this release's quality; search again." }
1396
+ Object.assign(body, { seriesId, episodeIds: a.episode_ids.map(Number), shouldOverride: true,
1397
+ quality: cached.quality_raw, languages: Array.isArray(cached.languages_raw) ? cached.languages_raw : [] })
1398
+ if (a.download_client_id !== undefined && a.download_client_id !== null) body.downloadClientId = Number(a.download_client_id)
1399
+ }
1400
+ }
1401
+ const res = await arrFor(a.kind)("/release", { method: "POST", body })
1402
+ return { result: "grabbed", kind: a.kind, title: cached.title, request: body,
1403
+ response: { approved: res?.approved ?? null, rejected: res?.rejected ?? null, rejections: res?.rejections ?? [], download_id: res?.downloadId ?? null } }
1404
+ }
1405
+
1406
+ const BLOCKLIST_PAGE_SIZE = 100
1407
+ const BLOCKLIST_MAX_PAGES = 20
1408
+
1409
+ async function itemBlocklist(kind, serviceId) {
1410
+ const idKey = idKeyOf(kind)
1411
+ const filter = kind === "series" ? { seriesIds: serviceId } : { movieIds: serviceId }
1412
+ const rows = []
1413
+ for (let page = 1; page <= BLOCKLIST_MAX_PAGES; page++) {
1414
+ const q = await arrFor(kind)("/blocklist", { query: { ...filter, page, pageSize: BLOCKLIST_PAGE_SIZE } })
1415
+ const records = q?.records ?? []
1416
+ rows.push(...records)
1417
+ if (!records.length || !(Number(q?.totalRecords) > page * BLOCKLIST_PAGE_SIZE)) return rows.filter((r) => r[idKey] === serviceId)
1418
+ }
1419
+ const own = rows.filter((r) => r[idKey] === serviceId)
1420
+ own.truncated = true
1421
+ return own
1422
+ }
1423
+
1424
+ const blocklistReport = (rows) => rows.map((r) => ({ blocklist_id: r.id, title: r.sourceTitle ?? null, date: r.date ?? null, indexer: r.indexer ?? null,
1425
+ quality: r.quality?.quality?.name ?? null, episode_ids: r.episodeIds ?? [], message: r.message ?? null }))
1426
+
1427
+ export async function mediaBlocklist(a) {
1428
+ if (!kindOk(a)) return invalidKind()
1429
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1430
+ const serviceId = Number(a.service_id)
1431
+ const rows = await itemBlocklist(a.kind, serviceId)
1432
+ if (!Array.isArray(a.remove_ids) || !a.remove_ids.length) {
1433
+ return { kind: a.kind, service_id: serviceId, count: rows.length, ...(rows.truncated ? { truncated: true } : {}), entries: blocklistReport(rows) }
1434
+ }
1435
+ const own = new Set(rows.map((r) => r.id))
1436
+ const foreign = a.remove_ids.filter((id) => !own.has(id))
1437
+ if (foreign.length) return { result: "blocklist_id_not_for_item", foreign_blocklist_ids: foreign, entries: blocklistReport(rows) }
1438
+ await arrFor(a.kind)("/blocklist/bulk", { method: "DELETE", body: { ids: a.remove_ids.map(Number) } })
1439
+ const left = await itemBlocklist(a.kind, serviceId)
1440
+ return { result: "removed", removed: a.remove_ids, count: left.length, entries: blocklistReport(left) }
1441
+ }
1442
+
1443
+ async function previewRows(seriesId, downloadId) {
1444
+ const rows = await sonarr("/manualimport", { query: { downloadId, seriesId, filterExistingFiles: false } })
1445
+ return Array.isArray(rows) ? rows : []
1446
+ }
1447
+
1448
+ const previewReport = (rows) => rows.map((r) => ({ path: r.path, name: r.name ?? null, parsed_season: r.seasonNumber ?? null,
1449
+ mapped_episodes: (r.episodes ?? []).map((e) => ({ episode_id: e.id ?? null, code: sxe(e), title: e.title ?? null })),
1450
+ quality: r.quality?.quality?.name ?? null, rejections: (r.rejections ?? []).map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) }))
1451
+
1452
+ export async function mediaManualImport(a) {
1453
+ if (a.service_id === undefined || a.service_id === null) return { result: "service_id_required" }
1454
+ if (!a.download_id) return { result: "download_id_required" }
1455
+ const seriesId = Number(a.service_id)
1456
+ const rows = await previewRows(seriesId, a.download_id)
1457
+ if (a.mode !== "import") return { mode: "preview", series_id: seriesId, download_id: a.download_id, files: previewReport(rows) }
1458
+ if (!Array.isArray(a.files) || !a.files.length || a.files.some((f) => !f || typeof f.path !== "string")) return { result: "files_required" }
1459
+ const paths = a.files.map((f) => f.path)
1460
+ if (new Set(paths).size !== paths.length) return { result: "duplicate_path" }
1461
+ const byPath = new Map(rows.map((r) => [r.path, r]))
1462
+ const unknown = a.files.filter((f) => !byPath.has(f.path)).map((f) => f.path)
1463
+ if (unknown.length) return { result: "path_not_in_preview", paths: unknown, files: previewReport(rows) }
1464
+ const seriesEps = await seriesEpisodes(seriesId)
1465
+ const own = new Set(seriesEps.map((e) => e.id))
1466
+ const foreign = a.files.flatMap((f) => (f.episode_ids ?? []).filter((id) => !own.has(id)))
1467
+ if (foreign.length) return { result: "episode_id_not_for_series", foreign_episode_ids: foreign }
1468
+ const empty = a.files.filter((f) => !Array.isArray(f.episode_ids) || !f.episode_ids.length).map((f) => f.path)
1469
+ if (empty.length) return { result: "episode_ids_required", paths: empty }
1470
+ const targets = a.files.flatMap((f) => f.episode_ids.map(Number))
1471
+ if (new Set(targets).size !== targets.length) return { result: "episode_id_on_two_files" }
1472
+ const files = a.files.map((f) => {
1473
+ const r = byPath.get(f.path)
1474
+ return { path: f.path, seriesId, episodeIds: f.episode_ids.map(Number), quality: r.quality, languages: r.languages, releaseGroup: r.releaseGroup ?? "",
1475
+ indexerFlags: r.indexerFlags ?? 0, releaseType: r.releaseType ?? "unknown", downloadId: a.download_id }
1476
+ })
1477
+ const c = await sonarr("/command", { method: "POST", body: { name: "ManualImport", files, importMode: "auto" } })
1478
+ // Episodes that already had a file: Sonarr treats these imports as replacements.
1479
+ const replacing = seriesEps.filter((e) => e.hasFile && targets.includes(e.id)).map((e) => ({ episode_id: e.id, code: sxe(e) }))
1480
+ 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 } }
1481
+ }
1482
+
1483
+ // ------------------------------------------------------- tool: fill missing
1484
+ //
1485
+ // The whole "get the missing episodes" job as one deterministic pass, so a long
1486
+ // request no longer depends on the model chaining a dozen calls correctly
1487
+ // (2026-10-03: The Chef Show took an owner hint, a wrong pack, an invented
1488
+ // parameter and the step cap). Each call re-reads Sonarr, so it is safe to call
1489
+ // again: in-flight grabs are never repeated, and once nothing is missing it says
1490
+ // stop. Release names follow streaming numbering, so a release is matched to
1491
+ // episodes only on evidence: an episode title, a season plus the air year, or a
1492
+ // Sonarr parse whose own numbering agrees with the episode's TVDB or scene code.
1493
+
1494
+ const FILL_MAX_GRABS = 3
1495
+ const FILL_DEADLINE_MS = 150_000
1496
+ const FILL_RECENT_GRAB_MS = 15 * 60_000
1497
+ const FILL_EVIDENCE_ROWS = 5
1498
+ // A torrent with no ETA is called stalled only after its remaining size has not moved for this long.
1499
+ const FILL_STALL_CONFIRM_MS = 30 * 60_000
1500
+
1501
+ // Years in a release name, ignoring resolutions such as 1920x1080 and 2160p.
1502
+ const yearsIn = (title) => new Set((String(title ?? "").match(/(?<![0-9x])(?:19|20)[0-9]{2}(?![0-9px])/gi) ?? []).map(Number))
1503
+ const airYear = (e) => (e.airDate ? Number(String(e.airDate).slice(0, 4)) : null)
1504
+ const hasWord = (haystack, needle) => needle.length > 0 && ` ${haystack} `.includes(` ${needle} `)
1505
+ const rejectionTexts = (r) => (Array.isArray(r.rejections) ? r.rejections.map((x) => (typeof x === "string" ? x : x?.reason ?? String(x))) : [])
1506
+ // "Doctor Who (2005)" and "The Office (US)" are named without the suffix in most releases.
1507
+ export const seriesBaseTitle = (title) => normalizeTitle(String(title ?? "").replace(/\s*\((?:19|20)[0-9]{2}\)\s*$/, "").replace(/\s*\((?:us|uk|au|nz|ca)\)\s*$/i, ""))
1508
+
1509
+ // An episode title is evidence only when it is distinctive enough not to appear by chance:
1510
+ // several words, or one long word that is not a generic release term.
1511
+ const GENERIC_TITLE_WORDS = new Set(["special", "specials", "episode", "finale", "premiere", "extended", "complete", "unknown", "untitled", "trailer", "preview", "bonus"])
1512
+ function episodeTitleIn(releaseNorm, episode) {
1513
+ const t = normalizeTitle(episode.title)
1514
+ const distinctive = t.includes(" ") ? t.length >= 6 : t.length >= 7 && !GENERIC_TITLE_WORDS.has(t) && !/^[0-9]+$/.test(t)
1515
+ return distinctive && hasWord(releaseNorm, t)
1516
+ }
1517
+
1518
+ // Season named in a release title: "Season 2", "Temporada 2", "S02" (not "S02E01").
1519
+ export function seasonInTitle(title) {
1520
+ const s = String(title ?? "")
1521
+ const word = s.match(/\b(?:season|temporada|saison|staffel)\s*0*([0-9]{1,2})\b/i)
1522
+ if (word) return Number(word[1])
1523
+ const code = s.match(/\bS0*([0-9]{1,2})(?![0-9]|\s*E[0-9])\b/i)
1524
+ return code ? Number(code[1]) : null
1525
+ }
1526
+
1527
+ // Sonarr's mapping is trusted only when the numbering in the name is the episode's own or scene code.
1528
+ function parseAgrees(release, episode) {
1529
+ const season = release.seasonNumber
1530
+ const numbers = Array.isArray(release.episodeNumbers) ? release.episodeNumbers : []
1531
+ const codes = [[episode.seasonNumber, episode.episodeNumber], [episode.sceneSeasonNumber, episode.sceneEpisodeNumber]]
1532
+ return codes.some(([s, e]) => Number.isInteger(s) && s === season && (numbers.length ? numbers.includes(e) : Boolean(release.fullSeason)))
1533
+ }
1534
+
1535
+ // Which wanted episodes one release really holds, and on what evidence; or why it is unusable.
1536
+ // A blocklisted release is still rejected, but says which wanted episodes it would hold, so a
1537
+ // release blocklisted by mistake can be offered back to the owner.
1538
+ export function matchReleaseToEpisodes(release, ctx) {
1539
+ const rejections = rejectionTexts(release)
1540
+ if (!rejections.some((x) => /blocklist/i.test(x))) return matchUnblocked(release, ctx, rejections)
1541
+ const m = matchUnblocked(release, ctx, rejections.filter((x) => !/blocklist/i.test(x)))
1542
+ if (m.reject === "other_series") return m
1543
+ return { reject: "blocklisted", ...(m.episode_ids ? { would_match: { episode_ids: m.episode_ids, basis: m.basis } } : {}) }
1544
+ }
1545
+
1546
+ function matchUnblocked(release, { seriesId, seriesTitle, seriesYear, wanted, have }, rejections) {
1547
+ const title = release.title ?? ""
1548
+ const norm = normalizeTitle(title)
1549
+ const base = seriesBaseTitle(seriesTitle)
1550
+ if (!hasWord(norm, base)) return { reject: "other_series" }
1551
+ if (release.mappedSeriesId && seriesId && release.mappedSeriesId !== seriesId) return { reject: "other_series" }
1552
+ if (rejections.some((x) => /not wanted in profile|below .*minimum|custom format/i.test(x))) return { reject: "quality_not_wanted" }
1553
+ const wantedYears = new Set(wanted.map(airYear).filter(Boolean))
1554
+ // The series' own premiere year ("Show (2019) Season 2") says nothing about which season it is,
1555
+ // unless the missing episodes aired that year too.
1556
+ const years = new Set([...yearsIn(title)].filter((y) => y !== seriesYear || wantedYears.has(y)))
1557
+ if (years.size && ![...years].some((y) => wantedYears.has(y))) return { reject: "year_mismatch", years: [...years] }
1558
+ // Episode titles are looked for in the name with the series name taken out.
1559
+ const rest = ` ${norm} `.replace(` ${base} `, " ").trim()
1560
+ const byTitle = wanted.filter((e) => episodeTitleIn(rest, e))
1561
+ if (byTitle.length) return { episode_ids: byTitle.map((e) => e.id), basis: "episode_title" }
1562
+ if (have.some((e) => episodeTitleIn(rest, e))) return { reject: "holds_episodes_we_have" }
1563
+ const wantedById = new Map(wanted.map((e) => [e.id, e]))
1564
+ const mapped = (release.mappedEpisodeInfo ?? []).map((e) => e.id).filter((id) => id !== undefined && id !== null)
1565
+ const mappedWanted = mapped.filter((id) => wantedById.has(id))
1566
+ if (mappedWanted.length) {
1567
+ if (mappedWanted.every((id) => parseAgrees(release, wantedById.get(id)))) return { episode_ids: mappedWanted, basis: "sonarr_parse" }
1568
+ return { reject: "parse_disagrees_with_numbering" }
1569
+ }
1570
+ // A season pack named with the season and the air year of the missing episodes
1571
+ // ("The Chef Show [Season 2] (2020)"), whatever Sonarr's scene mapping says it holds.
1572
+ const season = seasonInTitle(title) ?? (release.fullSeason ? release.seasonNumber ?? null : null)
1573
+ if (season !== null && years.size && !/\bE[0-9]{1,3}\b/i.test(title)) {
1574
+ const covered = wanted.filter((e) => e.seasonNumber === season && years.has(airYear(e)))
1575
+ if (covered.length) return { episode_ids: covered.map((e) => e.id), basis: "season_and_air_year" }
1576
+ }
1577
+ return { reject: mapped.length ? "holds_episodes_we_have" : "no_episode_match" }
1578
+ }
1579
+
1580
+ // Why a download is not going to finish on its own, or null while it may still be moving.
1581
+ // `confirmed` is false when the only sign is a missing ETA not yet seen to persist; such a
1582
+ // download is reported but never replaced.
1583
+ export function stallReason(row, nowMs, previous) {
1584
+ const left = row.sizeleft ?? 0
1585
+ const noEta = row.timeleft === undefined || row.timeleft === null || row.timeleft === "00:00:00"
1586
+ const unchangedFor30 = Boolean(previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS)
1587
+ if (isStalledRow(row, nowMs)) {
1588
+ if (left >= (row.size ?? 0)) return { stall: "never_started", confirmed: true }
1589
+ // Old and unfinished is not dead by age alone: a slow torrent with a real ETA is still moving.
1590
+ return noEta || unchangedFor30 ? { stall: "unfinished_for_days", confirmed: true } : null
1591
+ }
1592
+ const ageHours = row.added ? (nowMs - Date.parse(row.added)) / 3_600_000 : 0
1593
+ const moving = row.status === "downloading" || row.status === "warning"
1594
+ if (!(moving && left > 0 && noEta && ageHours >= STALL_AFTER_HOURS)) return null
1595
+ const unchanged = previous && previous.sizeleft === left && nowMs - previous.at >= FILL_STALL_CONFIRM_MS
1596
+ return { stall: "no_peers", confirmed: Boolean(unchanged) }
1597
+ }
1598
+
1599
+ // Remaining size per download, as first seen at that size, so a later call can tell stopped from slow.
1600
+ // Kept on disk: every Butler restart starts a new MCP process, and an observation lost with it
1601
+ // would leave a dead download unconfirmable (or make a fresh one look confirmed too early).
1602
+ const PROGRESS_FORGET_MS = 14 * 24 * 3_600_000
1603
+ // Observations further apart than this are not continuous: the download may have been paused
1604
+ // and resumed in between, so the older one stops counting.
1605
+ const PROGRESS_CONTINUITY_MS = 6 * 3_600_000
1606
+ const progressPath = () => process.env.SANCTUARY_MEDIA_STATE ?? "/home/ouro/AgentBundles/sanctuary.ouro/state/media/download-progress.json"
1607
+ let progressSeen = null
1608
+ function readProgressFile() {
1609
+ const out = new Map()
1610
+ try {
1611
+ for (const [k, v] of Object.entries(JSON.parse(readFileSync(progressPath(), "utf8")))) {
1612
+ 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 })
1613
+ }
1614
+ } catch { /* first run, or unreadable: start empty */ }
1615
+ return out
1616
+ }
1617
+ function loadProgress() {
1618
+ if (!progressSeen) progressSeen = readProgressFile()
1619
+ return progressSeen
1620
+ }
1621
+ // Merge with what another process (an overlapping restart) may have saved, keeping the
1622
+ // later sighting per download, then replace the file atomically so a crash cannot truncate it.
1623
+ function saveProgress(nowMs) {
1624
+ try {
1625
+ for (const [k, v] of readProgressFile()) {
1626
+ const mine = progressSeen.get(k)
1627
+ if (nowMs - v.seen <= PROGRESS_FORGET_MS && (!mine || v.seen > mine.seen)) progressSeen.set(k, v)
1628
+ }
1629
+ mkdirSync(dirname(progressPath()), { recursive: true, mode: 0o700 })
1630
+ const tmp = `${progressPath()}.tmp-${process.pid}`
1631
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(progressSeen)), { mode: 0o600 })
1632
+ renameSync(tmp, progressPath())
1633
+ } catch (e) {
1634
+ // Best effort: confirmation then waits for a later observation in this process.
1635
+ process.stderr.write(`media-mcp: download progress not saved: ${e.message}\n`)
1636
+ }
1637
+ }
1638
+ // Read-only look at the memory: what observeProgress would return, without recording a sighting.
1639
+ function peekProgress(key, sizeleft, nowMs) {
1640
+ const previous = loadProgress().get(key)
1641
+ return previous && nowMs - previous.seen <= PROGRESS_CONTINUITY_MS ? previous : undefined
1642
+ }
1643
+ export const progressKey = (row, kind = "series") => `${kind}:${row.downloadId ?? `row:${row.id}`}`.toUpperCase()
1644
+ function observeProgress(downloadId, sizeleft, nowMs) {
1645
+ const seen = loadProgress()
1646
+ for (const [k, v] of seen) if (nowMs - v.seen > PROGRESS_FORGET_MS) seen.delete(k)
1647
+ let previous = seen.get(downloadId)
1648
+ if (previous && nowMs - previous.seen > PROGRESS_CONTINUITY_MS) previous = undefined
1649
+ if (!previous || previous.sizeleft !== sizeleft) seen.set(downloadId, { sizeleft, at: nowMs, seen: nowMs })
1650
+ else seen.set(downloadId, { ...previous, seen: nowMs })
1651
+ saveProgress(nowMs)
1652
+ return previous
1653
+ }
1654
+
1655
+ const importDone = (row) => (row.sizeleft ?? 0) === 0 || row.status === "completed"
1656
+ const importNeeded = (row) => importDone(row) && ["importPending", "importBlocked", "importFailed"].includes(row.trackedDownloadState)
1657
+
1658
+ async function seriesGrabHistory(seriesId) {
1659
+ const list = await sonarr("/history/series", { query: { seriesId, eventType: "grabbed" } })
1660
+ return Array.isArray(list) ? list : []
1661
+ }
1662
+
1663
+ async function runningImportFor(downloadId) {
1664
+ const list = await sonarr("/command")
1665
+ return (Array.isArray(list) ? list : []).some((c) => c.name === "ManualImport" && ["queued", "started"].includes(c.status)
1666
+ && (c.body?.files ?? []).some((f) => String(f.downloadId ?? "").toUpperCase() === String(downloadId).toUpperCase()))
1667
+ }
1668
+
1669
+ // Map a finished download's files to the wanted episodes by title. Only a file whose name
1670
+ // holds exactly one wanted episode title, and the only file holding it, is imported.
1671
+ async function importByTitle(seriesId, seriesTitle, downloadId, wantedEps) {
1672
+ if (await runningImportFor(downloadId)) return { action: "import_already_running", download_id: downloadId }
1673
+ const rows = await previewRows(seriesId, downloadId)
1674
+ const base = seriesBaseTitle(seriesTitle)
1675
+ const picks = []
1676
+ const unmatched = []
1677
+ for (const r of rows) {
1678
+ const rest = ` ${normalizeTitle(`${r.name ?? ""} ${r.relativePath ?? ""}`)} `.replace(` ${base} `, " ").trim()
1679
+ const ids = wantedEps.filter((e) => episodeTitleIn(rest, e)).map((e) => e.id)
1680
+ if (ids.length === 1) picks.push({ row: r, ids })
1681
+ else unmatched.push(r.name ?? r.path)
1682
+ }
1683
+ const counts = new Map()
1684
+ for (const p of picks) counts.set(p.ids[0], (counts.get(p.ids[0]) ?? 0) + 1)
1685
+ const unique = picks.filter((p) => counts.get(p.ids[0]) === 1)
1686
+ for (const p of picks) if (!unique.includes(p)) unmatched.push(p.row.name ?? p.row.path)
1687
+ if (!unique.length) {
1688
+ return { action: "import_needs_mapping", download_id: downloadId, unmatched_files: unmatched,
1689
+ note: "No file names an episode title. Map them with media_manual_import (preview, then import by title from media_episodes)." }
1690
+ }
1691
+ const files = unique.map(({ row: r, ids }) => ({ path: r.path, seriesId, episodeIds: ids, quality: r.quality, languages: r.languages, releaseGroup: r.releaseGroup ?? "",
1692
+ indexerFlags: r.indexerFlags ?? 0, releaseType: r.releaseType ?? "unknown", downloadId }))
1693
+ const c = await sonarr("/command", { method: "POST", body: { name: "ManualImport", files, importMode: "auto" } })
1694
+ return { action: "imported_by_title", download_id: downloadId, command_id: c?.id ?? null,
1695
+ files: unique.map(({ row: r, ids }) => ({ file: r.name ?? r.path, episode_ids: ids })), ...(unmatched.length ? { unmatched_files: unmatched } : {}) }
1696
+ }
1697
+
1698
+ const pct = (row) => ((row.size ?? 0) > 0 ? Math.round((((row.size ?? 0) - (row.sizeleft ?? 0)) / row.size) * 1000) / 10 : null)
1699
+ const fillRunning = new Set()
1700
+ // When each season or episode of a series was last searched, so repeat calls reach the ones a deadline cut off.
1701
+ const lastSearched = new Map()
1702
+ const FILL_ACTION_GRACE_MS = 45_000
1703
+
1704
+ export async function mediaFillMissing(a, opts = {}) {
1705
+ const found = await resolveLibraryItem({ kind: "series", service_id: a.service_id, title: a.series })
1706
+ if (!found.item) return { result: found.result, candidates: found.candidates, message: "Name the series by its Sonarr service_id or exact title." }
1707
+ const seriesId = found.item.id
1708
+ // One pass per series at a time: a retry after a timeout must not grab beside a pass still running.
1709
+ if (fillRunning.has(seriesId)) return { result: "already_running", series_id: seriesId, message: "A media_fill_missing pass for this series is still working. Wait a minute and call again; do not act by hand." }
1710
+ fillRunning.add(seriesId)
1711
+ try {
1712
+ return await fillPass(a, seriesId, found.item.title, opts)
1713
+ } finally {
1714
+ fillRunning.delete(seriesId)
1715
+ }
1716
+ }
1717
+
1718
+ async function fillPass(a, seriesId, seriesTitle, { nowMs = Date.now(), deadlineMs = FILL_DEADLINE_MS } = {}) {
1719
+ const startedAt = Date.now()
1720
+ const remainingMs = () => deadlineMs - (Date.now() - startedAt)
1721
+ const timeLeft = () => remainingMs() > 0
1722
+ // Grabs and imports may run a little past the search deadline, never past the harness timeout.
1723
+ const mayAct = () => remainingMs() > -FILL_ACTION_GRACE_MS
1724
+ const errors = []
1725
+ // Each step after the first reads is isolated: one failure is reported, the rest of the pass and its record survive.
1726
+ const attempt = async (step, fn) => {
1727
+ try { return await fn() } catch (e) { errors.push({ step, error: e.code ?? "failed", message: e.message }); return undefined }
1728
+ }
1729
+ const seriesYear = Number((await attempt("read series", () => sonarr(`/series/${seriesId}`)))?.year) || null
1730
+ const season = a.season_number === undefined || a.season_number === null ? null : Number(a.season_number)
1731
+ const scope = (await seriesEpisodes(seriesId, season ?? undefined)).filter((e) => (season === null ? e.seasonNumber > 0 : true))
1732
+ const aired = (e) => Boolean(e.airDateUtc ?? e.airDate) && Date.parse(e.airDateUtc ?? e.airDate) <= nowMs
1733
+ const missing = scope.filter((e) => !e.hasFile && aired(e))
1734
+ const wanted = missing.filter((e) => e.monitored)
1735
+ const have = scope.filter((e) => e.hasFile)
1736
+ const code = (e) => ({ episode_id: e.id, code: sxe(e), title: e.title ?? null, air_date: e.airDate ?? null })
1737
+ const base = { series_id: seriesId, series: seriesTitle, season_number: season, checked_at: new Date(nowMs).toISOString(),
1738
+ on_shelf: { count: have.length, of: scope.filter(aired).length },
1739
+ ...(missing.length > wanted.length ? { not_monitored_missing: missing.filter((e) => !e.monitored).map(code) } : {}) }
1740
+ if (!wanted.length) {
1741
+ return { ...base, goal_met: true, in_flight: [], not_found: [], actions: [],
1742
+ summary: `Nothing monitored is missing: ${have.length} of ${base.on_shelf.of} aired episodes are on the shelf.`,
1743
+ next_step: "Goal met. Stop here and tell the owner; do not search or grab anything else." }
1744
+ }
1745
+
1746
+ const actions = []
1747
+ const byId = new Map(wanted.map((e) => [e.id, e]))
1748
+ const queue = await itemQueue("series", seriesId)
1749
+ const history = await seriesGrabHistory(seriesId)
1750
+ const grabbedFor = new Map()
1751
+ for (const h of history) {
1752
+ // A client without download ids (e.g. a blackhole) is tracked by release title instead.
1753
+ const key = h.downloadId ? String(h.downloadId).toUpperCase() : h.sourceTitle ? `TITLE:${normalizeTitle(h.sourceTitle)}` : null
1754
+ if (!key) continue
1755
+ if (!grabbedFor.has(key)) grabbedFor.set(key, { ids: new Set(), date: h.date, title: h.sourceTitle })
1756
+ grabbedFor.get(key).ids.add(h.episodeId)
1757
+ }
1758
+ // Sonarr re-parses a tracked download's name, so its queue rows can point at the
1759
+ // wrong episodes; the grab history keeps the mapping the grab was made with.
1760
+ const downloads = new Map()
1761
+ for (const r of queue) {
1762
+ const key = String(r.downloadId ?? `row:${r.id}`).toUpperCase()
1763
+ if (!downloads.has(key)) downloads.set(key, { key, row: r, ids: new Set(grabbedFor.get(key)?.ids ?? []) })
1764
+ if (!grabbedFor.has(key)) downloads.get(key).ids.add(r.episodeId)
1765
+ }
1766
+ const queuedTitles = new Set(queue.map((r) => normalizeTitle(r.title)))
1767
+ for (const [key, g] of grabbedFor) {
1768
+ const recent = nowMs - Date.parse(g.date) < FILL_RECENT_GRAB_MS
1769
+ if (recent && !downloads.has(key) && !queuedTitles.has(normalizeTitle(g.title))) downloads.set(key, { key, row: null, ids: g.ids, title: g.title })
1770
+ }
1771
+
1772
+ let cutShort = false
1773
+ const covered = new Set()
1774
+ const stalled = []
1775
+ const inFlight = []
1776
+ for (const d of downloads.values()) {
1777
+ const ids = wanted.map((e) => e.id).filter((id) => d.ids.has(id))
1778
+ if (!ids.length) continue
1779
+ const entry = { title: d.row?.title ?? d.title ?? null, download_id: d.row?.downloadId ?? d.key, episodes: ids.map((id) => sxe(byId.get(id))) }
1780
+ if (!d.row) { inFlight.push({ ...entry, state: "just_grabbed" }); ids.forEach((id) => covered.add(id)); continue }
1781
+ if (importNeeded(d.row)) {
1782
+ const done = mayAct() ? await attempt(`import ${d.row.downloadId}`, () => importByTitle(seriesId, seriesTitle, d.row.downloadId, ids.map((id) => byId.get(id)))) : undefined
1783
+ if (done) actions.push(done)
1784
+ inFlight.push({ ...entry, state: done?.action === "import_needs_mapping" ? "downloaded_needs_mapping" : done ? "importing" : mayAct() ? "downloaded_import_failed" : "downloaded_import_next_call" })
1785
+ if (!done) cutShort = true
1786
+ ids.forEach((id) => covered.add(id))
1787
+ continue
1788
+ }
1789
+ const why = stallReason(d.row, nowMs, observeProgress(progressKey(d.row), d.row.sizeleft ?? 0, nowMs))
1790
+ const info = { ...entry, percent: pct(d.row), queue_id: d.row.id, added: d.row.added ?? null }
1791
+ if (why) stalled.push({ ...info, ids, ...why })
1792
+ else { inFlight.push({ ...info, state: importDone(d.row) ? "importing" : "downloading" }); ids.forEach((id) => covered.add(id)) }
1793
+ }
1794
+
1795
+ // Search for everything not covered by a moving download, stalled ones included.
1796
+ const need = wanted.filter((e) => !covered.has(e.id))
1797
+ const searched = []
1798
+ const searchedSeasons = new Set()
1799
+ const searchedEpisodes = new Set()
1800
+ const candidates = new Map()
1801
+ const rejected = new Map()
1802
+ const blockedMatches = new Map()
1803
+ const inFlightTitles = new Set([...downloads.values()].map((d) => normalizeTitle(d.row?.title ?? d.title)).filter(Boolean))
1804
+ const consider = (raw) => {
1805
+ for (const r of Array.isArray(raw) ? raw : []) {
1806
+ if (!r?.guid || candidates.has(r.guid) || rejected.has(r.guid)) continue
1807
+ const m = matchReleaseToEpisodes(r, { seriesId, seriesTitle, seriesYear, wanted: need, have })
1808
+ const sameAsInFlight = inFlightTitles.has(normalizeTitle(r.title))
1809
+ if (m.would_match && !sameAsInFlight) blockedMatches.set(r.guid, { raw: r, ids: m.would_match.episode_ids, basis: m.would_match.basis })
1810
+ 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 }
1811
+ cacheRelease(`series:${r.guid}`, { ...releaseRow("series", r), service_id: seriesId, season_number: null, quality_raw: r.quality ?? null, languages_raw: r.languages ?? null })
1812
+ candidates.set(r.guid, { raw: r, ids: m.episode_ids, basis: m.basis })
1813
+ }
1814
+ }
1815
+ const searchTimeout = () => Math.max(5_000, Math.min(SEARCH_TIMEOUT_MS, remainingMs()))
1816
+ const hasSeededCandidate = (e) => [...candidates.values()].some((c) => (c.raw.seeders ?? 0) > 0 && c.ids.includes(e.id))
1817
+ const searchedAt = (key) => lastSearched.get(`${seriesId}:${key}`) ?? 0
1818
+ const markSearched = (key) => lastSearched.set(`${seriesId}:${key}`, Date.now())
1819
+ // Least recently searched first, so a deadline never starves the same seasons on every call.
1820
+ const seasons = [...new Set(need.map((e) => e.seasonNumber))].sort((x, y) => searchedAt(`s${x}`) - searchedAt(`s${y}`) || x - y)
1821
+ for (const s of seasons) {
1822
+ if (!timeLeft()) break
1823
+ searchedSeasons.add(s)
1824
+ markSearched(`s${s}`)
1825
+ searched.push(`Sonarr season search S${code2(s)}`)
1826
+ consider(await attempt(`season search S${code2(s)}`, () => sonarr("/release", { query: { seriesId, seasonNumber: s }, timeoutMs: searchTimeout() })))
1827
+ }
1828
+ const episodeOrder = need.filter((x) => !hasSeededCandidate(x)).sort((x, y) => searchedAt(`e${x.id}`) - searchedAt(`e${y.id}`))
1829
+ for (const e of episodeOrder.slice(0, MAX_EPISODE_SEARCHES)) {
1830
+ if (!timeLeft()) break
1831
+ searchedEpisodes.add(e.id)
1832
+ markSearched(`e${e.id}`)
1833
+ searched.push(`Sonarr episode search ${sxe(e)}`)
1834
+ consider(await attempt(`episode search ${sxe(e)}`, () => sonarr("/release", { query: { episodeId: e.id }, timeoutMs: searchTimeout() })))
1835
+ }
1836
+
1837
+ // Episodes whose only matching releases are on the blocklist. With the owner's words such a
1838
+ // release joins the candidates and its blocklist entry is lifted only once it is actually being
1839
+ // grabbed (an unseeded one then waits for peers and is kept); without, it is reported.
1840
+ const covers = (id) => [...candidates.values()].some((c) => c.ids.includes(id))
1841
+ const blockedOnly = [...blockedMatches.values()].filter((b) => b.ids.some((id) => !covers(id)))
1842
+ const ownerRetry = typeof a.retry_blocklisted === "string" ? a.retry_blocklisted.trim() : ""
1843
+ const blockedLeft = new Map()
1844
+ if (blockedOnly.length) {
1845
+ const entries = (await attempt("read blocklist", () => itemBlocklist("series", seriesId))) ?? []
1846
+ for (const b of blockedOnly) {
1847
+ const ids = entries.filter((x) => normalizeTitle(x.sourceTitle) === normalizeTitle(b.raw.title)).map((x) => x.id)
1848
+ blockedLeft.set(b.raw.guid, { b, blocklist_ids: ids })
1849
+ if (ownerRetry && ids.length) {
1850
+ 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 })
1851
+ candidates.set(b.raw.guid, { ...b, blocklistIds: ids })
1852
+ }
1853
+ }
1854
+ }
1855
+ const lifted = new Set()
1856
+ const liftFor = async (c) => {
1857
+ const ids = c.blocklistIds.filter((id) => !lifted.has(id))
1858
+ if (ids.length && !(await attempt("remove from blocklist", async () => { await sonarr("/blocklist/bulk", { method: "DELETE", body: { ids } }); return true }))) return false
1859
+ ids.forEach((id) => lifted.add(id))
1860
+ if (ids.length) actions.push({ action: "removed_from_blocklist", title: c.raw.title ?? null, owner_words: ownerRetry })
1861
+ return true
1862
+ }
1863
+
1864
+ // Seeded releases first, then the ones that cover the most, then the best seeded.
1865
+ const ranked = [...candidates.values()].sort((x, y) =>
1866
+ 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))
1867
+ const remaining = new Set(need.map((e) => e.id))
1868
+ const stalledIds = new Set(stalled.flatMap((s) => s.ids))
1869
+ // Until a stall is confirmed on a later call, its episodes are not fetched a second time.
1870
+ const unconfirmedIds = new Set(stalled.filter((s) => !s.confirmed).flatMap((s) => s.ids))
1871
+ for (const s of stalled.filter((x) => !x.confirmed)) {
1872
+ s.alternative = ranked.some((c) => (c.raw.seeders ?? 0) > 0 && s.ids.every((id) => c.ids.includes(id)))
1873
+ }
1874
+ const deferred = new Set()
1875
+ let grabs = 0
1876
+ for (const c of ranked) {
1877
+ const seeded = (c.raw.seeders ?? 0) > 0
1878
+ // An unseeded release is no better than a stalled download: never fetch those episodes twice that way.
1879
+ const ids = c.ids.filter((id) => remaining.has(id) && !unconfirmedIds.has(id) && (seeded || !stalledIds.has(id)))
1880
+ if (!ids.length || !c.raw.quality) continue
1881
+ if (grabs >= FILL_MAX_GRABS || !mayAct()) { ids.forEach((id) => deferred.add(id)); cutShort ||= !mayAct(); continue }
1882
+ 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 : [] }
1883
+ const post = async () => (await sonarr("/release", { method: "POST", body })) ?? {}
1884
+ let res
1885
+ if (c.blocklistIds) {
1886
+ // Grab first; lift the entry after it succeeds, or before one retry if Sonarr refused it as blocklisted.
1887
+ try { res = await post() } catch { res = undefined }
1888
+ const liftedOk = await liftFor(c)
1889
+ if (!res && liftedOk) res = await attempt(`grab ${c.raw.title}`, post)
1890
+ if (!res) continue
1891
+ blockedLeft.delete(c.raw.guid)
1892
+ for (const [g, x] of blockedLeft) if (normalizeTitle(x.b.raw.title) === normalizeTitle(c.raw.title)) blockedLeft.delete(g)
1893
+ } else {
1894
+ res = await attempt(`grab ${c.raw.title}`, post)
1895
+ }
1896
+ if (!res) continue
1897
+ grabs += 1
1898
+ ids.forEach((id) => remaining.delete(id))
1899
+ actions.push({ action: "grabbed", title: c.raw.title ?? null, indexer: c.raw.indexer ?? null, seeders: c.raw.seeders ?? null, matched_by: c.basis,
1900
+ episodes: ids.map((id) => sxe(byId.get(id))), download_id: res.downloadId ?? null, ...(seeded ? {} : { may_never_finish: true }) })
1901
+ inFlight.push({ title: c.raw.title ?? null, download_id: res.downloadId ?? null, episodes: ids.map((id) => sxe(byId.get(id))), state: "just_grabbed" })
1902
+ // Only after the replacement is grabbed, and only for a confirmed stall it fully covers with a seeded release.
1903
+ if (!seeded) continue
1904
+ for (const s of stalled.filter((x) => !x.replaced && x.confirmed && x.ids.every((id) => ids.includes(id)))) {
1905
+ 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 })
1906
+ if (!removed) continue
1907
+ s.replaced = true
1908
+ actions.push({ action: "blocklisted_stalled", title: s.title, percent: s.percent, stall: s.stall })
1909
+ }
1910
+ }
1911
+ for (const s of stalled.filter((x) => !x.replaced)) {
1912
+ const alsoGrabbed = s.ids.every((id) => !remaining.has(id))
1913
+ 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,
1914
+ ...(s.confirmed ? {} : { stall_confirmed: false }),
1915
+ 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)."
1916
+ : alsoGrabbed ? "Releases for some of these episodes were grabbed; this download was kept for the rest."
1917
+ : "No other usable release was found, so this download was kept in case peers return." })
1918
+ s.ids.forEach((id) => remaining.delete(id))
1919
+ }
1920
+
1921
+ const open = need.filter((e) => remaining.has(e.id) && !deferred.has(e.id))
1922
+ const unsearched = open.filter((e) => !searchedSeasons.has(e.seasonNumber) && !searchedEpisodes.has(e.id))
1923
+ const notFound = open.filter((e) => !unsearched.includes(e)).map(code)
1924
+ const stuck = inFlight.filter((x) => x.state === "stalled")
1925
+ let evidence
1926
+ if ((notFound.length || stuck.length) && timeLeft()) {
1927
+ // What exists on the indexers under any name, so a "can't find it" is backed by a listing. Best effort.
1928
+ evidence = []
1929
+ const target = notFound.length ? need.filter((e) => notFound.some((n) => n.episode_id === e.id)) : wanted
1930
+ const ys = [...new Set(target.map((e) => e.airDate?.slice(0, 4)).filter(Boolean))].slice(0, 2)
1931
+ const scene = [...new Set(target.map((e) => e.sceneSeasonNumber).filter((n) => Number.isInteger(n)))].slice(0, 1)
1932
+ const queries = [...(ys.length ? ys : [""]).map((y) => `${seriesTitle} ${y}`.trim()), ...scene.map((n) => `${seriesTitle} S${code2(n)}`)]
1933
+ for (const q of queries) {
1934
+ if (!timeLeft()) break
1935
+ const raw = await attempt(`indexer evidence "${q}"`, () => prowlarr("/search", { query: { query: q, type: "search", limit: 100 }, timeoutMs: searchTimeout() }))
1936
+ if (!Array.isArray(raw)) continue
1937
+ // Indexers answer free text loosely ("Vegas Chef Prizefight"); keep only releases named for this series.
1938
+ const own = raw.filter((r) => hasWord(normalizeTitle(r.title), seriesBaseTitle(seriesTitle)))
1939
+ const rows = own.sort((x, y) => (y.seeders ?? -1) - (x.seeders ?? -1)).slice(0, FILL_EVIDENCE_ROWS)
1940
+ evidence.push({ query: q, results: own.length, top: rows.map((r) => ({ title: r.title ?? null, seeders: r.seeders ?? null, indexer: r.indexer ?? null })) })
1941
+ }
1942
+ }
1943
+ const blockedReport = []
1944
+ for (const { b, blocklist_ids } of blockedLeft.values()) {
1945
+ if (blockedReport.some((x) => normalizeTitle(x.title) === normalizeTitle(b.raw.title))) continue
1946
+ blockedReport.push({ title: b.raw.title ?? null, seeders: b.raw.seeders ?? null, episodes: b.ids.map((id) => sxe(byId.get(id))), blocklist_ids })
1947
+ }
1948
+ const incomplete = cutShort || deferred.size > 0 || unsearched.length > 0 || !timeLeft() || errors.length > 0
1949
+ const moving = inFlight.filter((x) => x.state !== "stalled").length
1950
+ const unseeded = actions.filter((x) => x.action === "grabbed" && x.may_never_finish)
1951
+ const summary = [
1952
+ `${have.length} of ${base.on_shelf.of} aired episodes are on the shelf; ${wanted.length} monitored ${wanted.length === 1 ? "episode is" : "episodes are"} missing.`,
1953
+ grabs ? `Grabbed ${grabs} release${grabs === 1 ? "" : "s"} now.` : "",
1954
+ 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 never finish.` : "",
1955
+ moving ? `${moving} download(s) in progress.` : "",
1956
+ stuck.length ? `${stuck.length} download(s) stalled with no peers and no other usable release (${stuck.map((s) => `${s.title} at ${s.percent}%`).join("; ")}).` : "",
1957
+ notFound.length ? `No usable release found for ${notFound.map((e) => e.code).join(", ")}.` : "",
1958
+ 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("; ")}.` : "",
1959
+ deferred.size || unsearched.length ? `${deferred.size + unsearched.length} episode(s) not handled yet in this pass.` : "",
1960
+ errors.length ? `${errors.length} step(s) failed: ${errors.map((x) => x.step).join("; ")}.` : "",
1961
+ ].filter(Boolean).join(" ")
1962
+ const nextStep = incomplete
1963
+ ? "This pass did not finish everything. Tell the owner what it did, then call media_fill_missing again to continue; do not act by hand."
1964
+ : stuck.length || notFound.length
1965
+ ? "Tell the owner exactly this outcome with the evidence; do not grab, import or blocklist anything by hand. Call media_fill_missing again later to retry."
1966
+ : unseeded.length
1967
+ ? "Tell the owner what was grabbed and that it has no seeders, so it may never finish. File a follow-up with await_condition to call media_fill_missing again later. Do not search or grab anything else now."
1968
+ : "Work is in progress. Tell the owner what is downloading; call media_fill_missing again later to import and confirm. Do not search or grab anything else now."
1969
+ const blockedHint = !blockedReport.length ? ""
1970
+ : ownerRetry ? " The owner's retry could not take the blocklisted release back (see errors and blocklisted_matches); tell the owner that plainly."
1971
+ : " The only matching release is on the blocklist: tell the owner, and if the owner then asks to get it anyway, call media_fill_missing again with retry_blocklisted set to the owner's own words. Do not remove blocklist entries or grab by hand."
1972
+ return { ...base, goal_met: false, in_flight: inFlight, not_found: notFound, actions,
1973
+ ...(deferred.size ? { deferred: need.filter((e) => deferred.has(e.id)).map(code) } : {}), ...(unsearched.length ? { unsearched: unsearched.map(code) } : {}),
1974
+ searched, ...(blockedReport.length ? { blocklisted_matches: blockedReport } : {}), ...(rejected.size ? { rejected_releases: [...rejected.values()].slice(0, 12) } : {}), ...(evidence ? { indexer_evidence: evidence } : {}),
1975
+ ...(errors.length ? { errors } : {}), ...(incomplete ? { incomplete: true } : {}), summary, next_step: nextStep + blockedHint }
1976
+ }
1977
+
1978
+ // ------------------------------------------------- tool: quality profiles
1979
+
1980
+ // Radarr and Sonarr keep the upgrade rules (whether a better release may replace a file, and the quality at which they
1981
+ // stop) in a quality profile. The Butler once told the owner this was "config-screen-only"; it is an ordinary API, so it
1982
+ // is a typed tool: read profiles, set cutoff and upgradeAllowed, and put a movie or series on a profile. Writes are a
1983
+ // dry run unless dry_run is false, and return before, after and applied_at like media_diagnose_and_fix.
1984
+
1985
+ const itemQualityId = (i) => i.quality?.id ?? i.id
1986
+ const itemQualityName = (i) => i.quality?.name ?? i.name
1987
+
1988
+ function profileView(p) {
1989
+ const items = p.items ?? []
1990
+ const cutoffItem = items.find((i) => itemQualityId(i) === p.cutoff)
1991
+ return { id: p.id, name: p.name, upgrade_allowed: Boolean(p.upgradeAllowed), cutoff: p.cutoff ?? null,
1992
+ cutoff_name: cutoffItem ? itemQualityName(cutoffItem) : null,
1993
+ qualities: items.map((i) => ({ id: itemQualityId(i), name: itemQualityName(i), allowed: Boolean(i.allowed), ...(i.items?.length ? { group: true } : {}) })) }
1994
+ }
1995
+
1996
+ 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." })
1997
+ const isHttp404 = (e) => /_http_404$/.test(e?.code ?? "")
1998
+
1999
+ async function getProfile(kind, id) {
2000
+ try { return await arrFor(kind)(`/qualityprofile/${id}`) } catch (e) { if (isHttp404(e)) return null; throw e }
2001
+ }
2002
+
2003
+ async function getItem(kind, serviceId) {
2004
+ try { return await arrFor(kind)(`/${kind === "series" ? "series" : "movie"}/${serviceId}`) } catch (e) { if (isHttp404(e)) return null; throw e }
2005
+ }
2006
+
2007
+ // One line per applied change: what changed, the owner's words that asked for it, who called, and when.
2008
+ const qualityAuditPath = () => process.env.SANCTUARY_MEDIA_AUDIT ?? "/home/ouro/AgentBundles/sanctuary.ouro/state/media/quality-profile-audit.ndjson"
2009
+ function auditQualityChange(entry) {
2010
+ try {
2011
+ mkdirSync(dirname(qualityAuditPath()), { recursive: true })
2012
+ appendFileSync(qualityAuditPath(), `${JSON.stringify(entry)}\n`)
2013
+ return null
2014
+ } catch (e) { return `${e.code ?? e.message}` }
2015
+ }
2016
+ const titlesUsing = async (kind, profileId) => (await arrFor(kind)(kind === "series" ? "/series" : "/movie")).filter((t) => t.qualityProfileId === profileId).length
2017
+ 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."
2018
+ const OWNER_WORDS_NOTE_AUDIT = "claimed by the caller; not verified"
2019
+ 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." }
2020
+
2021
+ const itemView = (item) => ({ service_id: item.id, title: item.title ?? null, quality_profile_id: item.qualityProfileId ?? null })
2022
+ 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; do not ask the owner to open a settings page."
2023
+
2024
+ // Release profiles are the apps' own rules for which releases to take: a release whose title holds an ignored term is never
2025
+ // grabbed, and one missing a required term is skipped. Writes follow media_quality_profile: dry run first, owner_words to apply.
2026
+ const releaseProfileView = (p) => ({ id: p.id, name: p.name ?? null, enabled: p.enabled !== false,
2027
+ ignored: [].concat(p.ignored ?? []), required: [].concat(p.required ?? []) })
2028
+ const termList = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map((x) => String(x).trim()).filter(Boolean)
2029
+
2030
+ export async function mediaReleaseProfile(a) {
2031
+ if (!kindOk(a)) return invalidKind()
2032
+ const action = a.action ?? "read"
2033
+ const client = arrFor(a.kind)
2034
+ const profiles = await client("/releaseprofile")
2035
+ if (action === "read") return { kind: a.kind, result: "release_profiles", profiles: profiles.map(releaseProfileView) }
2036
+ if (action !== "set") return { result: "invalid_action", message: "action must be 'read' or 'set'." }
2037
+ const name = typeof a.name === "string" ? a.name.trim() : ""
2038
+ if (!name) return { result: "name_required", message: "Pass name: the release profile to create or change (matched case-insensitively)." }
2039
+ const ignored = termList(a.ignored)
2040
+ const required = termList(a.required)
2041
+ if (!ignored.length && !required.length && a.enabled === undefined) {
2042
+ return { result: "no_change_requested", message: "Pass ignored terms, required terms or enabled." }
2043
+ }
2044
+ const current = profiles.find((p) => String(p.name ?? "").toLowerCase() === name.toLowerCase())
2045
+ const before = current ? releaseProfileView(current) : null
2046
+ const next = { ...(current ?? { name, indexerId: 0, tags: [] }),
2047
+ enabled: a.enabled ?? current?.enabled ?? true,
2048
+ ignored: a.ignored !== undefined ? ignored : [].concat(current?.ignored ?? []),
2049
+ required: a.required !== undefined ? required : [].concat(current?.required ?? []) }
2050
+ const after = releaseProfileView({ ...next, id: current?.id ?? null })
2051
+ 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." }
2052
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
2053
+ if (!ownerWords) return OWNER_WORDS_REQUIRED
2054
+ const saved = current
2055
+ ? await client(`/releaseprofile/${current.id}`, { method: "PUT", body: next })
2056
+ : await client("/releaseprofile", { method: "POST", body: next })
2057
+ const failed = auditQualityChange({ at: new Date().toISOString(), tool: "media_release_profile", action, kind: a.kind, owner_words: ownerWords,
2058
+ owner_words_note: OWNER_WORDS_NOTE_AUDIT, caller: typeof a.caller === "string" ? a.caller : "unknown", before, after })
2059
+ return { kind: a.kind, result: current ? "updated" : "created", before, after: releaseProfileView({ ...next, ...(saved ?? {}) }),
2060
+ applied_at: new Date().toISOString(), owner_words_note: OWNER_WORDS_NOTE, ...(failed ? { audit_error: failed } : {}) }
2061
+ }
2062
+
2063
+ export async function mediaQualityProfile(a) {
2064
+ if (!kindOk(a)) return invalidKind()
2065
+ const action = a.action ?? "read"
2066
+ const dryRun = a.dry_run !== false
2067
+ const hasProfileId = a.profile_id !== undefined && a.profile_id !== null
2068
+ const hasServiceId = a.service_id !== undefined && a.service_id !== null
2069
+ const client = arrFor(a.kind)
2070
+ const ownerWords = typeof a.owner_words === "string" ? a.owner_words.trim() : ""
2071
+ if (!dryRun && action !== "read" && !ownerWords) return OWNER_WORDS_REQUIRED
2072
+ const audit = (entry) => {
2073
+ 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 })
2074
+ return failed ? { audit_error: failed, owner_words_note: OWNER_WORDS_NOTE } : { owner_words_note: OWNER_WORDS_NOTE }
2075
+ }
2076
+
2077
+ if (action === "read") {
2078
+ let profiles
2079
+ if (hasProfileId) {
2080
+ const one = await getProfile(a.kind, Number(a.profile_id))
2081
+ if (!one) return profileNotFound(Number(a.profile_id))
2082
+ profiles = [one]
2083
+ } else {
2084
+ profiles = await client("/qualityprofile")
2085
+ }
2086
+ const out = { kind: a.kind, result: "profiles", profiles: profiles.map(profileView) }
2087
+ if (hasServiceId) {
2088
+ const item = await getItem(a.kind, Number(a.service_id))
2089
+ if (!item) return { result: "no_such_item", kind: a.kind, service_id: Number(a.service_id) }
2090
+ out.item = itemView(item)
2091
+ }
2092
+ return out
2093
+ }
2094
+
2095
+ if (action === "set_upgrade") {
2096
+ if (!hasProfileId) return { result: "profile_id_required" }
2097
+ const wantsCutoff = a.cutoff !== undefined || a.cutoff_name !== undefined
2098
+ if (!wantsCutoff && a.upgrade_allowed === undefined) {
2099
+ return { result: "no_change_requested", message: "Pass upgrade_allowed and/or cutoff (a quality id) or cutoff_name." }
2100
+ }
2101
+ const current = await getProfile(a.kind, Number(a.profile_id))
2102
+ if (!current) return profileNotFound(Number(a.profile_id))
2103
+ const next = { ...current }
2104
+ if (wantsCutoff) {
2105
+ const wanted = (current.items ?? []).find((i) => (a.cutoff !== undefined ? itemQualityId(i) === Number(a.cutoff) : String(itemQualityName(i)).toLowerCase() === String(a.cutoff_name).toLowerCase()))
2106
+ if (!wanted) return { result: "cutoff_not_in_profile", profile_id: current.id, qualities: profileView(current).qualities }
2107
+ next.cutoff = itemQualityId(wanted)
2108
+ }
2109
+ if (a.upgrade_allowed !== undefined) next.upgradeAllowed = Boolean(a.upgrade_allowed)
2110
+ const before = profileView(current)
2111
+ const after = profileView(next)
2112
+ if (before.cutoff === after.cutoff && before.upgrade_allowed === after.upgrade_allowed) return { action, dry_run: dryRun, result: "unchanged", before, after: before }
2113
+ if (dryRun) {
2114
+ const shared = await titlesUsing(a.kind, current.id)
2115
+ return { action, dry_run: true, result: "would_apply", before, after, titles_using_profile: shared,
2116
+ 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.`,
2117
+ 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.` }
2118
+ }
2119
+ const saved = await client(`/qualityprofile/${current.id}`, { method: "PUT", body: next })
2120
+ const appliedAfter = profileView(saved ?? next)
2121
+ 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 }
2122
+ }
2123
+
2124
+ if (action === "assign") {
2125
+ if (!hasServiceId) return { result: "service_id_required" }
2126
+ if (!hasProfileId) return { result: "profile_id_required" }
2127
+ const item = await getItem(a.kind, Number(a.service_id))
2128
+ if (!item) return { result: "no_such_item", kind: a.kind, service_id: Number(a.service_id) }
2129
+ const profile = await getProfile(a.kind, Number(a.profile_id))
2130
+ if (!profile) return profileNotFound(Number(a.profile_id))
2131
+ const before = itemView(item)
2132
+ const after = itemView({ ...item, qualityProfileId: profile.id })
2133
+ if (before.quality_profile_id === profile.id) return { action, dry_run: dryRun, result: "unchanged", before, after: before }
2134
+ if (dryRun) {
2135
+ return { action, dry_run: true, result: "would_apply", before, after, profile: profileView(profile),
2136
+ would_do: `Put "${item.title ?? item.id}" on the "${profile.name}" profile. Call again with dry_run false to apply.` }
2137
+ }
2138
+ const saved = await client(`/${a.kind === "series" ? "series" : "movie"}/${item.id}`, { method: "PUT", body: { ...item, qualityProfileId: profile.id } })
2139
+ const assignedAfter = itemView(saved ?? { ...item, qualityProfileId: profile.id })
2140
+ return { action, dry_run: false, applied_at: new Date().toISOString(), result: "applied", before, after: assignedAfter,
2141
+ ...audit({ service_id: item.id, profile_id: profile.id, before, after: assignedAfter }), profile: profileView(profile), next_step: UPGRADE_NEXT_STEP }
2142
+ }
2143
+
2144
+ return { result: "invalid_action", message: "action must be read, set_upgrade or assign." }
2145
+ }
2146
+
2147
+ // ------------------------------------------------------------------- schema
2148
+
2149
+ // The harness waits 30 s for a tool call unless the tool declares longer; indexer searches can take minutes.
2150
+ const TIMEOUT_META_KEY = "ouro.bot/timeoutMs"
2151
+
2152
+ const TOOL_LIST = [
2153
+ {
2154
+ name: "media_search",
2155
+ annotations: { readOnlyHint: true },
2156
+ 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 does not exist, comes only from a lookup made this turn, never from memory or an earlier reply; never say a title does not exist without reading both. 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.",
2157
+ inputSchema: { type: "object", properties: {
2158
+ query: { type: "string", description: "Title or free text. Omit to browse by filters." },
2159
+ kind: { type: "string", enum: ["movie", "series", "any"], description: "Default any." },
2160
+ year_range: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "[minYear, maxYear]" },
2161
+ genres: { type: "array", items: { type: "string" }, description: "TMDB genre names, e.g. ['Romance','Drama']." },
2162
+ keywords: { type: "array", items: { type: "string" }, description: "TMDB keywords, e.g. ['autumn','small town']. Best lever for mood/vibe requests." },
2163
+ on_shelf: { type: "boolean", description: "true = only what we already have; false = only what we do not; omit = both." },
2164
+ limit: { type: "number", description: "1-20, default 12." },
2165
+ sort: { type: "string", enum: ["relevance", "release_year"] },
2166
+ } },
2167
+ },
2168
+ {
2169
+ name: "media_request",
2170
+ 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, never a duplicate. Returns the downstream sonarr_id/radarr_id so media_request_status needs no re-resolution. Someone asking is the request: call this and say what happened. Never send anyone to Jellyseerr or another screen to ask for it themselves.",
2171
+ inputSchema: { type: "object", properties: {
2172
+ tmdb_id: { type: "number" },
2173
+ title: { type: "string" },
2174
+ year: { type: "number" },
2175
+ kind: { type: "string", enum: ["movie", "series"] },
2176
+ season_number: { type: "number", description: "Series only. Omit to request all seasons." },
2177
+ } },
2178
+ },
2179
+ {
2180
+ name: "media_request_status",
2181
+ annotations: { readOnlyHint: true },
2182
+ 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. Never infer the cause yourself — read diagnosis.summary.",
2183
+ inputSchema: { type: "object", properties: {
2184
+ request_id: { type: "string", description: "e.g. jellyseerr:42" },
2185
+ tmdb_id: { type: "number" },
2186
+ title: { type: "string" },
2187
+ } },
2188
+ },
2189
+ {
2190
+ name: "media_diagnose_and_fix",
2191
+ 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.",
2192
+ inputSchema: { type: "object", properties: {
2193
+ request_id: { type: "string" }, tmdb_id: { type: "number" }, title: { type: "string" },
2194
+ action: { type: "string", enum: ["rescan", "enable_monitoring", "force_import_scan", "blocklist_and_research", "report_only"] },
2195
+ dry_run: { type: "boolean" },
2196
+ } },
2197
+ },
2198
+ {
2199
+ name: "media_chain_health",
2200
+ annotations: { readOnlyHint: true },
2201
+ 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.",
2202
+ inputSchema: { type: "object", properties: {} },
2203
+ },
2204
+ {
2205
+ name: "media_play_or_resolve",
2206
+ 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.",
2207
+ inputSchema: { type: "object", properties: {
2208
+ request_id: { type: "string" }, tmdb_id: { type: "number" }, title: { type: "string" },
2209
+ } },
2210
+ },
2211
+ {
2212
+ name: "media_queue",
2213
+ 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'.",
2214
+ inputSchema: { type: "object", properties: {
2215
+ kind: { type: "string", enum: ["series", "movie"] },
2216
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2217
+ tmdb_id: { type: "number" },
2218
+ title: { type: "string", description: "Exact or near-exact library title." },
2219
+ }, required: ["kind"] },
2220
+ },
2221
+ {
2222
+ name: "media_search_now",
2223
+ description: "Trigger a Sonarr/Radarr search for a series or movie that is already in the library, and report its queue. Use this whenever something already in Sonarr/Radarr needs a search, re-search or another look; no Jellyseerr request id is needed. Identify it by service_id, tmdb_id, or exact title. Never adds anything new: zero or several matches come back as 'not_found' or 'ambiguous' with candidates. Never tell anyone to click Search in the web UI.",
2224
+ inputSchema: { type: "object", properties: {
2225
+ kind: { type: "string", enum: ["series", "movie"] },
2226
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2227
+ title: { type: "string" },
2228
+ tmdb_id: { type: "number" },
2229
+ }, required: ["kind"] },
2230
+ },
2231
+ {
2232
+ name: "media_blocklist_stalled",
2233
+ 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.",
2234
+ inputSchema: { type: "object", properties: {
2235
+ kind: { type: "string", enum: ["series", "movie"] },
2236
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id (media_search_now returns it)." },
2237
+ queue_ids: { type: "array", items: { type: "number" } },
2238
+ research: { type: "boolean", description: "Search again afterwards. Default true." },
2239
+ 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'." },
2240
+ }, required: ["kind", "service_id"] },
2241
+ },
2242
+ {
2243
+ name: "media_fill_missing",
2244
+ _meta: { [TIMEOUT_META_KEY]: 240_000 },
2245
+ description: "Get a series' missing episodes, start to finish, in one call. Use this first whenever someone asks why episodes are missing or asks to get them. It re-reads Sonarr, finds the monitored aired episodes without files, searches the indexers, matches releases to episodes by episode title and air year as well as Sonarr's parse (so streaming-volume numbering cannot fool it), prefers seeded releases, skips packs of episodes already on the shelf, grabs with the right episode mapping, imports finished downloads by title, and replaces a stalled download when a usable alternative exists. Returns on_shelf, in_flight, not_found, actions, indexer_evidence, summary and next_step. Safe to call again: it never grabs what is already in flight. When goal_met is true, stop. Relay summary and follow next_step as they are; do not redo its steps by hand. Never offer to clear, cancel or blocklist a stalled download it chose to keep; it replaces that download itself once a seeded alternative exists. Until goal_met is true, call it again whenever next_step leaves more to do. When blocklisted_matches comes back, call again with retry_blocklisted set to the asker's words for those episodes and get them.",
2246
+ inputSchema: { type: "object", properties: {
2247
+ series: { type: "string", description: "Series title as the owner said it." },
2248
+ service_id: { type: "number", description: "Sonarr series id, when known." },
2249
+ season_number: { type: "number", description: "Limit to one season. Omit for the whole series (specials excluded)." },
2250
+ 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." },
2251
+ } },
2252
+ },
2253
+ {
2254
+ name: "media_episodes",
2255
+ annotations: { readOnlyHint: true },
2256
+ 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.",
2257
+ inputSchema: { type: "object", properties: {
2258
+ service_id: { type: "number", description: "Sonarr series id." },
2259
+ season_number: { type: "number" },
2260
+ }, required: ["service_id"] },
2261
+ },
2262
+ {
2263
+ name: "media_monitor",
2264
+ annotations: { readOnlyHint: false },
2265
+ 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.",
2266
+ inputSchema: { type: "object", properties: {
2267
+ service_id: { type: "number", description: "Sonarr series id." },
2268
+ season_numbers: { type: "array", items: { type: "number" } },
2269
+ episode_ids: { type: "array", items: { type: "number" } },
2270
+ monitored: { type: "boolean" },
2271
+ search: { type: "boolean" },
2272
+ }, required: ["service_id", "monitored"] },
2273
+ },
2274
+ {
2275
+ name: "media_watch_history",
2276
+ annotations: { readOnlyHint: true },
2277
+ 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).",
2278
+ inputSchema: { type: "object", properties: {
2279
+ user: { type: "string", description: "Jellyfin user name or id." },
2280
+ title: { type: "string" },
2281
+ state: { type: "string", enum: WATCH_STATES },
2282
+ limit: { type: "number" },
2283
+ }, required: [] },
2284
+ },
2285
+ {
2286
+ name: "media_indexer_search",
2287
+ annotations: { readOnlyHint: true },
2288
+ _meta: { [TIMEOUT_META_KEY]: 200_000 },
2289
+ 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.",
2290
+ inputSchema: { type: "object", properties: {
2291
+ query: { type: "string" },
2292
+ limit: { type: "number", description: "1-50, default 25." },
2293
+ }, required: ["query"] },
2294
+ },
2295
+ {
2296
+ name: "media_release_search",
2297
+ annotations: { readOnlyHint: true },
2298
+ _meta: { [TIMEOUT_META_KEY]: 240_000 },
2299
+ 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.",
2300
+ inputSchema: { type: "object", properties: {
2301
+ kind: { type: "string", enum: ["series", "movie"] },
2302
+ service_id: { type: "number", description: "Sonarr series id or Radarr movie id." },
2303
+ season_number: { type: "number" },
2304
+ episode_ids: { type: "array", items: { type: "number" } },
2305
+ query: { type: "string", description: "Case-insensitive text the release title must contain." },
2306
+ limit: { type: "number", description: "1-100, default 40." },
2307
+ }, required: ["kind", "service_id"] },
2308
+ },
2309
+ {
2310
+ name: "media_release_grab",
2311
+ 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.",
2312
+ inputSchema: { type: "object", properties: {
2313
+ kind: { type: "string", enum: ["series", "movie"] },
2314
+ guid: { type: "string" },
2315
+ indexer_id: { type: "number" },
2316
+ series_id: { type: "number", description: "Required with episode_ids." },
2317
+ episode_ids: { type: "array", items: { type: "number" }, description: "Episodes this release really holds." },
2318
+ season_number: { type: "number", description: "Target season, checked against a season pack's parsed season when episode_ids is omitted." },
2319
+ download_client_id: { type: "number" },
2320
+ }, required: ["kind", "guid", "indexer_id"] },
2321
+ },
2322
+ {
2323
+ name: "media_blocklist",
2324
+ 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.",
2325
+ inputSchema: { type: "object", properties: {
2326
+ kind: { type: "string", enum: ["series", "movie"] },
2327
+ service_id: { type: "number" },
2328
+ remove_ids: { type: "array", items: { type: "number" } },
2329
+ }, required: ["kind", "service_id"] },
2330
+ },
2331
+ {
2332
+ name: "media_quality_profile",
2333
+ 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'). This is a normal API, never a settings screen the owner has 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.",
2334
+ inputSchema: { type: "object", properties: {
2335
+ kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
2336
+ action: { type: "string", enum: ["read", "set_upgrade", "assign"], description: "Default read." },
2337
+ profile_id: { type: "number", description: "Quality profile id (from action read)." },
2338
+ service_id: { type: "number", description: "Radarr movie id or Sonarr series id (media_search returns it)." },
2339
+ upgrade_allowed: { type: "boolean", description: "set_upgrade: whether a better release may replace the file." },
2340
+ cutoff: { type: "number", description: "set_upgrade: quality id from the profile at which upgrades stop." },
2341
+ cutoff_name: { type: "string", description: "set_upgrade: the same, by quality name (for example Bluray-1080p)." },
2342
+ dry_run: { type: "boolean", description: "Writes only. Default true: report before and after without changing anything. Pass false to apply." },
2343
+ 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." },
2344
+ caller: { type: "string", description: "Filled in by the runtime for the audit line; leave it out." },
2345
+ }, required: ["kind"] },
2346
+ },
2347
+ {
2348
+ name: "media_release_profile",
2349
+ 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 is never grabbed; one missing a required term is skipped. Use it for household rules such as never taking 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.",
2350
+ inputSchema: { type: "object", properties: {
2351
+ kind: { type: "string", enum: ["movie", "series"], description: "movie = Radarr, series = Sonarr." },
2352
+ action: { type: "string", enum: ["read", "set"], description: "Default read." },
2353
+ name: { type: "string", description: "set: the release profile's name; an existing one is changed, otherwise it is created." },
2354
+ ignored: { type: "array", items: { type: "string" }, description: "set: terms or /regex/ that a release title must not contain." },
2355
+ required: { type: "array", items: { type: "string" }, description: "set: terms or /regex/ that a release title must contain." },
2356
+ enabled: { type: "boolean", description: "set: whether the profile is in force. Default: unchanged, or true for a new one." },
2357
+ dry_run: { type: "boolean", description: "Default true: report before and after without changing anything. Pass false to apply." },
2358
+ owner_words: { type: "string", description: "Required to apply: the owner's exact words asking for this change." },
2359
+ caller: { type: "string", description: "Filled in by the runtime for the audit line; leave it out." },
2360
+ }, required: ["kind"] },
2361
+ },
2362
+ {
2363
+ name: "media_manual_import",
2364
+ 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.",
2365
+ inputSchema: { type: "object", properties: {
2366
+ mode: { type: "string", enum: ["preview", "import"], description: "Default preview." },
2367
+ service_id: { type: "number", description: "Sonarr series id." },
2368
+ download_id: { type: "string", description: "Download client id of the completed download (queue row downloadId)." },
2369
+ files: { type: "array", items: { type: "object", properties: { path: { type: "string" }, episode_ids: { type: "array", items: { type: "number" } } }, required: ["path", "episode_ids"] } },
2370
+ }, required: ["service_id", "download_id"] },
2371
+ },
2372
+ ]
2373
+
2374
+ // Every schema is closed: an argument the tool does not define (an invented dry_run,
2375
+ // a misspelled id) is refused with its name, never silently ignored.
2376
+ function closeSchema(schema) {
2377
+ if (!schema || typeof schema !== "object" || schema.type !== "object") return schema
2378
+ const properties = Object.fromEntries(Object.entries(schema.properties ?? {}).map(([k, v]) => [k, v?.type === "array" && v.items ? { ...v, items: closeSchema(v.items) } : closeSchema(v)]))
2379
+ return { ...schema, properties, additionalProperties: false }
2380
+ }
2381
+
2382
+ export const TOOLS = TOOL_LIST.map((t) => ({ ...t, inputSchema: closeSchema(t.inputSchema) }))
2383
+
2384
+ // The same check inside the server, for any caller that does not validate against the schema.
2385
+ export function unknownArguments(toolName, args) {
2386
+ const tool = TOOLS.find((t) => t.name === toolName)
2387
+ const allowed = Object.keys(tool?.inputSchema?.properties ?? {})
2388
+ const unknown = Object.keys(args ?? {}).filter((k) => !allowed.includes(k))
2389
+ return unknown.length ? { error: "unknown_parameter", unknown, allowed,
2390
+ 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
2391
+ }
2392
+
2393
+ const HANDLERS = {
2394
+ media_search: mediaSearch,
2395
+ media_request: mediaRequest,
2396
+ media_request_status: mediaRequestStatus,
2397
+ media_diagnose_and_fix: mediaDiagnoseAndFix,
2398
+ media_chain_health: mediaChainHealth,
2399
+ media_play_or_resolve: mediaPlayOrResolve,
2400
+ media_search_now: mediaSearchNow,
2401
+ media_queue: mediaQueue,
2402
+ media_blocklist_stalled: mediaBlocklistStalled,
2403
+ media_episodes: mediaEpisodes,
2404
+ media_monitor: mediaMonitor,
2405
+ media_watch_history: mediaWatchHistory,
2406
+ media_fill_missing: mediaFillMissing,
2407
+ media_indexer_search: mediaIndexerSearch,
2408
+ media_release_search: mediaReleaseSearch,
2409
+ media_release_grab: mediaReleaseGrab,
2410
+ media_blocklist: mediaBlocklist,
2411
+ media_manual_import: mediaManualImport,
2412
+ media_quality_profile: mediaQualityProfile,
2413
+ media_release_profile: mediaReleaseProfile,
2414
+ }
2415
+
2416
+ // ------------------------------------------------------------ jsonrpc stdio
2417
+
2418
+ function send(msg) { process.stdout.write(JSON.stringify(msg) + "\n") }
2419
+
2420
+ async function handle(msg) {
2421
+ const { id, method, params } = msg
2422
+ if (method === "initialize") {
2423
+ return send({ jsonrpc: "2.0", id, result: {
2424
+ protocolVersion: "2024-11-05",
2425
+ capabilities: { tools: {} },
2426
+ serverInfo: { name: "sanctuary-media", version: "1.0.0" },
2427
+ } })
2428
+ }
2429
+ if (method === "initialized" || method === "notifications/initialized") return
2430
+ if (method === "tools/list") return send({ jsonrpc: "2.0", id, result: { tools: TOOLS } })
2431
+ if (method === "tools/call") {
2432
+ const fn = HANDLERS[params?.name]
2433
+ if (!fn) return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: `Unknown tool: ${params?.name}` }] } })
2434
+ if (credError) {
2435
+ const payload = { error: "credentials_unavailable", message: credError, human_action_required: true,
2436
+ human_action_reason: credError }
2437
+ return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(payload, null, 1) }] } })
2438
+ }
2439
+ const unknown = unknownArguments(params.name, params.arguments)
2440
+ if (unknown) return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(unknown, null, 1) }] } })
2441
+ try {
2442
+ const out = await fn(params.arguments ?? {})
2443
+ return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out, null, 1) }] } })
2444
+ } catch (e) {
2445
+ const payload = { error: e.code ?? "tool_failed", message: e.message,
2446
+ human_action_required: true,
2447
+ human_action_reason: `The media tool could not complete: ${e.message}. Report this failure rather than guessing the answer.` }
2448
+ return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: JSON.stringify(payload, null, 1) }] } })
2449
+ }
2450
+ }
2451
+ if (id !== undefined) send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } })
2452
+ }
2453
+
2454
+ let buf = ""
2455
+ let inFlight = 0
2456
+ let stdinClosed = false
2457
+
2458
+ // Exit only when stdin is closed AND nothing is still running. Exiting on 'end'
2459
+ // alone drops in-flight tool calls, which silently truncates a slow answer.
2460
+ function exitWhenIdle() {
2461
+ if (stdinClosed && inFlight === 0) process.exit(0)
2462
+ }
2463
+
2464
+ // Only run the stdio server when invoked directly (node media-mcp.mjs, exactly
2465
+ // how agent.json launches it). Guarding this lets the test suite import the
2466
+ // module for computeDownloadState/diagnose without attaching to stdin or exiting
2467
+ // the test process. The launch is a plain node <abs-path>, so argv[1] is the
2468
+ // file's own path and this comparison holds.
2469
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
2470
+ process.stdin.setEncoding("utf8")
2471
+ process.stdin.on("data", (chunk) => {
2472
+ buf += chunk
2473
+ let nl
2474
+ while ((nl = buf.indexOf("\n")) >= 0) {
2475
+ const line = buf.slice(0, nl).trim()
2476
+ buf = buf.slice(nl + 1)
2477
+ if (!line) continue
2478
+ let msg
2479
+ try { msg = JSON.parse(line) } catch { continue }
2480
+ inFlight += 1
2481
+ handle(msg)
2482
+ .catch((e) => {
2483
+ if (msg.id !== undefined) send({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: e.message } })
2484
+ })
2485
+ .finally(() => { inFlight -= 1; exitWhenIdle() })
2486
+ }
2487
+ })
2488
+ process.stdin.on("end", () => { stdinClosed = true; exitWhenIdle() })
2489
+ }