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