feedhelm-mcp 0.1.0__py3-none-any.whl
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.
- feedhelm_mcp/__init__.py +3 -0
- feedhelm_mcp/__main__.py +5 -0
- feedhelm_mcp/app.py +91 -0
- feedhelm_mcp/autoreply/__init__.py +5 -0
- feedhelm_mcp/autoreply/ai/__init__.py +6 -0
- feedhelm_mcp/autoreply/ai/command.py +77 -0
- feedhelm_mcp/autoreply/ai/fake.py +18 -0
- feedhelm_mcp/autoreply/ai/gate.py +29 -0
- feedhelm_mcp/autoreply/ai/guard_port.py +30 -0
- feedhelm_mcp/autoreply/ai/harness.py +122 -0
- feedhelm_mcp/autoreply/ai/hook.py +83 -0
- feedhelm_mcp/autoreply/ai/pass_.py +201 -0
- feedhelm_mcp/autoreply/ai/port.py +48 -0
- feedhelm_mcp/autoreply/ai/sender.py +30 -0
- feedhelm_mcp/autoreply/ceilings.py +43 -0
- feedhelm_mcp/autoreply/commenter.py +32 -0
- feedhelm_mcp/autoreply/data/screens_en.toml +45 -0
- feedhelm_mcp/autoreply/data/screens_pt-BR.toml +46 -0
- feedhelm_mcp/autoreply/deps.py +51 -0
- feedhelm_mcp/autoreply/digest.py +29 -0
- feedhelm_mcp/autoreply/gate.py +49 -0
- feedhelm_mcp/autoreply/guard_port.py +77 -0
- feedhelm_mcp/autoreply/hashing.py +8 -0
- feedhelm_mcp/autoreply/killswitch.py +67 -0
- feedhelm_mcp/autoreply/lifecycle.py +355 -0
- feedhelm_mcp/autoreply/limits.py +95 -0
- feedhelm_mcp/autoreply/model.py +206 -0
- feedhelm_mcp/autoreply/observe.py +69 -0
- feedhelm_mcp/autoreply/paths.py +38 -0
- feedhelm_mcp/autoreply/policy.py +76 -0
- feedhelm_mcp/autoreply/poll.py +230 -0
- feedhelm_mcp/autoreply/regex_subset.py +215 -0
- feedhelm_mcp/autoreply/rules.py +424 -0
- feedhelm_mcp/autoreply/rules_file.py +185 -0
- feedhelm_mcp/autoreply/screens.py +95 -0
- feedhelm_mcp/autoreply/send.py +278 -0
- feedhelm_mcp/autoreply/sensitive.py +182 -0
- feedhelm_mcp/autoreply/state_keys.py +7 -0
- feedhelm_mcp/autoreply/status.py +51 -0
- feedhelm_mcp/autoreply/stop.py +34 -0
- feedhelm_mcp/autoreply/store.py +444 -0
- feedhelm_mcp/autoreply/tick.py +251 -0
- feedhelm_mcp/autoreply/triage.py +219 -0
- feedhelm_mcp/cli/__init__.py +1 -0
- feedhelm_mcp/cli/approvals.py +171 -0
- feedhelm_mcp/cli/audit.py +64 -0
- feedhelm_mcp/cli/autoreply.py +477 -0
- feedhelm_mcp/cli/clipboard.py +97 -0
- feedhelm_mcp/cli/credentials.py +173 -0
- feedhelm_mcp/cli/doctor.py +129 -0
- feedhelm_mcp/cli/main.py +194 -0
- feedhelm_mcp/cli/output.py +13 -0
- feedhelm_mcp/cli/prompt.py +71 -0
- feedhelm_mcp/cli/rehearsal.py +78 -0
- feedhelm_mcp/cli/runner.py +336 -0
- feedhelm_mcp/cli/runtime.py +161 -0
- feedhelm_mcp/cli/setup.py +239 -0
- feedhelm_mcp/cli/verify.py +86 -0
- feedhelm_mcp/compose.py +189 -0
- feedhelm_mcp/config/__init__.py +1 -0
- feedhelm_mcp/config/capabilities.py +11 -0
- feedhelm_mcp/config/paths.py +61 -0
- feedhelm_mcp/config/settings.py +283 -0
- feedhelm_mcp/credentials/__init__.py +1 -0
- feedhelm_mcp/credentials/keyring_hint.py +15 -0
- feedhelm_mcp/credentials/provider.py +153 -0
- feedhelm_mcp/credentials/store.py +84 -0
- feedhelm_mcp/engage/__init__.py +1 -0
- feedhelm_mcp/engage/identity.py +37 -0
- feedhelm_mcp/engage/text.py +36 -0
- feedhelm_mcp/engage/window.py +77 -0
- feedhelm_mcp/graph/__init__.py +1 -0
- feedhelm_mcp/graph/client.py +293 -0
- feedhelm_mcp/graph/errors.py +285 -0
- feedhelm_mcp/graph/http.py +24 -0
- feedhelm_mcp/graph/models.py +67 -0
- feedhelm_mcp/graph/pacing.py +78 -0
- feedhelm_mcp/graph/retry.py +43 -0
- feedhelm_mcp/graph/untrusted.py +48 -0
- feedhelm_mcp/graph/usage.py +91 -0
- feedhelm_mcp/i18n/__init__.py +1 -0
- feedhelm_mcp/i18n/catalog.py +3671 -0
- feedhelm_mcp/i18n/language.py +38 -0
- feedhelm_mcp/i18n/when.py +25 -0
- feedhelm_mcp/mcp_server.py +109 -0
- feedhelm_mcp/publish/__init__.py +5 -0
- feedhelm_mcp/publish/bucket.py +109 -0
- feedhelm_mcp/publish/builder.py +79 -0
- feedhelm_mcp/publish/captions.py +20 -0
- feedhelm_mcp/publish/deps.py +31 -0
- feedhelm_mcp/publish/executor.py +428 -0
- feedhelm_mcp/publish/file_ports.py +40 -0
- feedhelm_mcp/publish/file_upload.py +68 -0
- feedhelm_mcp/publish/flow.py +111 -0
- feedhelm_mcp/publish/jobs.py +299 -0
- feedhelm_mcp/publish/limits_table.py +87 -0
- feedhelm_mcp/publish/local_file.py +102 -0
- feedhelm_mcp/publish/mp4.py +253 -0
- feedhelm_mcp/publish/mp4_boxes.py +86 -0
- feedhelm_mcp/publish/object_store.py +92 -0
- feedhelm_mcp/publish/public_head.py +69 -0
- feedhelm_mcp/publish/readback.py +151 -0
- feedhelm_mcp/publish/reconcile.py +53 -0
- feedhelm_mcp/publish/resumable.py +88 -0
- feedhelm_mcp/publish/urls.py +115 -0
- feedhelm_mcp/publish/video_check.py +113 -0
- feedhelm_mcp/py.typed +0 -0
- feedhelm_mcp/redact/__init__.py +1 -0
- feedhelm_mcp/redact/errors.py +16 -0
- feedhelm_mcp/redact/logging.py +41 -0
- feedhelm_mcp/redact/redactor.py +59 -0
- feedhelm_mcp/runner/__init__.py +1 -0
- feedhelm_mcp/runner/account.py +47 -0
- feedhelm_mcp/runner/autoreply_hook.py +90 -0
- feedhelm_mcp/runner/blocks.py +69 -0
- feedhelm_mcp/runner/deps.py +40 -0
- feedhelm_mcp/runner/logfile.py +32 -0
- feedhelm_mcp/runner/replay.py +127 -0
- feedhelm_mcp/runner/tick.py +380 -0
- feedhelm_mcp/safety/__init__.py +1 -0
- feedhelm_mcp/safety/audit.py +165 -0
- feedhelm_mcp/safety/caps.py +100 -0
- feedhelm_mcp/safety/clock.py +13 -0
- feedhelm_mcp/safety/context.py +24 -0
- feedhelm_mcp/safety/facade.py +118 -0
- feedhelm_mcp/safety/gate.py +45 -0
- feedhelm_mcp/safety/guard.py +291 -0
- feedhelm_mcp/safety/idempotency.py +94 -0
- feedhelm_mcp/safety/limits.py +85 -0
- feedhelm_mcp/safety/models.py +56 -0
- feedhelm_mcp/safety/payload.py +56 -0
- feedhelm_mcp/safety/pending.py +164 -0
- feedhelm_mcp/safety/permissions.py +96 -0
- feedhelm_mcp/safety/problems.py +17 -0
- feedhelm_mcp/safety/process_lock.py +79 -0
- feedhelm_mcp/safety/scope_cache.py +53 -0
- feedhelm_mcp/safety/store.py +32 -0
- feedhelm_mcp/safety/taint.py +22 -0
- feedhelm_mcp/safety/tokens_issue.py +62 -0
- feedhelm_mcp/safety/tokens_verify.py +55 -0
- feedhelm_mcp/safety/verified.py +143 -0
- feedhelm_mcp/safety/wiring.py +183 -0
- feedhelm_mcp/safety/write_pacer.py +99 -0
- feedhelm_mcp/scheduling/__init__.py +1 -0
- feedhelm_mcp/scheduling/guard_port.py +61 -0
- feedhelm_mcp/scheduling/media_url.py +20 -0
- feedhelm_mcp/scheduling/model.py +111 -0
- feedhelm_mcp/scheduling/policy.py +111 -0
- feedhelm_mcp/scheduling/runner_view.py +34 -0
- feedhelm_mcp/scheduling/spool.py +116 -0
- feedhelm_mcp/scheduling/status.py +29 -0
- feedhelm_mcp/scheduling/store.py +311 -0
- feedhelm_mcp/scheduling/timeparse.py +108 -0
- feedhelm_mcp/services/__init__.py +1 -0
- feedhelm_mcp/services/account.py +167 -0
- feedhelm_mcp/services/comment_reply.py +14 -0
- feedhelm_mcp/services/comments.py +109 -0
- feedhelm_mcp/services/doctor.py +614 -0
- feedhelm_mcp/services/insights.py +340 -0
- feedhelm_mcp/services/insights_rules.py +296 -0
- feedhelm_mcp/services/media.py +163 -0
- feedhelm_mcp/services/messages.py +219 -0
- feedhelm_mcp/services/paging.py +26 -0
- feedhelm_mcp/services/rawfields.py +46 -0
- feedhelm_mcp/services/reader.py +18 -0
- feedhelm_mcp/setup/__init__.py +1 -0
- feedhelm_mcp/setup/adapters/__init__.py +1 -0
- feedhelm_mcp/setup/adapters/autoreply_enabler.py +67 -0
- feedhelm_mcp/setup/adapters/command_runner.py +44 -0
- feedhelm_mcp/setup/adapters/environment.py +41 -0
- feedhelm_mcp/setup/adapters/fs.py +95 -0
- feedhelm_mcp/setup/adapters/launchd.py +119 -0
- feedhelm_mcp/setup/adapters/prompter.py +108 -0
- feedhelm_mcp/setup/adapters/runner_probe.py +41 -0
- feedhelm_mcp/setup/core/__init__.py +5 -0
- feedhelm_mcp/setup/core/autoreply_hook.py +64 -0
- feedhelm_mcp/setup/core/bundle.py +89 -0
- feedhelm_mcp/setup/core/claude_code.py +89 -0
- feedhelm_mcp/setup/core/config_toml.py +113 -0
- feedhelm_mcp/setup/core/desktop_install.py +59 -0
- feedhelm_mcp/setup/core/desktop_merge.py +48 -0
- feedhelm_mcp/setup/core/launchd_plist.py +74 -0
- feedhelm_mcp/setup/core/locations.py +29 -0
- feedhelm_mcp/setup/core/model.py +73 -0
- feedhelm_mcp/setup/core/plan.py +261 -0
- feedhelm_mcp/setup/core/ports.py +99 -0
- feedhelm_mcp/setup/core/runner_hook.py +86 -0
- feedhelm_mcp/setup/core/server_entry.py +91 -0
- feedhelm_mcp/setup/core/skill_install.py +81 -0
- feedhelm_mcp/setup/core/state.py +41 -0
- feedhelm_mcp/setup/core/steps_autoreply.py +55 -0
- feedhelm_mcp/setup/core/steps_local.py +242 -0
- feedhelm_mcp/setup/core/steps_network.py +147 -0
- feedhelm_mcp/setup/core/summary.py +123 -0
- feedhelm_mcp/setup/render.py +65 -0
- feedhelm_mcp/setup/skill/feedhelm-connect/SKILL.md +95 -0
- feedhelm_mcp/setup/skill/feedhelm-connect/references/chrome-setup.md +46 -0
- feedhelm_mcp/setup/skill/feedhelm-connect/references/meta-setup.md +104 -0
- feedhelm_mcp/setup/skill/feedhelm-connect/references/secrets.md +68 -0
- feedhelm_mcp/setup/skill/feedhelm-connect/references/troubleshooting.md +43 -0
- feedhelm_mcp/setup/skill_files.py +33 -0
- feedhelm_mcp/tools/__init__.py +1 -0
- feedhelm_mcp/tools/account.py +150 -0
- feedhelm_mcp/tools/audit.py +101 -0
- feedhelm_mcp/tools/comment_inbox.py +325 -0
- feedhelm_mcp/tools/comment_inbox_models.py +46 -0
- feedhelm_mcp/tools/comment_writes.py +334 -0
- feedhelm_mcp/tools/comments.py +73 -0
- feedhelm_mcp/tools/descriptions.py +102 -0
- feedhelm_mcp/tools/dm_writes.py +172 -0
- feedhelm_mcp/tools/errors.py +56 -0
- feedhelm_mcp/tools/inputs.py +57 -0
- feedhelm_mcp/tools/insights.py +140 -0
- feedhelm_mcp/tools/limits.py +92 -0
- feedhelm_mcp/tools/media.py +76 -0
- feedhelm_mcp/tools/messages.py +119 -0
- feedhelm_mcp/tools/problems.py +8 -0
- feedhelm_mcp/tools/publish.py +188 -0
- feedhelm_mcp/tools/publish_file.py +171 -0
- feedhelm_mcp/tools/publish_models.py +143 -0
- feedhelm_mcp/tools/publish_requests.py +115 -0
- feedhelm_mcp/tools/publish_run.py +262 -0
- feedhelm_mcp/tools/reel_intake.py +56 -0
- feedhelm_mcp/tools/registry.py +77 -0
- feedhelm_mcp/tools/runtime.py +130 -0
- feedhelm_mcp/tools/schedule.py +212 -0
- feedhelm_mcp/tools/schedule_list.py +200 -0
- feedhelm_mcp/tools/schedule_manage.py +242 -0
- feedhelm_mcp/tools/schedule_models.py +58 -0
- feedhelm_mcp/tools/schedule_run.py +267 -0
- feedhelm_mcp/tools/spec.py +25 -0
- feedhelm_mcp/tools/status.py +91 -0
- feedhelm_mcp/tools/target_ids.py +20 -0
- feedhelm_mcp/tools/undo.py +204 -0
- feedhelm_mcp/tools/write_result.py +27 -0
- feedhelm_mcp/tools/writes.py +58 -0
- feedhelm_mcp-0.1.0.dist-info/METADATA +324 -0
- feedhelm_mcp-0.1.0.dist-info/RECORD +241 -0
- feedhelm_mcp-0.1.0.dist-info/WHEEL +4 -0
- feedhelm_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- feedhelm_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
feedhelm_mcp/__init__.py
ADDED
feedhelm_mcp/__main__.py
ADDED
feedhelm_mcp/app.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Composition root for `serve`.
|
|
2
|
+
|
|
3
|
+
Order matters: logging is configured before settings, credentials or any SDK object
|
|
4
|
+
exist (the SDK must find our redacting handler already installed), the token is read
|
|
5
|
+
last so it is registered for redaction before the server is built.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from feedhelm_mcp import __version__
|
|
13
|
+
from feedhelm_mcp.compose import (
|
|
14
|
+
build_autoreply_line,
|
|
15
|
+
build_autoreply_tool_deps,
|
|
16
|
+
build_schedule_deps,
|
|
17
|
+
compose_publish,
|
|
18
|
+
)
|
|
19
|
+
from feedhelm_mcp.config.settings import ConfigError, load_settings
|
|
20
|
+
from feedhelm_mcp.credentials.provider import CredentialProvider
|
|
21
|
+
from feedhelm_mcp.mcp_server import build_server, run_stdio
|
|
22
|
+
from feedhelm_mcp.redact.errors import safe_message
|
|
23
|
+
from feedhelm_mcp.redact.logging import setup_logging
|
|
24
|
+
from feedhelm_mcp.redact.redactor import Redactor
|
|
25
|
+
from feedhelm_mcp.tools.errors import make_error_text
|
|
26
|
+
from feedhelm_mcp.tools.registry import build_read_specs
|
|
27
|
+
from feedhelm_mcp.tools.schedule_list import runner_line
|
|
28
|
+
from feedhelm_mcp.tools.spec import ToolSpec
|
|
29
|
+
from feedhelm_mcp.tools.writes import build_write_specs
|
|
30
|
+
|
|
31
|
+
_log = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
EXIT_CONFIG_ERROR = 2
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_serve(
|
|
37
|
+
redactor: Redactor,
|
|
38
|
+
*,
|
|
39
|
+
config_file: Path | None = None,
|
|
40
|
+
env_file: Path | None = None,
|
|
41
|
+
overrides: Mapping[str, object] | None = None,
|
|
42
|
+
extra_specs: Sequence[ToolSpec] = (),
|
|
43
|
+
) -> int:
|
|
44
|
+
setup_logging(redactor)
|
|
45
|
+
try:
|
|
46
|
+
loaded = load_settings(config_file=config_file, env_file=env_file, overrides=overrides)
|
|
47
|
+
except ConfigError as exc:
|
|
48
|
+
_log.error("%s", safe_message(exc, redactor))
|
|
49
|
+
return EXIT_CONFIG_ERROR
|
|
50
|
+
setup_logging(redactor, level=loaded.settings.log_level)
|
|
51
|
+
|
|
52
|
+
provider = CredentialProvider(redactor, env_file=loaded.env_file)
|
|
53
|
+
stack = compose_publish(loaded, provider, redactor)
|
|
54
|
+
runtime, guard = stack.runtime, stack.guard
|
|
55
|
+
token_source = stack.token_source
|
|
56
|
+
schedule_deps = build_schedule_deps(stack)
|
|
57
|
+
write_specs = build_write_specs(
|
|
58
|
+
runtime,
|
|
59
|
+
guard,
|
|
60
|
+
loaded.settings,
|
|
61
|
+
publish_deps=stack.deps,
|
|
62
|
+
file_ports=stack.file_ports,
|
|
63
|
+
schedule_deps=schedule_deps,
|
|
64
|
+
autoreply_deps=build_autoreply_tool_deps(stack),
|
|
65
|
+
)
|
|
66
|
+
specs = build_read_specs(
|
|
67
|
+
runtime,
|
|
68
|
+
loaded,
|
|
69
|
+
__version__,
|
|
70
|
+
extra=[*write_specs, *extra_specs],
|
|
71
|
+
safety=stack.safety,
|
|
72
|
+
scheduler_line=lambda: runner_line(schedule_deps, loaded.settings, runtime.lang),
|
|
73
|
+
autoreply_line=build_autoreply_line(
|
|
74
|
+
state_dir=stack.safety.state_dir,
|
|
75
|
+
config_dir=loaded.config_file.parent,
|
|
76
|
+
settings=loaded.settings,
|
|
77
|
+
clock=lambda: stack.safety.clock.now().timestamp(),
|
|
78
|
+
runner_status=schedule_deps.runner_status,
|
|
79
|
+
lang=runtime.lang,
|
|
80
|
+
),
|
|
81
|
+
)
|
|
82
|
+
server = build_server(
|
|
83
|
+
specs,
|
|
84
|
+
redactor,
|
|
85
|
+
__version__,
|
|
86
|
+
lifespan=runtime.session,
|
|
87
|
+
error_text=make_error_text(runtime.lang, loaded.settings.graph_host),
|
|
88
|
+
)
|
|
89
|
+
_log.info("starting stdio server (token source: %s)", token_source or "none")
|
|
90
|
+
run_stdio(server)
|
|
91
|
+
return 0
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Tier 3 building blocks: the model port, the safety harness, a fake and a command adapter.
|
|
2
|
+
|
|
3
|
+
Optional and off by default. Nothing here imports a model SDK or a network module: the model call
|
|
4
|
+
lives in the person's own program. Comment text is quoted DATA; the harness limits what can leave.
|
|
5
|
+
Tier 3 cannot be made injection-proof, only blast-radius-limited.
|
|
6
|
+
"""
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""CommandDrafter: the person's own program, run through the same command port setup uses.
|
|
2
|
+
|
|
3
|
+
The model call lives in a program the person configures (`autoreply_ai_command`); this package never
|
|
4
|
+
imports or names a model SDK. The program gets one JSON object as its last argument (the port closes
|
|
5
|
+
stdin) and answers one JSON object on stdout: `{"text": "..."}` or `{"text": null}`. The command must
|
|
6
|
+
be an absolute path with no shell metacharacters and runs as an argument list, never through a shell.
|
|
7
|
+
Every failure (bad command, exit code, timeout, bad or oversize output) is an `ai_error` result.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from dataclasses import asdict
|
|
14
|
+
from pathlib import PurePosixPath, PureWindowsPath
|
|
15
|
+
from typing import Final
|
|
16
|
+
|
|
17
|
+
import anyio
|
|
18
|
+
|
|
19
|
+
from feedhelm_mcp.autoreply.ai.port import DraftError, DraftRequest, DraftResult
|
|
20
|
+
from feedhelm_mcp.setup.core.ports import CommandResult, CommandRunner
|
|
21
|
+
|
|
22
|
+
MAX_OUTPUT_BYTES: Final = 4096
|
|
23
|
+
TIMEOUT_CODE: Final = 124
|
|
24
|
+
_SAFE_PATH: Final = re.compile(r"[A-Za-z0-9_./ +@:\\-]+")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _is_absolute(path: str) -> bool:
|
|
28
|
+
return PurePosixPath(path).is_absolute() or PureWindowsPath(path).is_absolute()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def command_problem(command: Sequence[str]) -> str | None:
|
|
32
|
+
"""A short code for why the command is not allowed, or None. Never echoes the command."""
|
|
33
|
+
if not command or not command[0]:
|
|
34
|
+
return "empty"
|
|
35
|
+
program = command[0]
|
|
36
|
+
if not _is_absolute(program):
|
|
37
|
+
return "not_absolute"
|
|
38
|
+
if not _SAFE_PATH.fullmatch(program) or ".." in re.split(r"[\\/]", program):
|
|
39
|
+
return "unsafe_path"
|
|
40
|
+
if any(ord(ch) < 32 or ord(ch) == 127 for arg in command for ch in arg):
|
|
41
|
+
return "control_character"
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse(result: CommandResult) -> DraftResult:
|
|
46
|
+
if result.returncode == TIMEOUT_CODE:
|
|
47
|
+
return DraftResult(error=DraftError.TIMEOUT)
|
|
48
|
+
if result.returncode != 0:
|
|
49
|
+
return DraftResult(error=DraftError.FAILED)
|
|
50
|
+
if len(result.stdout.encode("utf-8")) > MAX_OUTPUT_BYTES:
|
|
51
|
+
return DraftResult(error=DraftError.TOO_LARGE)
|
|
52
|
+
try:
|
|
53
|
+
body = json.loads(result.stdout)
|
|
54
|
+
except ValueError:
|
|
55
|
+
return DraftResult(error=DraftError.BAD_OUTPUT)
|
|
56
|
+
if not isinstance(body, dict) or set(body) != {"text"}:
|
|
57
|
+
return DraftResult(error=DraftError.BAD_OUTPUT)
|
|
58
|
+
text = body["text"]
|
|
59
|
+
if text is None or isinstance(text, str):
|
|
60
|
+
return DraftResult(text=text)
|
|
61
|
+
return DraftResult(error=DraftError.BAD_OUTPUT)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class CommandDrafter:
|
|
65
|
+
def __init__(self, runner: CommandRunner, command: Sequence[str]) -> None:
|
|
66
|
+
self._runner = runner
|
|
67
|
+
self._command = tuple(command)
|
|
68
|
+
|
|
69
|
+
async def draft(self, request: DraftRequest) -> DraftResult:
|
|
70
|
+
if command_problem(self._command) is not None:
|
|
71
|
+
return DraftResult(error=DraftError.BAD_COMMAND)
|
|
72
|
+
argv = [*self._command, json.dumps(asdict(request), ensure_ascii=True, separators=(",", ":"))]
|
|
73
|
+
try:
|
|
74
|
+
result = await anyio.to_thread.run_sync(self._runner.run, argv)
|
|
75
|
+
except Exception:
|
|
76
|
+
return DraftResult(error=DraftError.FAILED)
|
|
77
|
+
return _parse(result)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""A drafter for tests and dry runs: scripted answers in order, and a record of what it was asked."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
|
|
5
|
+
from feedhelm_mcp.autoreply.ai.port import DraftError, DraftRequest, DraftResult
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ScriptedDrafter:
|
|
9
|
+
def __init__(self, script: Sequence[str | DraftResult | None]) -> None:
|
|
10
|
+
self._script = list(script)
|
|
11
|
+
self.requests: list[DraftRequest] = []
|
|
12
|
+
|
|
13
|
+
async def draft(self, request: DraftRequest) -> DraftResult:
|
|
14
|
+
self.requests.append(request)
|
|
15
|
+
if not self._script:
|
|
16
|
+
return DraftResult(error=DraftError.FAILED)
|
|
17
|
+
item = self._script.pop(0)
|
|
18
|
+
return item if isinstance(item, DraftResult) else DraftResult(text=item)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""The Tier 3 gate, re-read on every pass: both opt-ins must hold and nothing may be stopped.
|
|
2
|
+
|
|
3
|
+
Opt-in one is the config capability `auto_reply_ai`; opt-in two is the typed-phrase consent row. The
|
|
4
|
+
mode (draft or send) is the person's second phrase. Either opt-in missing, a pause, a halt or a timed
|
|
5
|
+
block leaves Tier 3 completely inert: no model call, no Graph call.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from feedhelm_mcp.autoreply.killswitch import paused
|
|
11
|
+
from feedhelm_mcp.autoreply.state_keys import KEY_AI_MODE, KEY_AI_OPTIN_AT
|
|
12
|
+
from feedhelm_mcp.autoreply.status import AiMode
|
|
13
|
+
from feedhelm_mcp.autoreply.store import AutoreplyStore
|
|
14
|
+
from feedhelm_mcp.config.settings import Settings
|
|
15
|
+
|
|
16
|
+
CAPABILITY = "auto_reply_ai"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ai_mode(
|
|
20
|
+
settings: Settings, store: AutoreplyStore, state_dir: Path, *, halted: bool, blocked: bool
|
|
21
|
+
) -> AiMode | None:
|
|
22
|
+
""" "draft" or "send" when Tier 3 may run now, else None."""
|
|
23
|
+
if CAPABILITY not in settings.autoreply_capabilities:
|
|
24
|
+
return None
|
|
25
|
+
if store.kv_get(KEY_AI_OPTIN_AT) is None:
|
|
26
|
+
return None
|
|
27
|
+
if halted or blocked or paused(state_dir, store, runner_halted=halted):
|
|
28
|
+
return None
|
|
29
|
+
return "send" if store.kv_get(KEY_AI_MODE) == "send" else "draft"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""AutoReplyAiGuard: the only producer of origin "autoreply_ai".
|
|
2
|
+
|
|
3
|
+
It checks, like the rules guard, that the request is exactly one stored reply (tool, comment id, text
|
|
4
|
+
hash, idempotency key) and refuses anything else, so a model's output can reach exactly one write
|
|
5
|
+
function: one public reply to one comment. Approval is skipped only when the person typed the second
|
|
6
|
+
phrase (send mode); draft mode never reaches a guard at all. Capability, caps, pacing, the write lock
|
|
7
|
+
and audit always apply.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
|
|
12
|
+
from feedhelm_mcp.autoreply.guard_port import BoundReplyGuard
|
|
13
|
+
from feedhelm_mcp.safety.models import WriteRequest
|
|
14
|
+
from feedhelm_mcp.safety.wiring import GuardPort
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AutoReplyAiGuard(BoundReplyGuard):
|
|
18
|
+
def __init__(self, inner: GuardPort, comment_id: str, stored_reply_hash: str, *, send_mode: bool) -> None:
|
|
19
|
+
super().__init__(inner, comment_id, stored_reply_hash)
|
|
20
|
+
self._send_mode = send_mode
|
|
21
|
+
|
|
22
|
+
def _bind(self, req: WriteRequest) -> WriteRequest:
|
|
23
|
+
return replace(
|
|
24
|
+
req,
|
|
25
|
+
origin="autoreply_ai",
|
|
26
|
+
ai_send_mode=self._send_mode,
|
|
27
|
+
inherited_untrusted=True,
|
|
28
|
+
local=False,
|
|
29
|
+
needs_approval=True,
|
|
30
|
+
)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The Tier 3 safety harness: pure checks on a model's draft before it may become sendable.
|
|
2
|
+
|
|
3
|
+
It limits WHAT CAN LEAVE (short, no link, no mention, no number, no echo of the comment, none of the
|
|
4
|
+
person's blocked words, nothing a skip rule would have skipped). It cannot prove a reply is
|
|
5
|
+
appropriate. Reasons are codes; neither the draft nor the comment is ever echoed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from difflib import SequenceMatcher
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Final
|
|
13
|
+
|
|
14
|
+
from feedhelm_mcp.autoreply import sensitive
|
|
15
|
+
from feedhelm_mcp.autoreply.rules import (
|
|
16
|
+
RuleSet,
|
|
17
|
+
SkipRule,
|
|
18
|
+
fold,
|
|
19
|
+
has_forbidden_char,
|
|
20
|
+
keyword_pattern,
|
|
21
|
+
pattern_hits,
|
|
22
|
+
)
|
|
23
|
+
from feedhelm_mcp.autoreply.screens import has_link, has_mention, normalize
|
|
24
|
+
from feedhelm_mcp.engage.text import reply_text_problems
|
|
25
|
+
|
|
26
|
+
ECHO_LIMIT: Final = 20
|
|
27
|
+
BUILTIN_BLOCKED: Final = (
|
|
28
|
+
"suicide",
|
|
29
|
+
"kill yourself",
|
|
30
|
+
"self harm",
|
|
31
|
+
"abuse",
|
|
32
|
+
"lawyer",
|
|
33
|
+
"attorney",
|
|
34
|
+
"lawsuit",
|
|
35
|
+
"refund",
|
|
36
|
+
"diagnose",
|
|
37
|
+
"diagnosis",
|
|
38
|
+
"guaranteed",
|
|
39
|
+
"cure",
|
|
40
|
+
"medication",
|
|
41
|
+
)
|
|
42
|
+
_PHONE: Final = re.compile(r"(?:\d[\s().-]?){7,}")
|
|
43
|
+
_SPELLED_EMAIL: Final = re.compile(r"[a-z0-9._+-]{1,64}\s?(?:\(at\)|\[at\])\s?[a-z0-9-]{1,63}")
|
|
44
|
+
_PLAIN_EMAIL: Final = re.compile(r"\w@\w")
|
|
45
|
+
_BUILTIN_PATTERN: Final = keyword_pattern([fold(w) for w in BUILTIN_BLOCKED])
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class HarnessReason(StrEnum):
|
|
49
|
+
EMPTY = "empty"
|
|
50
|
+
CONTROL = "control"
|
|
51
|
+
TOO_LONG = "too_long"
|
|
52
|
+
LINK = "link"
|
|
53
|
+
MENTION = "mention"
|
|
54
|
+
HASHTAG = "hashtag"
|
|
55
|
+
EMAIL = "email"
|
|
56
|
+
PHONE = "phone"
|
|
57
|
+
BLOCKLIST = "blocklist"
|
|
58
|
+
ECHO = "echo"
|
|
59
|
+
SKIP_RULE = "skip_rule"
|
|
60
|
+
SENSITIVE = "sensitive"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class HarnessPolicy:
|
|
65
|
+
max_chars: int
|
|
66
|
+
blocked_words: tuple[str, ...] = () # the person's ai_block words, already folded
|
|
67
|
+
skips: tuple[SkipRule, ...] = field(default_factory=tuple)
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def from_rules(cls, max_chars: int, rules: RuleSet | None) -> "HarnessPolicy":
|
|
71
|
+
if rules is None:
|
|
72
|
+
return cls(max_chars)
|
|
73
|
+
return cls(max_chars, rules.ai_block, rules.skips)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _echoes(draft: str, comment: str) -> bool:
|
|
77
|
+
match = SequenceMatcher(None, draft, comment, autojunk=False).find_longest_match(
|
|
78
|
+
0, len(draft), 0, len(comment)
|
|
79
|
+
)
|
|
80
|
+
return match.size > ECHO_LIMIT
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _blocked(folded: str, policy: HarnessPolicy) -> bool:
|
|
84
|
+
if _BUILTIN_PATTERN.search(folded):
|
|
85
|
+
return True
|
|
86
|
+
return (
|
|
87
|
+
bool(policy.blocked_words) and keyword_pattern(list(policy.blocked_words)).search(folded) is not None
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def draft_is_sendable(
|
|
92
|
+
draft: str | None, normalized_comment: str, policy: HarnessPolicy
|
|
93
|
+
) -> list[HarnessReason]:
|
|
94
|
+
"""Every reason the draft may not be sent (empty list means the checks pass)."""
|
|
95
|
+
if draft is None or not draft.strip():
|
|
96
|
+
return [HarnessReason.EMPTY]
|
|
97
|
+
reasons: list[HarnessReason] = []
|
|
98
|
+
if has_forbidden_char(draft):
|
|
99
|
+
reasons.append(HarnessReason.CONTROL)
|
|
100
|
+
if len(draft) > policy.max_chars or reply_text_problems(draft):
|
|
101
|
+
reasons.append(HarnessReason.TOO_LONG)
|
|
102
|
+
normalized = normalize(draft)
|
|
103
|
+
if has_link(normalized):
|
|
104
|
+
reasons.append(HarnessReason.LINK)
|
|
105
|
+
if has_mention(normalized):
|
|
106
|
+
reasons.append(HarnessReason.MENTION)
|
|
107
|
+
if "#" in normalized:
|
|
108
|
+
reasons.append(HarnessReason.HASHTAG)
|
|
109
|
+
if _PLAIN_EMAIL.search(normalized) or _SPELLED_EMAIL.search(normalized):
|
|
110
|
+
reasons.append(HarnessReason.EMAIL)
|
|
111
|
+
if _PHONE.search(normalized):
|
|
112
|
+
reasons.append(HarnessReason.PHONE)
|
|
113
|
+
folded = fold(normalized)
|
|
114
|
+
if _blocked(folded, policy):
|
|
115
|
+
reasons.append(HarnessReason.BLOCKLIST)
|
|
116
|
+
if _echoes(normalized, normalized_comment):
|
|
117
|
+
reasons.append(HarnessReason.ECHO)
|
|
118
|
+
if any(pattern_hits(skip.pattern, skip.accent_insensitive, normalized) for skip in policy.skips):
|
|
119
|
+
reasons.append(HarnessReason.SKIP_RULE)
|
|
120
|
+
if sensitive.check(normalized_comment) is not None:
|
|
121
|
+
reasons.append(HarnessReason.SENSITIVE)
|
|
122
|
+
return reasons
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""The Tier 3 hook the runner shell plugs into the autopilot pass (the only wiring of the model side).
|
|
2
|
+
|
|
3
|
+
Every pass re-reads both opt-ins and every stop; with either missing, or the rules file unusable, the
|
|
4
|
+
drafter is never asked and no Graph call is made. In draft mode no sender is built at all.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from feedhelm_mcp.autoreply.ai.gate import ai_mode
|
|
11
|
+
from feedhelm_mcp.autoreply.ai.harness import HarnessPolicy
|
|
12
|
+
from feedhelm_mcp.autoreply.ai.pass_ import AiPassConfig, run_ai_pass
|
|
13
|
+
from feedhelm_mcp.autoreply.ai.port import ReplyDrafter
|
|
14
|
+
from feedhelm_mcp.autoreply.ai.sender import AiSender
|
|
15
|
+
from feedhelm_mcp.autoreply.deps import AiHook, AutoreplyDeps
|
|
16
|
+
from feedhelm_mcp.autoreply.limits import effective_policy
|
|
17
|
+
from feedhelm_mcp.autoreply.model import AiReport, AutoreplyPolicy
|
|
18
|
+
from feedhelm_mcp.autoreply.observe import AUDIT_ORIGIN_AI, observe
|
|
19
|
+
from feedhelm_mcp.autoreply.rules import RuleSet
|
|
20
|
+
from feedhelm_mcp.runner import blocks
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _load(deps: AutoreplyDeps) -> RuleSet | None:
|
|
24
|
+
if deps.rules_loader is None:
|
|
25
|
+
return None
|
|
26
|
+
return deps.rules_loader().rules
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _policy_from(deps: AutoreplyDeps, rules: RuleSet | None) -> HarnessPolicy | None:
|
|
30
|
+
if rules is None:
|
|
31
|
+
return None
|
|
32
|
+
return HarnessPolicy.from_rules(deps.settings.autoreply_ai_max_chars, rules)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _harness_source(deps: AutoreplyDeps, first: RuleSet | None) -> Callable[[], HarnessPolicy | None]:
|
|
36
|
+
"""The first look at the rules serves both the person's limits and the first harness check (one read);
|
|
37
|
+
every later check reads the file afresh, so a rule edited meanwhile still applies."""
|
|
38
|
+
used = {"first": False}
|
|
39
|
+
|
|
40
|
+
def source() -> HarnessPolicy | None:
|
|
41
|
+
if not used["first"]:
|
|
42
|
+
used["first"] = True
|
|
43
|
+
return _policy_from(deps, first)
|
|
44
|
+
return _policy_from(deps, _load(deps))
|
|
45
|
+
|
|
46
|
+
return source
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def make_ai_hook(drafter: ReplyDrafter) -> AiHook:
|
|
50
|
+
async def hook(
|
|
51
|
+
deps: AutoreplyDeps, account: Callable[[], Awaitable[AutoreplyDeps | None]], may_send: bool
|
|
52
|
+
) -> AiReport:
|
|
53
|
+
mode = ai_mode(
|
|
54
|
+
deps.settings,
|
|
55
|
+
deps.store,
|
|
56
|
+
deps.state_dir,
|
|
57
|
+
halted=blocks.halted(deps.sched),
|
|
58
|
+
blocked=blocks.block_active(deps.sched, deps.clock()),
|
|
59
|
+
)
|
|
60
|
+
if mode is None:
|
|
61
|
+
return AiReport(inert=True)
|
|
62
|
+
|
|
63
|
+
def record(tool: str, payload: dict[str, Any]) -> None:
|
|
64
|
+
observe(deps.audit, tool, payload, origin=AUDIT_ORIGIN_AI)
|
|
65
|
+
|
|
66
|
+
first = _load(deps)
|
|
67
|
+
sender = None
|
|
68
|
+
if mode == "send" and may_send:
|
|
69
|
+
working = await account() # the own username is needed to check the thread before sending
|
|
70
|
+
sender = AiSender(working) if working is not None else None
|
|
71
|
+
config = AiPassConfig(
|
|
72
|
+
mode=mode,
|
|
73
|
+
policy=effective_policy(
|
|
74
|
+
AutoreplyPolicy.from_settings(deps.settings, "ai"), None if first is None else first.limits
|
|
75
|
+
),
|
|
76
|
+
max_chars=deps.settings.autoreply_ai_max_chars,
|
|
77
|
+
may_send=may_send and (mode == "draft" or sender is not None),
|
|
78
|
+
harness=_harness_source(deps, first),
|
|
79
|
+
observe=record,
|
|
80
|
+
)
|
|
81
|
+
return await run_ai_pass(drafter, sender, deps.store, config, deps.clock)
|
|
82
|
+
|
|
83
|
+
return hook
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""One Tier 3 pass: pick one waiting comment, ask the drafter, check the draft, store it or send it.
|
|
2
|
+
|
|
3
|
+
The pass receives a ReplyDrafter, a ReplySender (one method) and the inbox: it has no guard, no
|
|
4
|
+
runtime, no Graph client and no tool, so the only thing a model's words can ever cause is one public
|
|
5
|
+
reply, through the sender, after the harness accepted them. Draft mode (the default) stores the checked
|
|
6
|
+
draft for the person and sends nothing; send mode (the second typed phrase) replies, at most one per
|
|
7
|
+
pass, under the tighter AI caps. No comment text, username or draft is written to any audit line: ids,
|
|
8
|
+
codes, lengths and hashes only.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, Final
|
|
14
|
+
|
|
15
|
+
from feedhelm_mcp.autoreply import sensitive
|
|
16
|
+
from feedhelm_mcp.autoreply.ai.harness import HarnessPolicy, draft_is_sendable
|
|
17
|
+
from feedhelm_mcp.autoreply.ai.port import DraftRequest, ReplyDrafter, ReplySender
|
|
18
|
+
from feedhelm_mcp.autoreply.hashing import reply_hash
|
|
19
|
+
from feedhelm_mcp.autoreply.limits import person_block
|
|
20
|
+
from feedhelm_mcp.autoreply.model import (
|
|
21
|
+
AiReport,
|
|
22
|
+
AutoreplyPolicy,
|
|
23
|
+
InboxRow,
|
|
24
|
+
InboxState,
|
|
25
|
+
Intent,
|
|
26
|
+
SkipReason,
|
|
27
|
+
needs_human_reason,
|
|
28
|
+
)
|
|
29
|
+
from feedhelm_mcp.autoreply.observe import TOOL_AI_DRAFT, TOOL_AI_SEND, TOOL_AI_SKIP
|
|
30
|
+
from feedhelm_mcp.autoreply.policy import jittered_interval
|
|
31
|
+
from feedhelm_mcp.autoreply.screens import normalize
|
|
32
|
+
from feedhelm_mcp.autoreply.status import AiMode
|
|
33
|
+
from feedhelm_mcp.autoreply.store import AutoreplyStore
|
|
34
|
+
from feedhelm_mcp.safety.caps import DAY_SECONDS, HOUR_SECONDS, wait_for_times
|
|
35
|
+
|
|
36
|
+
REASON_NO_MATCH: Final = "no_match"
|
|
37
|
+
WAIT_TIER1_FIRST: Final = "tier1_first"
|
|
38
|
+
WAIT_RULES_INVALID: Final = "rules_invalid"
|
|
39
|
+
STYLE_NOTE: Final = "" # the rules file has no style field yet: the drafter gets none
|
|
40
|
+
_TEXT_SHA_LENGTH: Final = 16
|
|
41
|
+
|
|
42
|
+
type Observer = Callable[[str, dict[str, Any]], None]
|
|
43
|
+
type HarnessSource = Callable[[], HarnessPolicy | None]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class AiPassConfig:
|
|
48
|
+
mode: AiMode
|
|
49
|
+
policy: AutoreplyPolicy # the AI policy: tighter caps and a longer interval
|
|
50
|
+
max_chars: int
|
|
51
|
+
may_send: bool # False when a rule reply already went out in this pass
|
|
52
|
+
harness: HarnessSource # read afresh each time; None means the rules file is unusable
|
|
53
|
+
observe: Observer
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _payload(row: InboxRow, text: str | None = None, **extra: object) -> dict[str, Any]:
|
|
57
|
+
payload: dict[str, Any] = {"comment_id": row.comment_id, "media_id": row.media_id, **extra}
|
|
58
|
+
if text is not None:
|
|
59
|
+
payload["text_len"] = len(text)
|
|
60
|
+
payload["text_sha"] = reply_hash(text)[:_TEXT_SHA_LENGTH]
|
|
61
|
+
return payload
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _candidates(store: AutoreplyStore, now: float, policy: AutoreplyPolicy) -> list[InboxRow]:
|
|
65
|
+
"""Comments the rules looked at and left waiting, inside the answer window, oldest first."""
|
|
66
|
+
rows = store.rows_in_states([InboxState.WAITING])
|
|
67
|
+
return [
|
|
68
|
+
r
|
|
69
|
+
for r in rows
|
|
70
|
+
if r.reason == REASON_NO_MATCH
|
|
71
|
+
and r.text is not None
|
|
72
|
+
and now - r.commented_at <= policy.max_age_seconds
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _send_wait(row: InboxRow, intents: Sequence[Intent], now: float, policy: AutoreplyPolicy) -> str | None:
|
|
77
|
+
"""Why this reply may not go out yet: spacing over every tier, caps over the AI intents only."""
|
|
78
|
+
if (blocked := person_block(intents, row, now, policy)) is not None:
|
|
79
|
+
return blocked
|
|
80
|
+
if intents:
|
|
81
|
+
remaining = jittered_interval(row.comment_id, policy.min_interval_seconds) - (
|
|
82
|
+
now - max(i.at for i in intents)
|
|
83
|
+
)
|
|
84
|
+
if remaining > 0:
|
|
85
|
+
return "interval"
|
|
86
|
+
ai_times = sorted(i.at for i in intents if i.tier == "ai")
|
|
87
|
+
for reason, window, limit in (
|
|
88
|
+
("cap_hour", HOUR_SECONDS, policy.cap_hour),
|
|
89
|
+
("cap_day", DAY_SECONDS, policy.cap_day),
|
|
90
|
+
):
|
|
91
|
+
if wait_for_times(ai_times, now, window, limit) is not None:
|
|
92
|
+
return reason
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def _send(
|
|
97
|
+
sender: ReplySender,
|
|
98
|
+
store: AutoreplyStore,
|
|
99
|
+
row: InboxRow,
|
|
100
|
+
text: str,
|
|
101
|
+
config: AiPassConfig,
|
|
102
|
+
report: AiReport,
|
|
103
|
+
) -> AiReport:
|
|
104
|
+
"""Check the text once more with the current rules, then hand it to the one-method sender."""
|
|
105
|
+
policy = config.harness()
|
|
106
|
+
normalized = normalize(row.text or "")
|
|
107
|
+
if policy is None or draft_is_sendable(text, normalized, policy):
|
|
108
|
+
store.mark_skipped(row.comment_id, SkipReason.AI_REJECTED.value)
|
|
109
|
+
config.observe(TOOL_AI_SKIP, _payload(row, text, reason=SkipReason.AI_REJECTED.value, n=1))
|
|
110
|
+
report.rejected += 1
|
|
111
|
+
return report
|
|
112
|
+
outcome = await sender.send_reply(row.comment_id, text)
|
|
113
|
+
config.observe(TOOL_AI_SEND, _payload(row, text, reason=outcome))
|
|
114
|
+
report.sent = outcome
|
|
115
|
+
return report
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def _leftover(
|
|
119
|
+
sender: ReplySender | None, store: AutoreplyStore, config: AiPassConfig, report: AiReport, now: float
|
|
120
|
+
) -> AiReport | None:
|
|
121
|
+
"""A reply stored as matched (tier ai) whose send never started: finish it under the same rules."""
|
|
122
|
+
row = next(
|
|
123
|
+
(
|
|
124
|
+
r
|
|
125
|
+
for r in store.rows_in_states([InboxState.MATCHED])
|
|
126
|
+
if r.tier == "ai" and r.draft_text is not None
|
|
127
|
+
),
|
|
128
|
+
None,
|
|
129
|
+
)
|
|
130
|
+
if row is None or sender is None:
|
|
131
|
+
return None
|
|
132
|
+
wait = _send_wait(row, store.intents(now - DAY_SECONDS), now, config.policy)
|
|
133
|
+
if wait is not None:
|
|
134
|
+
report.wait = wait
|
|
135
|
+
return report
|
|
136
|
+
return await _send(sender, store, row, row.draft_text or "", config, report)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def run_ai_pass(
|
|
140
|
+
drafter: ReplyDrafter,
|
|
141
|
+
sender: ReplySender | None,
|
|
142
|
+
store: AutoreplyStore,
|
|
143
|
+
config: AiPassConfig,
|
|
144
|
+
clock: Callable[[], float],
|
|
145
|
+
) -> AiReport:
|
|
146
|
+
"""Draft (and in send mode send) at most one reply. `sender` is None whenever sending is not allowed."""
|
|
147
|
+
report = AiReport()
|
|
148
|
+
now = clock()
|
|
149
|
+
sending = config.mode == "send"
|
|
150
|
+
if sending and not config.may_send:
|
|
151
|
+
report.wait = WAIT_TIER1_FIRST
|
|
152
|
+
return report
|
|
153
|
+
if sending and (finished := await _leftover(sender, store, config, report, now)) is not None:
|
|
154
|
+
return finished
|
|
155
|
+
intents = store.intents(now - DAY_SECONDS)
|
|
156
|
+
chosen: InboxRow | None = None
|
|
157
|
+
for row in _candidates(store, now, config.policy):
|
|
158
|
+
wait = _send_wait(row, intents, now, config.policy) if sending else None
|
|
159
|
+
if wait is None:
|
|
160
|
+
chosen = row
|
|
161
|
+
break
|
|
162
|
+
report.wait = report.wait or wait
|
|
163
|
+
if chosen is None:
|
|
164
|
+
return report
|
|
165
|
+
report.wait = None
|
|
166
|
+
policy = config.harness()
|
|
167
|
+
if policy is None: # an unusable rules file: ask the model nothing
|
|
168
|
+
report.wait = WAIT_RULES_INVALID
|
|
169
|
+
return report
|
|
170
|
+
normalized = normalize(chosen.text or "")
|
|
171
|
+
human = sensitive.check(normalized)
|
|
172
|
+
if human is not None: # a sensitive comment is never given to the model: it is left for the person
|
|
173
|
+
reason = needs_human_reason(human)
|
|
174
|
+
store.mark_needs_human(chosen.comment_id, reason)
|
|
175
|
+
config.observe(TOOL_AI_SKIP, _payload(chosen, reason=reason, n=1))
|
|
176
|
+
report.rejected += 1
|
|
177
|
+
return report
|
|
178
|
+
result = await drafter.draft(DraftRequest.build(normalized, STYLE_NOTE, config.max_chars))
|
|
179
|
+
if result.error is not None:
|
|
180
|
+
store.mark_skipped(chosen.comment_id, SkipReason.AI_ERROR.value)
|
|
181
|
+
config.observe(TOOL_AI_SKIP, _payload(chosen, reason=SkipReason.AI_ERROR.value, n=1))
|
|
182
|
+
report.errors += 1
|
|
183
|
+
return report
|
|
184
|
+
reasons = draft_is_sendable(result.text, normalized, policy)
|
|
185
|
+
if reasons or result.text is None:
|
|
186
|
+
store.mark_skipped(chosen.comment_id, SkipReason.AI_REJECTED.value)
|
|
187
|
+
config.observe(
|
|
188
|
+
TOOL_AI_SKIP, _payload(chosen, result.text, reason=SkipReason.AI_REJECTED.value, n=len(reasons))
|
|
189
|
+
)
|
|
190
|
+
report.rejected += 1
|
|
191
|
+
return report
|
|
192
|
+
text = result.text
|
|
193
|
+
digest = reply_hash(text)
|
|
194
|
+
if not sending:
|
|
195
|
+
if store.set_drafted(chosen.comment_id, digest, text):
|
|
196
|
+
config.observe(TOOL_AI_DRAFT, _payload(chosen, text, reason="drafted"))
|
|
197
|
+
report.drafted += 1
|
|
198
|
+
return report
|
|
199
|
+
if sender is None or not store.set_matched_ai(chosen.comment_id, digest, text):
|
|
200
|
+
return report
|
|
201
|
+
return await _send(sender, store, store.get(chosen.comment_id) or chosen, text, config, report)
|