diff --git a/.env.example b/.env.example index e88848adb..8fe74b24d 100644 --- a/.env.example +++ b/.env.example @@ -136,6 +136,9 @@ TYPESENSE_API_KEY=your-typesense-api-key-here # JVSPATIAL_FILES_ROOT_PATH=./.files # JVSPATIAL_FILE_STORAGE_BASE_URL=http://localhost:8000 # JVSPATIAL_FILE_STORAGE_MAX_SIZE=104857600 +# Signed proxy URLs for anonymous media delivery (TTS/WhatsApp). Required when auth is enabled. +# JVSPATIAL_PROXY_ENABLED=true +# JVSPATIAL_PROXY_PREFIX=/p # S3 (canonical names — do not use *_REGION_NAME / *_ACCESS_KEY_ID / *_SECRET_ACCESS_KEY) # JVSPATIAL_S3_BUCKET_NAME= diff --git a/.planning/plans/2026-11-06-harness-tracked-assets.json b/.planning/plans/2026-11-06-harness-tracked-assets.json index 09781b9a0..3c4e9d101 100644 --- a/.planning/plans/2026-11-06-harness-tracked-assets.json +++ b/.planning/plans/2026-11-06-harness-tracked-assets.json @@ -12,7 +12,7 @@ { "path": "examples/jvagent_app/agents/jvagent/leadgen_agent/skills/example_leadgen/SKILL.md", "scope": "app-example", - "sha256": "sha256:de520833cf56e3e747f2a4ae534cdbf995da6212648c97a0855cf829d1497128", + "sha256": "sha256:b8a19a4eaad41c64317d9d86f2be48cdd850c4f10f227530b052f0c0643c04c8", "name": "example_leadgen", "spec": null, "extends": "action:jvagent/leadgen", @@ -94,7 +94,7 @@ { "path": "examples/jvagent_app/agents/jvagent/leadgen_agent/skills/product_inquiry_leads/SKILL.md", "scope": "app-example", - "sha256": "sha256:e342e973c6ce9fd6ce2d0430adac37da8dba85138db6d7b552d8389a9c64d060", + "sha256": "sha256:0603c34934fc834d456c42bc4b4a8bdc855b058d18f5296c9db80b705c588f65", "name": "product_inquiry_leads", "spec": null, "extends": "action:jvagent/leadgen", @@ -513,7 +513,7 @@ { "path": "jvagent/action/leadgen/SKILL.md", "scope": "package", - "sha256": "sha256:02e3de03fbdf06772cddb2ebf5290d7c09ba6f60de0b6997c5362690386cf6cd", + "sha256": "sha256:4a34f16549137f67b758678e2c2017a63469872be9b8e2a4526e328585d601da", "name": "leadgen_base", "spec": null, "extends": null, @@ -533,12 +533,12 @@ "name" ], "tracked_directory_files": 20, - "tracked_directory_digest": "sha256:1a6be2ca8095118e4a399620db144ee69aee850d362076f215effad8e5b3d19e" + "tracked_directory_digest": "sha256:75f03f9262a664af9368abaf16923cf354607c5086f5f2d4ceefd4d0c0e00667" }, { "path": "jvagent/action/leadgen/examples/example_leadgen/SKILL.md", "scope": "package", - "sha256": "sha256:019976d27a37192f030568a838d61931c83a8e5a8e502b35ac2752c71cd261c3", + "sha256": "sha256:e0410e232030480d882fa87b1f5fd96c066c4cb0f79f15b6ada4a9f5196baf63", "name": "example_leadgen", "spec": null, "extends": "action:jvagent/leadgen", @@ -1291,7 +1291,7 @@ "name": "jvagent/handoff_action", "archetype": "HandoffAction", "tracked_directory_files": 4, - "tracked_directory_digest": "sha256:5f8d9c9a8c9b5b7cac0cafa61eff1edcb4f618f960126708e6463daadf78deaa" + "tracked_directory_digest": "sha256:0514274e3bc852c9b17d03de09adb00c0fcef0c461b29c5f173b3227c2d92050" }, { "path": "jvagent/action/interview/info.yaml", @@ -1309,7 +1309,7 @@ "name": "jvagent/intro_interact_action", "archetype": "IntroInteractAction", "tracked_directory_files": 3, - "tracked_directory_digest": "sha256:1f53c59c6e160931fbe0aac2e8302077800dc3b388939b7cc42288c4613fade2" + "tracked_directory_digest": "sha256:750df6352ea0626c8583342d38b2fffa98a598731ddbac6986356edcedea5aee" }, { "path": "jvagent/action/leadgen/info.yaml", @@ -1318,7 +1318,7 @@ "name": "jvagent/leadgen", "archetype": "LeadGenAction", "tracked_directory_files": 20, - "tracked_directory_digest": "sha256:1e7d64246b31b1775e2f4694a0d129aa282d6fa656a5f14f88271653088242a4" + "tracked_directory_digest": "sha256:3d973e40af17d1413500dd8d38a461b402f53aa9c41cb773c276eec3cb4ec086" }, { "path": "jvagent/action/mcp/info.yaml", @@ -1326,8 +1326,8 @@ "sha256": "sha256:556282e31e4399046a4d081db544a51a5012f7437e0d3a087c7b08473037def0", "name": "jvagent/mcp", "archetype": "MCPAction", - "tracked_directory_files": 8, - "tracked_directory_digest": "sha256:8a1cbe7486e365c139c2400c1a995cca2b7c4f820baa79d514050b74f118f039" + "tracked_directory_files": 11, + "tracked_directory_digest": "sha256:c54bb47f607f69572fdeb0bc23755e7eb391920c0c94af1181fc3038c20767c6" }, { "path": "jvagent/action/mcp_oauth/info.yaml", @@ -1335,8 +1335,8 @@ "sha256": "sha256:c7e662950af0eedd604ed2d4f6c5f508e7d8d14a1245f6f2ed0e0bbcb50c455f", "name": "jvagent/mcp_oauth", "archetype": "MCPOAuthAction", - "tracked_directory_files": 8, - "tracked_directory_digest": "sha256:5071e9a1657a37d9330af66bbb2c754d070ce9e669e4507e6f89b8b5f093bade" + "tracked_directory_files": 9, + "tracked_directory_digest": "sha256:79805a8c9b64fae3ffe3651fb491b406b24a0c5fb262c7f3c5c4a52604778b47" }, { "path": "jvagent/action/microsoft/microsoft_excel_action/info.yaml", @@ -1489,7 +1489,7 @@ "name": "jvagent/orchestrator", "archetype": "OrchestratorInteractAction", "tracked_directory_files": 32, - "tracked_directory_digest": "sha256:3a09e66b9885fd063026b799ee38a977a8af36ff862c75b9ed794bab90dfc215" + "tracked_directory_digest": "sha256:729f3b3bb16e88c37d18e2b052be25533f1071b74f5f53d9631bb5fc940e4a93" }, { "path": "jvagent/action/page_context/info.yaml", @@ -1516,7 +1516,7 @@ "name": "jvagent/pageindex_google_drive_sync_action", "archetype": "PageIndexGoogleDriveSyncAction", "tracked_directory_files": 7, - "tracked_directory_digest": "sha256:314daafbdb6059d9f3230bf3555084310f6d16012d0063eb7d54fd63c5e678a6" + "tracked_directory_digest": "sha256:b3fee5529d8ef16a9ef5d271cb4fab753cc25a2ab8779e3d86ce69eafa7ce79f" }, { "path": "jvagent/action/pageindex_read/info.yaml", @@ -1543,7 +1543,7 @@ "name": "jvagent/reply", "archetype": "ReplyAction", "tracked_directory_files": 3, - "tracked_directory_digest": "sha256:4efe3cc77e7614415192293d6d66f2a1a7bb610eb05f0890c21bb8db7c957f34" + "tracked_directory_digest": "sha256:494b814f4c0a795c01fb999935414e7fb299bb4ffd7ae591dd3b07ff7fff5dbe" }, { "path": "jvagent/action/sentdm_broadcast/info.yaml", @@ -1615,7 +1615,7 @@ "name": "jvagent/elevenlabs_tts", "archetype": "ElevenLabsTTSAction", "tracked_directory_files": 2, - "tracked_directory_digest": "sha256:0486050f24c4817cc8ed221ff8a0c3e70e31641e69f5b52a96cc037a0140ca6f" + "tracked_directory_digest": "sha256:affa7b96fc536e44da4fb8aae8a5d60c9ac7c91d3b7689c1006eabb573804a77" }, { "path": "jvagent/action/ui/info.yaml", @@ -1696,7 +1696,7 @@ "name": "jvagent/whatsapp_action", "archetype": "WhatsAppAction", "tracked_directory_files": 29, - "tracked_directory_digest": "sha256:91b3f52eb6e45de0df83d18ba3eb6629aa8da34913d1f4606edcb2b4bf2393e2" + "tracked_directory_digest": "sha256:d107c5381d332ee31097cc187e74f104162cb1edf510370b97d4f8117b6e49c0" }, { "path": "jvagent/action/whatsapp_voice/info.yaml", @@ -1756,7 +1756,7 @@ } ], "tracked_directory_files": 11, - "tracked_directory_digest": "sha256:89ad2c0a2b659fce3b43117200f6c6471b803d6519d5f146bdd440caf80bbcbe" + "tracked_directory_digest": "sha256:e5ad944ce4b0fea366233fbe1dbf6767fa9a90c3c10bd3e9a8410252a67eeb68" }, { "path": "examples/jvagent_app/agents/jvagent/orchestrator_agent/agent.yaml", diff --git a/.planning/reference/configuration-keys.md b/.planning/reference/configuration-keys.md index 645515a65..470194506 100644 --- a/.planning/reference/configuration-keys.md +++ b/.planning/reference/configuration-keys.md @@ -219,7 +219,8 @@ See [`docs/ORCHESTRATOR.md`](../../docs/ORCHESTRATOR.md) for the full pattern. H | `grounding_max_deflections` | `2` | how many times a turn may be deflected for an unsupported source claim or an invented specific before the reply passes; `0` disables. The corpus a reply is checked against is the user message, history, this turn's tool results and the SESSION CONTEXT block, so a year or date read from the clock is grounded | | `repeat_guard_window` | `8` | how many recent tool calls the repeat guard remembers; a call repeating one in the window (same tool + args) is nudged once and ends the turn on the second repeat; a repeat after an error/timeout gets one retry | | `history_limit` | `4` | prior turns fed into the loop prompt (working context). The rolling memory window is the agent-level `interaction_limit`. Loop history omits `[EVENT]` lines unless `with_event` is on (ADR-0041, amended by ADR-0053) | -| `with_event` | `false` | include `[EVENT]` lines from PRIOR interactions in loop history — log annotations about what the agent did out of band ("Report form was sent to the user"). Off = today's prompt, byte for byte. The current interaction is always excluded from its own history (ADR-0053) | +| `with_event` | `false` | include `[EVENT]` lines from PRIOR interactions in loop history — log annotations about what the agent did out of band ("Report form was sent to the user"). Off = today's prompt, byte for byte. The current interaction is always excluded from its own history (ADR-0053). When on, `hide_correlation` (default true) omits harness correlation events | +| `hide_correlation` | `true` | when `with_event` is on, omit harness correlation `[EVENT]` lines (`action_name=harness` / `corr-*`). Default keeps product side-effect events while omitting turn correlation noise. Set `false` to include correlation. Ignored when `with_event` is false | | `history_statement_max_chars` | `4000` | per-statement cap on each replayed prior utterance/response, and on each `[EVENT]` line when `with_event` is on (history is resent every tick). `0` disables | | `lock_active_flow` | `true` | deterministic turn-lock to an active flow's IA; `false` = model-mediated continuation (ADR-0013) | | `planning` | `false` | surface the `update_plan` tool so the model records a multi-step plan that persists across turns (`AGENTIC_LOOP` task on the `TaskStore`) and resumes an interrupted turn; off = zero cost (ADR-0019) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 32e0e0a61..567653384 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,46 @@ and this project adheres to [PEP 440](https://peps.python.org/pep-0440/) / ## [Unreleased] +### Changed + +- **`IntroInteractAction` publishes dual-scope intro parameters.** On + `visitor.new_user` it now adds `intro.first_message` at both + `orchestration` and `response` scope with the configured `directive` text, so + the executive that authors the reply sees the custom intro (not only + ReplyAction compose). Agents should put the full intro in + `intro_interact_action.directive` and not duplicate it into + `orchestrator.system_prompt_extra`. + +- **Leadgen is LLM-driven.** Removed `ask_next` and the `pending_activation` guard; + capture/retrieve results now include `optional_fields` (the optional pool with + guidance) and `validation_errors`; the base procedure is generic (required first, + optional by guidance, content-first extraction, one question); validation is per + field and keeps valid values; declines bypass validators. Breaking for callers that + passed `ask_next`. + +- **Leadgen base procedure hardened.** A withheld value ("no organization", + "none", "n/a", "personal", "not provided") is captured as that field's + `decline_value` instead of the visitor's phrase; every value the message + supplies is captured in that same turn before any field question; and a `skipped` + (including sync thresholds not met), `no-op`, or `failed` sync is a hand-off that + has not run, so the reply says the request is saved but not yet sent instead of + closing on an acknowledgement. The open optional pool is capped at five keys + (`MAX_OPTIONAL_FIELDS`) so the directive stays a bounded menu. The optional ask + now names the need criterion ("the one this request needs") instead of a + permission, and the hand-off sentence is not repeated on later captures + (`_leadgen_handoff_stated`, reset when a snapshotted field changes). + `gap_fill.priority`, `qualification`, and `project_qualification` are accepted + and ignored. The failed-hand-off reply names `sync.sales_contact` (or the + action's `sales_contact`) only when one is configured. + ### Fixed +- **TTS media URLs work with authentication enabled.** `as_url=True` now returns + a signed proxy URL (`/p/{code}`) instead of the auth-protected + `/api/files/...` route, so WhatsApp/Messenger adapters and LLM providers can + fetch voice notes anonymously. Requires `JVSPATIAL_PROXY_ENABLED=true`; the + action logs a warning and falls back to the direct file route when proxy URLs + are unavailable. - **Handoff mode prompts corrected.** The consult/transfer trigger is now gated on the owning skill/tool having run ("after the owning skill or tool ran, the answer is not in this turn's tool results"), so it cannot fire before the first diff --git a/docs/ORCHESTRATOR.md b/docs/ORCHESTRATOR.md index c365229c5..eb91d1865 100644 --- a/docs/ORCHESTRATOR.md +++ b/docs/ORCHESTRATOR.md @@ -273,7 +273,10 @@ Interaction `[EVENT]` lines are omitted from loop history by default (ADR-0041) — they cost ~100+ tokens/tick when resent. Set `with_event: true` when the loop must know what the agent did out of band in earlier turns (ADR-0053); each line is then capped by `history_statement_max_chars` like any -other replayed statement. Bench a realistic turn with `--history N`. +other replayed statement. Harness correlation events (`action_name=harness` / +`corr-*`) stay out by default via `hide_correlation: true`; set +`hide_correlation: false` to include them. Bench a realistic turn with +`--history N`. **4. Cache accounting.** OpenAI caches long prefixes automatically and reports hits in `usage.prompt_tokens_details.cached_tokens`; Anthropic caches only up to diff --git a/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/example_leadgen/SKILL.md b/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/example_leadgen/SKILL.md index 92959a653..2c98a9e98 100644 --- a/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/example_leadgen/SKILL.md +++ b/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/example_leadgen/SKILL.md @@ -47,7 +47,6 @@ leadgen: guidance: Brief description of their project or need gap_fill: batch: true - priority: [name, phone, email, organization] sync: mode: on_capture min_fields: [name] diff --git a/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/product_inquiry_leads/SKILL.md b/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/product_inquiry_leads/SKILL.md index 3ed510972..46e9082f6 100644 --- a/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/product_inquiry_leads/SKILL.md +++ b/examples/jvagent_app/agents/jvagent/leadgen_agent/skills/product_inquiry_leads/SKILL.md @@ -40,7 +40,6 @@ leadgen: merge: true gap_fill: batch: true - priority: [name, phone, email, organization] # Sync config (mode, thresholds, destinations) lives in agent.yaml on the # jvagent/leadgen action — it's deployment/infra, not skill semantics. The # skill defines WHAT to capture; the agent defines WHERE it syncs. diff --git a/jvagent/action/google/google_action.py b/jvagent/action/google/google_action.py index ad6a1e6bf..b39b34276 100644 --- a/jvagent/action/google/google_action.py +++ b/jvagent/action/google/google_action.py @@ -17,6 +17,54 @@ _OIDC_SCOPES = frozenset({"openid", "profile", "email"}) +class GoogleAuthRequiredError(ValueError): + """An MCP OAuth credential exists but cannot be used for this Google API. + + Callers distinguish the three states that used to share one opaque + ``ValueError`` message: no credential at all, a credential whose granted + scopes cannot serve this action, and a refresh Google rejected. + """ + + def __init__( + self, + message: str, + service: str = "", + auth_url: str = "", + reason: str = "not_connected", + missing_scopes: Optional[List[str]] = None, + ) -> None: + # Every argument goes to BaseException.args so pickle and copy.copy + # can rebuild the instance. str() stays the human message. + scopes = list(missing_scopes or []) + super().__init__(message, service, auth_url, reason, scopes) + self.service = service + self.auth_url = auth_url + self.reason = reason + self.missing_scopes = scopes + + def __str__(self) -> str: + return str(self.args[0]) if self.args else "" + + +def _granted_scopes(token_data: Optional[Dict[str, Any]]) -> List[str]: + """Raw granted scopes from a stored token blob (string or list form).""" + raw = (token_data or {}).get("scopes") + if isinstance(raw, str) and raw.strip(): + return raw.split() + if isinstance(raw, list): + return [str(s).strip() for s in raw if str(s).strip()] + return [] + + +def _api_scopes(granted: List[str]) -> List[str]: + """Granted scopes that map to a Google API call (drops OIDC scopes).""" + return [ + s + for s in granted + if s.startswith("https://www.googleapis.com/auth/") and s not in _OIDC_SCOPES + ] + + def _normalize_expiry(value: Any) -> Optional[str]: """Coerce a stored expiry into the naive-UTC ISO form google-auth parses. @@ -190,24 +238,13 @@ async def _load_mcp_token( def _scopes_for_refresh(self, token_data: Optional[Dict[str, Any]]) -> List[str]: """This action's granted API scopes only (no OIDC / extra APIs).""" - raw = (token_data or {}).get("scopes") - granted: List[str] = [] - if isinstance(raw, str) and raw.strip(): - granted = raw.split() - elif isinstance(raw, list): - granted = [str(s).strip() for s in raw if str(s).strip()] - if not granted: + api = _api_scopes(_granted_scopes(token_data)) + if not api: return [] - api = { - s - for s in granted - if s.startswith("https://www.googleapis.com/auth/") - and s not in _OIDC_SCOPES - } wanted = [s for s in (self.SCOPES or []) if s] if wanted: return [s for s in wanted if s in api] - return [s for s in granted if s in api] + return api def _credentials_from_mcp_payload(self, token_data: Dict[str, Any]) -> Any: env_secret = self._resolve_client_secret_from_env() @@ -231,9 +268,13 @@ async def _get_credentials(self) -> Any: account_name, token_data, _node = await self._load_mcp_token() label = self.__class__.__name__ auth = self._mcp_auth_url() + service = self._MCP_SERVICE or "" if not token_data or not token_data.get("refresh_token"): - raise ValueError( - f"No valid MCP OAuth credentials for {label}. Authorize at {auth}" + raise GoogleAuthRequiredError( + f"Google credential for {label} is not connected. Authorize at {auth}", + service=service, + auth_url=auth, + reason="not_connected", ) refresh_scopes = self._scopes_for_refresh(token_data) @@ -264,15 +305,46 @@ async def _get_credentials(self) -> Any: client_id_hint=getattr(creds, "client_id", None), extra_details={"error_type": type(e).__name__}, ) - raise ValueError( + raise GoogleAuthRequiredError( f"OAuth2 credentials for {label} expired and could not " - f"be refreshed. Re-authorize at {auth}" + f"be refreshed. Re-authorize at {auth}", + service=service, + auth_url=auth, + reason="refresh_failed", ) from e return creds - raise ValueError( - f"No valid MCP OAuth credentials for {label}. Authorize at {auth}" + + # Expired (or unusable) with nothing safe to refresh with. When the + # stored grant is the cause, say which scope is missing: a partial + # consent still produces a refresh token, so "not authorized" alone + # sends the operator looking in the wrong place. + api = _api_scopes(_granted_scopes(token_data)) + missing = [s for s in (self.SCOPES or []) if s and s not in api] + if missing: + raise GoogleAuthRequiredError( + f"Google credential for {label} is missing required scope(s): " + f"{', '.join(missing)}. Re-authorize at {auth} and keep the " + "matching permission checked.", + service=service, + auth_url=auth, + reason="missing_scope", + missing_scopes=missing, + ) + raise GoogleAuthRequiredError( + f"No valid MCP OAuth credentials for {label}. Authorize at {auth}", + service=service, + auth_url=auth, + reason="not_connected", ) + async def assert_authorized(self) -> Any: + """Return usable credentials or raise ``GoogleAuthRequiredError``. + + Callers that must not start work on an unusable credential use this + instead of catching a generic error from ``get_service``. + """ + return await self._get_credentials() + async def _load_credentials(self) -> Any: """Alias for Docs and other callers that still use this name.""" return await self._get_credentials() diff --git a/jvagent/action/handoff_action/README.md b/jvagent/action/handoff_action/README.md index aab7c4d68..a4a04c830 100644 --- a/jvagent/action/handoff_action/README.md +++ b/jvagent/action/handoff_action/README.md @@ -757,10 +757,10 @@ Run one user/session, not one utterance per fresh user: Verify: ```bash -python3 "$HOME/.config/kilo/skills/jv_prompt/scripts/live_report.py" \ +python3 "$HOME/.config/kilo/skills/jv-prompt/scripts/live_report.py" \ --db --agent --channel web \ --run "|||||thanks" -python3 "$HOME/.config/kilo/skills/jv_prompt/scripts/db_read.py" \ +python3 "$HOME/.config/kilo/skills/jv-prompt/scripts/db_read.py" \ --db --entity HandoffQuestion --limit 5 ``` diff --git a/jvagent/action/interact/interact_walker.py b/jvagent/action/interact/interact_walker.py index 01d943727..5cbdb966e 100644 --- a/jvagent/action/interact/interact_walker.py +++ b/jvagent/action/interact/interact_walker.py @@ -548,7 +548,10 @@ async def _bootstrap_create_interaction( events.append( { "action_name": "harness", - "content": f"correlation_id={self.correlation_id}", + "content": ( + "internal turn correlation (not a request_id): " + f"{self.correlation_id}" + ), } ) self.interaction.events = events diff --git a/jvagent/action/intro/README.md b/jvagent/action/intro/README.md index a81796afa..b12da35d3 100644 --- a/jvagent/action/intro/README.md +++ b/jvagent/action/intro/README.md @@ -6,11 +6,18 @@ first reply. ## What it does On a new user's first message, `IntroInteractAction` contributes its intro text -as a **response-shaping parameter** (a "HOW" rule), not a standalone directive. -The single reply egress (`ReplyAction`) then weaves the greeting into the *same* -reply as whatever the rest of the turn produced — so a new visitor who opens with -a real question gets **one coherent answer that also introduces the agent**, -rather than a canned greeting stacked on top of a second, separate answer. +as **two parameters** with the same `directive` copy: + +- **`scope: orchestration`** (`key: intro.first_message`) — so the executive that + authors the reply directive sees the custom intro in its system prompt +- **`scope: response`** (`key: intro.first_message`) — so ReplyAction can still + weave the greeting if a bare directive slips through + +Neither is a standalone directive. The single reply egress (`ReplyAction`) then +weaves the greeting into the *same* reply as whatever the rest of the turn +produced — so a new visitor who opens with a real question gets **one coherent +answer that also introduces the agent**, rather than a canned greeting stacked +on top of a second, separate answer. - **First engagement only** — runs when `visitor.new_user` is true (first time this user appears under the agent's Memory). Skips returning users, session resumes, @@ -19,28 +26,35 @@ rather than a canned greeting stacked on top of a second, separate answer. the orchestrator's answer stays the single unit of content; the intro just makes the reply open with a brief self-introduction. - **Runs before the executive** — `weight = -300`, `always_execute = True`, so its - parameter is on the interaction before any downstream action queues a reply. + parameters are on the interaction before any downstream action queues a reply. ## Configure (agent.yaml) +Put the full custom intro in `directive` only. Do **not** duplicate it into +`orchestrator.system_prompt_extra` or reply custom parameters — the action +publishes the text into both scopes automatically. + ```yaml actions: - action: jvagent/intro_interact_action context: enabled: true - # Phrasing rule applied to the first reply. Written as a lead-in ("open - # your reply by …, then continue"), not a standalone message. + # Full custom intro + when to skip. Written as a lead-in ("open your + # reply by …, then continue"), not a standalone message. directive: >- - This is the visitor's first message: open your reply by briefly - introducing yourself by name and what you help with (one short - sentence), then continue naturally into the rest of your reply. + This is the visitor's first message: a greeting or small talk with no + request opens the reply with who you are by name and company, two or + three concrete examples of what you help with, and an invitation to + ask. A product, price, stock, policy, quote, or order message is not a + greeting: skip the introduction and answer directly. Never mention a + cutoff, model, or provider. ``` ## Attributes | Attribute | Type | Default | Description | |------------------|------|---------|-------------| -| `directive` | str | built-in lead-in intro | First-message self-introduction, applied as a response parameter | +| `directive` | str | built-in lead-in intro | First-message self-introduction, applied as orchestration + response parameters | | `weight` | int | `-300` | Runs before the Orchestrator (`-200`) | | `always_execute` | bool | `True` | Executes regardless of routing (gated internally by `new_user`) | @@ -48,8 +62,10 @@ actions: ``` new user's first message - → IntroInteractAction (weight -300): visitor.add_parameter({response: directive}) - → orchestrator / other actions queue the answer directive + → IntroInteractAction (weight -300): + add_parameter({key: intro.first_message, scope: orchestration, response: directive}) + add_parameter({key: intro.first_message, scope: response, response: directive}) + → orchestrator sees orchestration param → authors reply that includes the intro → ReplyAction: renders ONE reply — greeting woven in per the parameter, answer per the directive returning user → IntroInteractAction: skips (visitor.new_user is False) diff --git a/jvagent/action/intro/intro_interact_action.py b/jvagent/action/intro/intro_interact_action.py index 09dcd24b8..3b9e1c542 100644 --- a/jvagent/action/intro/intro_interact_action.py +++ b/jvagent/action/intro/intro_interact_action.py @@ -1,8 +1,9 @@ """IntroInteractAction for welcoming first-time users. This module provides IntroInteractAction, an InteractAction that detects -first-time users and adds an introductory response-shaping parameter for -ReplyAction to weave into the first reply. +first-time users and adds an introductory parameter for both the orchestrator +(so it authors the first reply with the custom intro) and ReplyAction (so +compose can still weave the greeting if a bare directive slips through). """ import logging @@ -12,20 +13,24 @@ from jvagent.action.interact.base import InteractAction from jvagent.action.interact.interact_walker import InteractWalker +from jvagent.action.parameters import SCOPE_ORCHESTRATION, SCOPE_RESPONSE if TYPE_CHECKING: pass logger = logging.getLogger(__name__) +_INTRO_PARAM_KEY = "intro.first_message" + class IntroInteractAction(InteractAction): """InteractAction that welcomes first-time users with an introductory message. IntroInteractAction: 1. Checks if the user is a first-time visitor to this agent (``visitor.new_user``) - 2. Adds an introductory response-shaping parameter for the responder - (ReplyAction) to weave into the reply + 2. Publishes the intro as orchestration-scoped and response-scoped parameters + so the executive sees the custom intro when authoring the reply, and + ReplyAction can still weave it at compose time 3. Only runs on first engagement with this agent (memory-scoped ``new_user``; skipped when resuming a session or when the user already exists under Memory) @@ -44,9 +49,10 @@ class IntroInteractAction(InteractAction): "or provider." ), description=( - "First-message self-introduction. Applied as a response-shaping " - "parameter (HOW) so the greeting is woven into the same reply as any " - "substantive answer, rather than emitted as a separate directive." + "First-message self-introduction. Applied as orchestration- and " + "response-scoped parameters (HOW) so the executive authors the intro " + "into the reply and compose can still weave it — rather than emitting " + "a separate directive." ), ) @@ -66,14 +72,14 @@ class IntroInteractAction(InteractAction): ) async def execute(self, visitor: "InteractWalker") -> None: - """Add a first-message self-introduction as a response-shaping parameter. + """Publish the first-message intro as orchestration + response parameters. - Runs at weight -300 (before the executive/router), so its parameter is on - the interaction before any downstream action queues an answer directive. - Contributing a *parameter* (HOW) rather than a *directive* (WHAT) lets the - single ReplyAction compose weave the greeting into the same reply as the - substantive answer, instead of emitting the intro as a separate mandated - section that reads as a second, disjoint blob. + Runs at weight -300 (before the executive/router), so both parameters are + on the interaction before any downstream action queues an answer + directive. Orchestration scope reaches the executive system prompt; + response scope reaches ReplyAction compose. Contributing a *parameter* + (HOW) rather than a *directive* (WHAT) lets one reply weave the greeting + into the substantive answer instead of a separate mandated section. Args: visitor: The InteractWalker visiting this action @@ -101,11 +107,24 @@ async def execute(self, visitor: "InteractWalker") -> None: await visitor.unrecord_action_execution() return - # Contribute the intro as a response-shaping parameter (not a - # directive) so it modulates HOW the reply opens rather than adding a - # separate mandated content section. Interaction-scoped, so it only - # affects this first reply. add_parameter sets action_name + saves. - await visitor.add_parameter({"response": self.directive}) + # Dual-scope: executive authors the intro into the reply directive; + # compose can still weave it if a bare greeting slips through. + # Interaction-scoped only for this first reply. add_parameter sets + # action_name + saves. + await visitor.add_parameter( + { + "key": _INTRO_PARAM_KEY, + "scope": SCOPE_ORCHESTRATION, + "response": self.directive, + } + ) + await visitor.add_parameter( + { + "key": _INTRO_PARAM_KEY, + "scope": SCOPE_RESPONSE, + "response": self.directive, + } + ) except Exception as e: logger.error( diff --git a/jvagent/action/leadgen/README.md b/jvagent/action/leadgen/README.md index 9366c5b47..bad9fcdd3 100644 --- a/jvagent/action/leadgen/README.md +++ b/jvagent/action/leadgen/README.md @@ -2,11 +2,12 @@ Conversational lead capture for orchestrator agents — interview-style skill foundation without turn-lock. -Capturing contact details is treated as a **standing goal**: after helping, the -agent proactively asks for the next missing field (name → email/phone), tied to -value, and eases off once the required fields are captured. Capture, retrieve, -and sync persist to a single `LeadRecord` per user (recalled across sessions on -return visits). +Capturing profile fields is treated as a **standing goal**: after helping, the +agent proactively asks for the next missing required field, tied to value, and +eases off once required fields are captured. Capture, retrieve, and sync persist +to a single `LeadRecord` per user (recalled across sessions on return visits). +Field names, hand-off wording, and sync gates come from the skill — the core is +agent-agnostic. ## Quick start @@ -19,12 +20,24 @@ return visits). write/append tool (flat file, spreadsheet, email, CRM, DB). A skill may instead declare its own `sync:` block to self-contain sync. +## Flexibility + +The action carries **no domain field vocabulary**: field names, `required`, +validators, `capture_only`, `merge`, `relevant_when`, `label`, sync gates, +`messages`, `channel_defaults`, and handlers come only from the skill's +`leadgen:` block. Domain rewriting (item lines, order vs quote intent) belongs +in skill hooks — never in the capture engine. `capture_only` fields are +captured only when volunteered. `phone_locale` resolves a built-in +`phone_` when no explicit `validator` is set (for example `GY`); an +unknown locale falls back to E164. Sync gates and channel autofill default to +empty. Refusals use the `decline_value` sentinel (any language). + ## Tools | Tool | Purpose | |------|---------| -| `leadgen__capture` | Save partial lead fields; returns `missing_fields` + `next_ask` + `gap_fill_priority`; auto-syncs when thresholds met | -| `leadgen__retrieve` | Load profile + `missing_fields` + `next_ask` + `field_reference` | +| `leadgen__capture` | Save partial lead fields; returns `status`, `fields_saved`, `fields`, `missing_fields`, `next_required`, `optional_fields`, `field_reference`, `validation_errors`, `sync_result`, and `response_directive` (sole ask); may also set a short observation `directive` hand-off marker for the sales-sentence guard; auto-syncs when thresholds met | +| `leadgen__retrieve` | Load profile + `missing_fields`, `next_required`, `optional_fields`, `field_reference`, and `response_directive` (sole ask; marker-only `directive` when a hand-off marker applies) | | `leadgen__status` | Progress snapshot | | `leadgen__sync` | Manual sync (`sync_mode: manual`) | @@ -33,6 +46,7 @@ return visits). - [frontmatter-schema.md](docs/frontmatter-schema.md) - [extending.md](docs/extending.md) - [thin-harness.md](docs/thin-harness.md) +- [troubleshooting.md](docs/troubleshooting.md) ## Reference diff --git a/jvagent/action/leadgen/SKILL.md b/jvagent/action/leadgen/SKILL.md index a16213127..bdc0e9d1e 100644 --- a/jvagent/action/leadgen/SKILL.md +++ b/jvagent/action/leadgen/SKILL.md @@ -13,52 +13,83 @@ allowed-tools: # Standard Leadgen Procedure -Capturing the visitor's contact details is a **primary, standing goal of every conversation** — treat it as a staple, not an afterthought. Keep genuinely helping the visitor, and in the same breath keep steering toward their **name** and a way to reach them (**email or phone**). The server validates, persists, and auto-syncs when configured — you decide **when** to capture, not how storage works ([thin harness](docs/thin-harness.md)). +The skill's field definitions and the runtime catalogue are the question set. The action validates, persists, and syncs; you choose the next best question and extract every value the visitor supplies. -## When to call `leadgen__capture` +## Opening and cycle -Call whenever the user's **latest message** provides or refuses lead information: +A request opens when the skill's context shows its intent; a greeting, small talk, or a standalone information question does not. The extended skill supplies the concrete business triggers. When the skill provides a prepare tool, use it to start or continue; otherwise use `leadgen__retrieve` for context. Never use retrieve to open a turn after a hand-off; the next cycle starts with the skill's prepare tool when it provides one. -- Name, company, email, phone, project details, product interest -- **Refusals** — use `decline_value` from `field_reference` (e.g. `email="N/A"`, `organization="Personal"`) -- Corrections — capture updated values in the same turn +## Read the catalogue -Do **not** call with empty arguments or when nothing changed. +`field_reference` is the whole field set in ask order, each with `guidance`, `required`, `decline_value`, `relevant_when`, and `capture_only`. `fields` holds the values already saved; `missing_fields` the required keys still empty; `next_required` the one required key to ask now; `optional_fields` the open optional keys once required is complete. After capture or retrieve ends the tool chain, Core delivers the next-step instruction for the reply — do not invent a different field, a second refusal policy, or a substitute close. Never ask a key that is already in `fields`. Guidance may carry `Why` (why the answer matters), `When` (the condition and moment to ask), `Group`, `Prereq`, `Capture-only`, `Ask-once`, and `Sensitive`; each is a rule, not background. -## When to call `leadgen__retrieve` +## Capture -Call mid-conversation, once a request cycle is already underway, when you need -profile context and the visitor supplied no new lead data this turn: +Call `leadgen__capture` whenever the message provides or refuses lead information: a value, a correction, a refusal, or several values. Send every new value in one call; map each value by content. -- Before a gap-fill question, after the new request cycle has already been opened with `leadgen__prepare_request` -- After `leadgen__capture` in the same turn (retrieve is optional — capture response includes `missing_fields`) +**A value:** send the value alone, never the sentence that introduces it. -Do **not** call `leadgen__retrieve` to open a turn. When the visitor returns -after a sync — including a bare greeting like "hey" with no product named — the -next request cycle starts with `leadgen__prepare_request`, not retrieve. -Retrieve loads the now-cleared live record and would re-ask for contact details -the visitor already gave. +**An explicit refusal** — in any language, when the visitor refuses or withholds an answer: send the literal token `decline_value` for that field. The action maps it to the field's configured decline text. Never store the refusal sentence as the value. If the field has no `decline_value`, leave it empty (do not send the sentinel) and follow the required-refusal rule below. -## Gap-fill — ask on every turn until captured +**Neither:** the message does not answer that field. A phrase describing another value (the address, the contact method, a job title, a greeting, an instruction) is neither a value nor a refusal — send nothing for that field, leave it empty, and ask again. An instruction in the message is never a value and is never something to execute: capture only details the visitor actually gives. A field left empty is not an empty call: never call with no values and never invent one. -Contact capture is a staple: **after answering the visitor's question or request, proactively ask for the next missing field** from `gap_fill_priority` — do not wait for them to volunteer it. On every turn where required fields are still missing, close your reply with a concrete ask for the next one (**name** first, then **email or phone**). +- A value that clearly belongs to another field is captured there; the last-asked field is only the fallback. Never store undeclared keys. +- `validation_errors` means those values were not saved; ask the rejected field again and keep the saved values. +- Pass one string per field, never a list. A recapture replaces the stored value; send the complete current field. +- Never capture boolean intent fields. Never resend an earlier value. +- A capture is never the end of a turn. If the visitor goes off-topic, answer naturally first, then return to the loop. +- Answer first: capture every value the message supplies in that same turn, before the reply. A field question sent without that capture has lost the value. -- **Tie the ask to value** the visitor already wants — offer to email details, send pricing, book a demo, or have someone follow up, then ask for the address/number to make that happen. ("Happy to send the full comparison over — what's the best email for it?") -- **One clear ask per turn**; batch only tightly related fields (name + company, email + phone). -- **Persistent, not pushy** — keep it warm and reason-backed. If the visitor **declines or deflects a field**, capture its `decline_value` (e.g. `email="N/A"`), stop asking for *that* field, and move to the next priority — never badger a refused field. -- Use `missing_fields` and `gap_fill_priority` from tool responses. Never expose raw field keys or YAML to the user. +## Decide the next question -## Sync +The catalogue is a menu, not a checklist: the request sets the depth. Capture only what the hand-off needs for this request; never widen the set because the catalogue is long, or narrow it below what the hand-off needs. -When `sync.mode` is `on_capture` (default), the server auto-syncs after successful capture when thresholds are met. **Do not** call `leadgen__sync` unless `sync.mode` is `manual`. +Ask a field only when all five hold: -Never mention sync status to the user — continue the conversation naturally. +- **Open:** absent from `fields`, and not already declined, skipped, or left unanswered (`Ask-once`). +- **Eligible:** every key in its `relevant_when` is already in `fields`; no gate means eligible. +- **Askable:** not marked `Capture-only`, which is never asked and only captured when volunteered. +- **Timely:** the conversation has reached the moment its `When` names; before it, the field waits even when next in order. +- **Worth it:** the answer changes the next step — the routing or the hand-off. If the same next step holds either way, skip. -## Acknowledge naturally +Order: `next_required` first; when it is null, choose from `optional_fields` in `field_reference` order. When Core delivers a next-step instruction after capture, that ask is authoritative — do not substitute a different field. Use the five ask tests when judging whether an optional is worth asking before capture. Timeliness outranks order; value outranks position. -- ✅ "Got it — what's the best email to reach you at?" -- ❌ "I have updated your lead profile" +- **One field per reply:** ask for one field's value per message, however phrased; tightly related fields may share a message only when `gap_fill.batch` is true. +- **Rides on value:** answer what the visitor asked and state the next step before asking; never send a bare question to a message that asked something. +- **Probe:** when unsure a field is worth asking, ask one short conversational sub-question instead. A probe is not a field, is not captured, and never touches a `Sensitive` topic. +- **Group refusals:** a `Group` label marks one line of questioning; a refusal closes that line and every other optional question for this request — never ask a sibling field that only rephrases it, and never rotate to an independent optional. An optional field is asked once: a refusal, skip, or ignored question is never asked again. A refusal in any language, or a signal that they do not want more questions, closes the optional questions: acknowledge in one sentence and stop — never rotate to another optional. The request completes without it. Send `decline_value` for the refused field. +- **Required refusals:** a required field with no `decline_value` is needed to file. If refused, do not re-ask in that turn — reply “ is needed to file this request — would you like to continue or cancel?” If the visitor answers elsewhere, capture that value, acknowledge, and ask the required field again in different words; if still refused, repeat the sentence. Continue means ask once more in fresh words; cancel means the skill's cancel tool, acknowledge, and end. Never store a refusal as the value. A field the message does not answer is asked again; only an explicit refusal takes the continue/cancel sentence. +- **Confirmation:** never repeat a question verbatim; while a required field is still missing, use no receipt or possession wording. +- **Sensitive:** ask only when the next step needs it and the timing is right, and never in a probe. A required `Sensitive` field takes its normal place in the required order; ask it plainly, on its own, like any other required field. -## Never expose internals +Stop and answer, confirm, or close when required fields are complete and no field passes the five tests; when the visitor says they have answered enough, wants to proceed now, declines the line, or signals they do not want more questions; or when another question would delay a hand-off. Never fill the silence with one more question; a field that passes the tests is asked, not skipped for brevity. -Do not send raw profile JSON, field names like `order_items`, digests, or `sync_result` to the user. +`sync-complete` is not a close: it authorizes the hand-off wording only. + +## Retrieve and status + +Call `leadgen__retrieve` mid-conversation for profile context when the visitor supplied no new lead data; captures already return the catalogue. Do not use it to open a turn — after a hand-off the skill's prepare tool starts the next cycle. `leadgen__status` gives progress; it is not a capture. + +## Close and hand-off + +Close only when the stop conditions above hold, or the visitor asked to skip the rest. Use the skill's `messages` wording when set; otherwise treat the entity as a request, the recipient as the team, and the visitor as the visitor. + +- On `sync-complete`: state the next step in one sentence: the request is with the team, and they will contact the visitor on the contact the visitor gave. Never repeat the visitor's email address or phone number in the reply. Do not use vague status phrases. When the delivered next-step names one optional field, ask it — one field, one question, in the visitor's terms — then close; when it names none, close with no question. Skills that hand off to sales set `messages.handoff_team` accordingly. +- After the hand-off sentence was already stated: do not restate that the request is with the team — even when turn context says a hand-off completes this turn. Obey the delivered next-step: briefly acknowledge the new detail in natural wording (no fixed opener), then ask the next field it names. When it names none, close in one thank + follow-up sentence (the team will follow up on the contact already given) — never a bare acknowledgement alone, never a clarifying or invented question (quantity, size, delivery address, or anything not named). +- When the delivered next-step says ask none / ask no further field: the reply is only the required close — never add a follow-up question. +- A `skipped` (including sync thresholds not met), `no-op`, or `failed` sync means the hand-off has not run: say in one sentence that the request is saved but not yet sent, name what is still missing in the visitor's own terms, and offer the contact when the next-step names one. Never close on an acknowledgement of the value, and never say it was sent, received, or passed on. +- A `sync-complete` with a failed notification: the request is with the team; do not say they were notified. +- `no destinations`: a draft; a blocked capture or destination error: a failed hand-off; say so and offer the contact when the next-step names one. +- Do not expose internal sync status otherwise. + +## Cancellation and correction + +A withdrawal is never a field value. Do not capture, sync, or ask another field: use the skill's cancel tool, acknowledge in one sentence, and end. The contact profile is kept; a later greeting does not restart. Never say the request was forwarded, sent, or passed on after a cancellation. A correction is captured on the same turn and replaces the stored value; never resend an earlier value. + +## Voice and internals + +Acknowledge naturally when it helps; do not thank the visitor every turn, do not reuse the same opener, and name the value only when it adds clarity. Never say you updated a profile, a record, or the request. Do not send raw profile data, field keys, digests, or `sync_result`. + +## Sync modes + +`sync.mode` is `on_capture`, `on_complete`, or `manual`. Do not call `leadgen__sync` unless manual; the action auto-syncs when thresholds are met. diff --git a/jvagent/action/leadgen/docs/extending.md b/jvagent/action/leadgen/docs/extending.md index dd4831e1f..69b30e364 100644 --- a/jvagent/action/leadgen/docs/extending.md +++ b/jvagent/action/leadgen/docs/extending.md @@ -39,3 +39,10 @@ allowed-tools: ```bash jvagent skill create-leadgen ``` + +## Agent-agnostic tips + +- Declare `sync.min_fields` / `require_any` explicitly; core defaults are empty. +- Override `messages` for non-sales hand-off wording (`handoff_team`, `contact_label`). +- Set `channel_defaults: {}` when the skill has no contact fields to autofill. +- Refusals: the model sends the sentinel `decline_value` (any language); do not rely on English phrase lists. diff --git a/jvagent/action/leadgen/docs/frontmatter-schema.md b/jvagent/action/leadgen/docs/frontmatter-schema.md index 79ae9ac2c..be7f44e2e 100644 --- a/jvagent/action/leadgen/docs/frontmatter-schema.md +++ b/jvagent/action/leadgen/docs/frontmatter-schema.md @@ -10,6 +10,11 @@ always-active: true leadgen: title: My Lead Capture summary: Optional description + messages: + entity: request # what is being filed + handoff_team: team # who receives it after sync (e.g. "sales team") + contact_label: contact # label when offering sales_contact + visitor: visitor # how the user is referred to fields: - key: full_name required: true @@ -23,19 +28,36 @@ leadgen: required: false validator: phone phone_locale: E164 # or GY + - key: severity + validator: enum + validator_args: + choices: [low, medium, high] - key: quote_items merge: true + - key: project_budget + guidance: Stated budget once a project is described + relevant_when: + any_present: [project_description] gap_fill: batch: true - priority: [full_name, phone, email, organization] + # priority, qualification, and project_qualification are ignored. + # Ask order is the field declaration order. + # Omitted or {} → no channel autofill. Skills that want WhatsApp + # phone/full_name backfill must declare it explicitly. + channel_defaults: + whatsapp: + phone: user_id + full_name: user_name sync: mode: on_capture # on_capture | on_complete | manual - min_fields: [full_name] + min_fields: [full_name] # empty default — declare gates you need require_any: [phone, email] + sales_contact: "" # optional; omitted from the failed-hand-off reply when empty + timezone: UTC # IANA zone for {last_updated} # Destination-agnostic: any MCP server + tool. Below is a flat file; a # spreadsheet, email, CRM, or DB is the same shape (only server/tool/args # change). Templates: {profile_json}, {profile_row}, {profile_keys}, - # {user_id}, {}. + # {user_id}, {last_updated}, {}. destinations: - server: leadfile # any configured MCP server (see MCPAction) mode: mcp @@ -57,17 +79,53 @@ allowed-tools: [] |-----|------|-------------| | `key` | string | Canonical field name (required) | | `guidance` | string | Model-facing description | -| `required` | bool | Included in gap-fill / on_complete sync | +| `label` | string | Short visitor-facing name for required-refusal directives when guidance is long | +| `required` | bool | Included in `missing_fields` and the sync gates | +| `capture_only` | bool | Captured only when the visitor volunteers it; never asked and never offered in `optional_fields` (use for request lines and qualification fields the model must not chase) | | `aliases` | list | Alternate names for capture | -| `validator` | string | Built-in: `email`, `phone`, `phone_e164`, `phone_gy`, `person_name` | -| `validator_args` | map | Passed to validator | -| `decline_value` | string | Value when user refuses (stops re-asking) | +| `validator` | string | Built-in: `email`, `phone`, `phone_e164`, `phone_gy`, `person_name`, `enum`, `regex`, `number`, `date`. Unknown names fail at parse time. | +| `validator_args` | map | Passed to validator (`choices` for enum, `pattern`/`flags` for regex, `min`/`max` for number, `formats` for date) | +| `decline_value` | string | Stored when the model sends the sentinel `decline_value` (refusal in any language) | | `merge` | bool | Comma-merge list fields on update | -| `phone_locale` | string | `GY` forces Guyana normalization | +| `phone_locale` | string | Resolves a built-in `phone_` validator on any field (`GY`, `E164`); unknown locale falls back to E164 | +| `relevant_when` | map | Optional gate: `{ any_present: [keys], not_declined: [keys], values_not: { key: [banned…] } }` — askable only once a listed key is filled, never while a `not_declined` key holds its own `decline_value`, and never while a `values_not` key holds a banned value; the gate travels in `field_reference` | + +## Messages + +| Key | Default | Description | +|-----|---------|-------------| +| `entity` | `request` | Noun for what is being filed | +| `handoff_team` | `team` | Who receives the hand-off | +| `contact_label` | `contact` | Label when offering `sales_contact` | +| `visitor` | `visitor` | How the user is referred to | + +## Channel defaults + +Map channel → field key → source (`user_id` | `user_name`). Omitted or `{}` → no autofill. + +### Capture catalogue (server-nominated ask) + +Tool results expose `fields` (saved values), `missing_fields` (required keys still empty), +`next_required` (the single required key to ask now, derived from `missing_fields[0]`), +`optional_fields` (open optional keys whose `relevant_when` passes), `field_reference` (every +declared field in ask order, with guidance and `required`), and `response_directive` (the sole +ask or hand-off instruction for this reply — orchestrator delivers it to ReplyAction as framed +prose; do not teach this key name in agent SOP). Observation `directive`, when present, is only a +short hand-off marker (`Hand-off is complete.` / `Hand-off already stated.`) for the +orchestrator sales-sentence guard — not a duplicate of the ask. There is no persisted ask pointer +and no `ask_next` stamp. `gap_fill.priority`, `qualification`, and `project_qualification` are +accepted and ignored so older skills still parse. A failed hand-off names `sync.sales_contact` +only when that value is set (or `sales_contact` on the action), using `messages.contact_label`. +`_leadgen_handoff_stated` is paired with a snapshot of the handed-off fields; clearing or +replacing one of those values states the hand-off again. + +Refusals: the model sends the literal token `decline_value` for a refused field (any language). The action maps it to the field's configured decline text and closes optional questions. ## Sync template tokens -`{user_id}`, `{profile_json}`, `{profile_keys}`, `{profile_row}`, `{}` +`{user_id}`, `{profile_json}`, `{profile_keys}`, `{profile_row}`, `{last_updated}`, `{}` + +`{last_updated}` uses `sync.timezone` (IANA, default `UTC`). ## Sync location: skill frontmatter vs the action @@ -82,7 +140,7 @@ deployment/infra, so the skill defines *what* to capture and the agent defines context: enabled: true sync_mode: on_capture # on_capture | on_complete | manual - sync_min_fields: [full_name] + sync_min_fields: [full_name] # empty by default — set gates you need sync_require_any: [phone, email] sync_destinations: - server: leadfile # any configured MCP server @@ -97,7 +155,8 @@ Precedence: if the **skill** declares sync destinations, its `sync:` block gover in full. Otherwise the **action-level** sync config (`sync_mode` / `sync_min_fields` / `sync_require_any` / `sync_destinations`) governs the whole sync. `LeadGenAction.default_fields` likewise supplies fields -when the skill declares none. +when the skill declares none. Sync `min_fields` / `require_any` default to empty +so non-CRM agents are not gated on `full_name` / `phone` / `email`. > Internal, underscore-prefixed keys (e.g. the stored sync digest) are excluded > from every template and from the change-detection digest, so they never sync out diff --git a/jvagent/action/leadgen/docs/thin-harness.md b/jvagent/action/leadgen/docs/thin-harness.md index f4cf778b6..5447c2c05 100644 --- a/jvagent/action/leadgen/docs/thin-harness.md +++ b/jvagent/action/leadgen/docs/thin-harness.md @@ -13,7 +13,8 @@ - `LeadRecord` persistence - Auto-sync threshold evaluation and MCP dispatch - Digest dedup -- Never classify user intent in action code +- Never classify user intent in action code (no order/buy heuristics, no + domain item-line rewriting — those belong in skill `post_capture` hooks) ## Invariants diff --git a/jvagent/action/leadgen/engine.py b/jvagent/action/leadgen/engine.py index 45f21de76..4bb68645a 100644 --- a/jvagent/action/leadgen/engine.py +++ b/jvagent/action/leadgen/engine.py @@ -5,7 +5,7 @@ import json import logging import time -from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, cast from jvagent.tooling.context import get_tool_visitor @@ -13,7 +13,9 @@ from .hooks import HookExecutionContext, call_hook from .spec import LeadGenSpec, fields_reference from .store import LeadRecord -from .validators import run_validator +from .validators import locale_validator, run_validator + +DECLINE_SENTINEL = "decline_value" if TYPE_CHECKING: from .leadgen_action import LeadGenAction @@ -68,6 +70,7 @@ def merge_spec_with_action_defaults( validator=str(cfg.get("validator", "") or ""), decline_value=cfg.get("decline_value"), merge=bool(cfg.get("merge", False)), + capture_only=bool(cfg.get("capture_only", False)), ) ) @@ -85,73 +88,81 @@ def merge_spec_with_action_defaults( min_fields=list(action.sync_min_fields), require_any=list(action.sync_require_any), destinations=list(action.sync_destinations), + sales_contact=merged.sync.sales_contact or action.sales_contact, + timezone=merged.sync.timezone or "UTC", ) + elif not merged.sync.sales_contact and action.sales_contact: + merged.sync.sales_contact = action.sales_contact return merged -def canonicalize_fields(raw: Dict[str, Any], spec: LeadGenSpec) -> Dict[str, Any]: +def canonicalize_fields( + raw: Dict[str, Any], spec: LeadGenSpec +) -> tuple[Dict[str, Any], List[str]]: + """Map aliases to declared keys. Return undeclared keys separately. + + Undeclared keys are not stored. Callers surface them in + ``validation_errors`` so a dropped value is visible to the model. + """ alias_map = spec.alias_map() out: Dict[str, Any] = {} + unknown: List[str] = [] known = set(spec.field_keys()) for key, value in raw.items(): if key.startswith("_"): out[key] = value continue clean = key.strip().lower().replace(" ", "_").replace("-", "_") - canonical = alias_map.get(clean, key if key in known else clean) - if canonical in known or canonical == key: + canonical = alias_map.get(clean, key) + if canonical in known: out[canonical] = value else: - out[key] = value - return out + unknown.append(str(key)) + return out, unknown async def validate_fields( fields: Dict[str, Any], spec: LeadGenSpec -) -> tuple[Dict[str, Any], Optional[str]]: +) -> tuple[Dict[str, Any], Dict[str, str]]: + """Validate each supplied field; keep valid values and collect per-field errors.""" validated: Dict[str, Any] = {} + errors: Dict[str, str] = {} for key, value in fields.items(): if key.startswith("_"): validated[key] = value continue fdef = spec.get_field(key) if fdef is None: - validated[key] = value continue str_val = str(value).strip() if value is not None else "" - if not str_val and fdef.decline_value is not None: - validated[key] = fdef.decline_value + if not str_val: + if fdef.decline_value is not None: + validated[key] = fdef.decline_value + continue + if str_val.strip().lower() == DECLINE_SENTINEL: + if fdef.decline_value is not None: + validated[key] = str(fdef.decline_value) + else: + errors[key] = "this field has no decline value; provide a value" + continue + if fdef.decline_value is not None and str_val == str(fdef.decline_value): + validated[key] = str_val continue - validator_name = fdef.validator - if fdef.key == "phone" and fdef.phone_locale == "GY": - validator_name = "phone_gy" - elif fdef.key == "phone" and not validator_name: + # Explicit validator wins; phone_locale is a fallback when unset. + validator_name = fdef.validator or locale_validator(fdef.phone_locale) + if fdef.phone_locale and not validator_name: validator_name = "phone_e164" if validator_name: normalized, err = run_validator( validator_name, str_val, fdef.validator_args ) if err: - return {}, err + errors[key] = err + continue validated[key] = normalized else: validated[key] = str_val - return validated, None - - -def next_ask(spec: LeadGenSpec, missing_fields: List[str]) -> Optional[str]: - """The single next contact field to ask for, in gap-fill priority order. - - Returns the highest-priority still-missing field so the model has an explicit - target for the standing gap-fill ask, or ``None`` when nothing is missing. - """ - if not missing_fields: - return None - missing = set(missing_fields) - for key in spec.gap_fill.priority: - if key in missing: - return key - return missing_fields[0] + return validated, errors def apply_merge_fields( @@ -218,7 +229,11 @@ async def maybe_auto_sync( return {"status": "no-op", "reason": "no destinations configured"} results, any_success = await sync_mod.sync_to_destinations( - action, destinations, profile_data, user_id + action, + destinations, + profile_data, + user_id, + timezone_name=sync_cfg.timezone or "UTC", ) if any_success: updated = dict(profile_data) @@ -229,43 +244,476 @@ async def maybe_auto_sync( return {"status": status, "results": results} -def capture_state(record: Any, spec: LeadGenSpec) -> Dict[str, Any]: - """The record snapshot every capture result carries, whatever its status. +def _field_filled(fields: Dict[str, Any], key: str) -> bool: + val = fields.get(key) + if val is None: + return False + return bool(str(val).strip()) + + +def _norm_phrase(value: str) -> str: + """Lowercase, strip surrounding punctuation and collapse whitespace.""" + text = str(value or "").strip().lower() + text = text.rstrip(".!?,;: ") + return " ".join(text.split()) + + +def _declined_keys(fields: Dict[str, Any], spec: LeadGenSpec) -> set: + """Keys whose stored value equals their own ``decline_value``.""" + out: set = set() + for fdef in spec.fields: + if fdef.decline_value is None: + continue + val = fields.get(fdef.key) + if val is None: + continue + if _norm_phrase(str(val)) == _norm_phrase(str(fdef.decline_value)): + out.add(fdef.key) + return out + + +def _relevant_when_met( + fields: Dict[str, Any], fdef: Any, declined: Optional[set] = None +) -> bool: + """True when the field has no gate, or its gate is satisfied. + + ``any_present`` needs one listed key filled. ``not_declined`` needs every + listed key filled and none of them holding its own ``decline_value``. + """ + gate = getattr(fdef, "relevant_when", None) or None + if not gate: + return True + any_present = gate.get("any_present") or [] + if any_present and not any( + _field_filled(fields, k) and (declined is None or k not in declined) + for k in any_present + ): + return False + for key in gate.get("not_declined") or []: + if not _field_filled(fields, key): + return False + if declined is not None and key in declined: + return False + return True + + +MAX_OPTIONAL_FIELDS = 5 + + +def _is_decline_sentinel(value: Any) -> bool: + return str(value or "").strip().lower() == DECLINE_SENTINEL + + +def payload_has_refusal(fields: Dict[str, Any], spec: LeadGenSpec) -> bool: + """True when this capture used the language-agnostic decline sentinel.""" + for key, value in fields.items(): + if not _is_decline_sentinel(value): + continue + fdef = spec.get_field(key) + if fdef is not None and fdef.decline_value is not None: + return True + return False + + +def _apply_channel_defaults( + raw_fields: Dict[str, Any], + spec: LeadGenSpec, + user: Any, + channel: str, +) -> None: + """Fill declared fields from channel identity when the skill maps them.""" + mapping = (spec.resolved_channel_defaults().get(channel.lower()) or {}).items() + known = set(spec.field_keys()) + for field_key, source in mapping: + if field_key not in known: + continue + if raw_fields.get(field_key): + continue + if source == "user_id" and getattr(user, "user_id", None): + raw_fields.setdefault(field_key, user.user_id) + elif source == "user_name" and getattr(user, "name", None): + raw_fields.setdefault(field_key, user.name) + + +def optional_field_keys( + fields: Dict[str, Any], spec: LeadGenSpec, *, ignored: Sequence[str] = () +) -> List[str]: + """Open optional keys that pass their ``relevant_when`` gate. + + Keys only: each key's guidance stays in ``field_reference``, so the payload + never repeats the same text twice. The list is capped at + ``MAX_OPTIONAL_FIELDS`` so the directive stays a bounded menu. + """ + declined = _declined_keys(fields, spec) + out: List[str] = [] + for fdef in spec.fields: + if fdef.required: + continue + if getattr(fdef, "capture_only", False): + continue + if _field_filled(fields, fdef.key): + continue + if fdef.key in ignored: + continue + if not _relevant_when_met(fields, fdef, declined): + continue + out.append(fdef.key) + return out[:MAX_OPTIONAL_FIELDS] + + +def failed_sync_directive( + sales_contact: str = "", + *, + contact_label: str = "contact", + entity: str = "request", + visitor: str = "visitor", +) -> str: + """Hand-off did not run. Name a contact only when one is configured.""" + contact = str(sales_contact or "").strip() + label = str(contact_label or "contact").strip() or "contact" + ent = str(entity or "request").strip() or "request" + who = str(visitor or "visitor").strip() or "visitor" + offer = f" Offer the {label} {contact}." if contact else "" + return ( + f"The {ent} is saved but not yet sent. In one sentence say that, " + f"and name anything still needed in the {who}'s own words." + + offer + + " Never say sent, received, forwarded, or passed on. Ask no further field." + ) + + +#: Default failed-hand-off wording when no contact is configured. +SYNC_FAILED_DIRECTIVE = failed_sync_directive() + +_RELAY_PREFIX = "Tell the user or ask the user: " +_HANDOFF_COMPLETE_PREFIX = "Hand-off is complete. " +#: Marks a directive that follows a hand-off already stated this conversation. +#: The orchestrator reads this to disarm the sales-sentence guard, which would +#: otherwise order the opposite of what the directive orders. +HANDOFF_ALREADY_STATED_PREFIX = "Hand-off already stated. " +#: Observation-only markers (no ask prose). Loop scans these to arm/disarm the +#: sales-sentence guard; the full ask lives only on ``response_directive``. +HANDOFF_COMPLETE_MARKER = "Hand-off is complete." +HANDOFF_ALREADY_STATED_MARKER = "Hand-off already stated." + + +def to_response_directive(instruction: str) -> str: + """Frame a leadgen instruction for ReplyAction terminal delivery. + + Strips framework hand-off markers (``Hand-off is complete.`` / + ``Hand-off already stated.``) and leads with the relay prefix so the + orchestrator compose path delivers ask-none / next-ask in full. Markers + stay on observation ``directive`` only — see ``attach_reply_directives``. + """ + text = str(instruction or "").strip() + if not text: + return "" + if text.startswith(_HANDOFF_COMPLETE_PREFIX): + text = text[len(_HANDOFF_COMPLETE_PREFIX) :].strip() + elif text.startswith(HANDOFF_ALREADY_STATED_PREFIX): + text = text[len(HANDOFF_ALREADY_STATED_PREFIX) :].strip() + if text.casefold().startswith("tell the user"): + return text + return f"{_RELAY_PREFIX}{text}" + + +def attach_reply_directives(target: Dict[str, Any], instruction: str) -> None: + """Split hand-off markers onto ``directive``; put the full ask on ``response_directive``. + + ``directive`` is marker-only when a hand-off marker applies (sales-sentence + guard). Otherwise it is omitted so capture results do not duplicate the ask. + """ + text = str(instruction or "").strip() + if text.startswith(_HANDOFF_COMPLETE_PREFIX): + target["directive"] = HANDOFF_COMPLETE_MARKER + elif text.startswith(HANDOFF_ALREADY_STATED_PREFIX): + target["directive"] = HANDOFF_ALREADY_STATED_MARKER + else: + target.pop("directive", None) + target["response_directive"] = to_response_directive(text) + + +# Internal, underscore-prefixed so both are excluded from the sync digest and +# from every destination template (see ``sync.compute_digest``). +HANDOFF_STATED_KEY = "_leadgen_handoff_stated" +HANDOFF_SNAPSHOT_KEY = "_leadgen_handoff_fields" + + +def _public_fields(profile: Dict[str, Any]) -> Dict[str, Any]: + return {k: v for k, v in profile.items() if not str(k).startswith("_")} + - Same keys and the same ``_`` filter as :func:`handle_retrieve`, so a caller - reads one set of keys no matter which tool produced the payload — and no - matter whether this particular call wrote anything. Built here rather than - inline so the two exits from ``handle_capture`` cannot drift apart, which - is the whole point of returning the merged record. +def handoff_already_stated(profile: Dict[str, Any]) -> bool: + """True while the handed-off field values are still the ones we stated for. + + A later capture that only adds fields stays inside the same hand-off. A new + cycle that clears or replaces a snapshotted value states the hand-off again. + A flag with no snapshot (written before snapshots existed) does not count. + """ + if not profile.get(HANDOFF_STATED_KEY): + return False + snapshot = profile.get(HANDOFF_SNAPSHOT_KEY) + if not isinstance(snapshot, dict) or not snapshot: + return False + public = _public_fields(profile) + return all(public.get(key) == value for key, value in snapshot.items()) + + +def handoff_directive( + optional_keys: List[str], + *, + already_stated: bool = False, + just_declined: bool = False, + stop_optional: bool = False, + entity: str = "request", + visitor: str = "visitor", + handoff_team: str = "team", +) -> str: + """Structural hand-off instruction. Wording of the sentence lives on the skill.""" + ent = str(entity or "request").strip() or "request" + who = str(visitor or "visitor").strip() or "visitor" + team = str(handoff_team or "team").strip() or "team" + if just_declined: + if already_stated: + return ( + HANDOFF_ALREADY_STATED_PREFIX + + "Do not repeat the hand-off sentence. Close in one natural " + "sentence: thank them for stopping and confirm the " + f"{team} will follow up using the contact already given. " + "Ask no field — no question mark, no invented field (delivery " + "address or anything not named here)." + ) + return ( + "Hand-off is complete. Use the skill's hand-off sentence " + f"(the {ent} has been sent to the {team}), then ask no field — the " + f"{who} declined or does not want more questions. If they supplied " + "an optional value this turn, say it is being added to the same " + f"{ent}." + ) + if stop_optional and optional_keys: + if already_stated: + return ( + HANDOFF_ALREADY_STATED_PREFIX + + "Do not repeat the hand-off sentence. Close in one natural " + "sentence: thank them and confirm the " + f"{team} will follow up using the contact already given — the " + f"optional questions have ended for this {ent}. Ask no field — " + "no question mark, no invented field (delivery address or " + "anything not named here)." + ) + return ( + "Hand-off is complete. Use the skill's hand-off sentence " + f"(the {ent} has been sent to the {team}) and ask no field — the " + f"optional questions have ended for this {ent}." + ) + if not optional_keys: + if already_stated: + return ( + HANDOFF_ALREADY_STATED_PREFIX + + "Do not repeat the hand-off sentence. Close in one natural " + "sentence: thank them for the detail just given and confirm " + f"the {team} will follow up using the contact already given. " + "Ask no field — no question mark, no invented field (delivery " + "address or anything not named here)." + ) + return ( + "Hand-off is complete. Use the skill's hand-off sentence " + f"(the {ent} has been sent to the {team}) and ask no further field " + "this turn." + ) + next_optional = optional_keys[0] + if already_stated: + return ( + HANDOFF_ALREADY_STATED_PREFIX + + "Do not repeat the hand-off sentence. Briefly acknowledge the " + "detail just captured in natural wording (thank, note, or confirm " + "— no fixed opener, no sales-team or same-request restatement). " + "Then ask for " + f"`{next_optional}` now — one field, one question, in " + f"the {who}'s terms and never by its key. Ask it because this turn " + "supplied or engaged with a value and did not refuse, skip, or " + "signal done. A refusal ends the optional questions: acknowledge " + "in one sentence and do not rotate to another field." + ) + return ( + "Hand-off is complete. Use the skill's hand-off sentence " + f"(the {ent} has been sent to the {team}), then ask for " + f"`{next_optional}` now — one field, one question, in the {who}'s " + "terms and never by its key, and state the reason inside that " + f"question: the details help the {team} prepare the follow-up. Ask it " + "because this turn supplied or engaged with a value and did not " + "refuse, skip, or signal done. A refusal ends the optional questions: " + "acknowledge in one sentence, do not rotate to another field — the " + f"{ent} stays with the {team} and anything added updates it." + ) + + +def _last_user_text(interaction: Any) -> str: + for attr in ("utterance", "user_message", "text", "message", "content"): + value = getattr(interaction, attr, "") + if isinstance(value, str) and value.strip(): + return value + return "" + + +def _visitor_label(spec: LeadGenSpec, key: Optional[str]) -> str: + """Short label safe to put in a visitor sentence. Never the raw key alone.""" + if not key: + return "" + fdef = spec.get_field(key) + if fdef is None: + return str(key).replace("_", " ").strip() + label = str(getattr(fdef, "label", "") or "").strip() + if label: + return label + guidance = str(fdef.guidance or "").strip() + if guidance and len(guidance) <= 80: + return guidance + return str(key).replace("_", " ").strip() + + +def next_ask_directive( + next_required: Optional[str], + optional_keys: List[str], + *, + just_declined: bool = False, + ask_label: str = "", + stop_optional: bool = False, + entity: str = "request", + visitor: str = "visitor", + refused_label: str = "", + declined_label: str = "", +) -> str: + """The ask for this reply. Business close wording stays on the skill.""" + ent = str(entity or "request").strip() or "request" + who = str(visitor or "visitor").strip() or "visitor" + if refused_label: + return ( + f"The visitor refused {refused_label}. Do not re-ask it this turn and " + f"do not name the field key: reply that {refused_label} is needed to " + f"file this {entity} — would you like to continue or cancel? If they " + "continue, ask once more in fresh words; if they cancel, use the " + "cancel tool. Never store a refusal as the value." + ) + if declined_label and (next_required or optional_keys): + if next_required: + then = f"Then ask only for `{next_required}` — one field, one question." + elif optional_keys: + then = f"Then ask only for `{optional_keys[0]}` — one field, one question." + else: + then = "Ask no further field." + return ( + f"The visitor declined {declined_label}; acknowledge it in one short " + f"clause that names {declined_label}, and do not re-ask it. {then} Do " + f"not say {declined_label} is needed to file the {entity}." + ) + if next_required: + return ( + "Ask only for " + f"`{next_required}` in this reply; do not ask any other field. " + "Never store a refusal as the value." + ) + if just_declined: + return ( + f"Ask no further field. The {who} declined or does not want more " + "questions, so do not rotate to another optional. The " + f"{ent} is saved, and any further details they give update the same " + f"{ent}. Do not say it was sent unless the hand-off has completed." + ) + if stop_optional: + return ( + "Ask no further field. The optional questions have ended for this " + f"{ent}; the {ent} stays filed, and any further detail the " + f"{who} gives updates it." + ) + if optional_keys: + if just_declined: + return ( + f"Ask no further field. The {who} declined or does not want " + "more questions, so do not rotate to another optional. The " + f"{ent} is saved, and any further details they give update the " + f"same {ent}. Do not say it was sent unless the hand-off has " + "completed." + ) + only = optional_keys[0] + return ( + "Required fields are complete. Ask for " + f"`{only}` only — one field, one question, in the {who}'s terms " + f"and never by its key. Ask it because the {who} answered with a " + "value and has not refused, skipped, or signalled they are done. If " + "they do not want it, ask no further field; never rotate to another " + "optional. Optional fields never block the " + f"{ent}." + ) + return ( + "Required fields are complete and no optional field is open. " + "Do not ask another field." + ) + + +def capture_state( + record: Any, + spec: LeadGenSpec, + *, + just_declined: bool = False, + stop_optional: bool = False, + ignored: Sequence[str] = (), + refused: Sequence[str] = (), +) -> Dict[str, Any]: + """The record snapshot every capture/retrieve result carries. + + ``next_required`` names the single required field to ask now, and + ``directive`` states the ask for this reply; ``optional_fields`` lists the + open optional keys once required is complete. The model reads guidance from + ``field_reference`` and keeps only the timing and value judgement. """ profile_data = record.get_yaml() or {} missing = record.get_missing_fields() fields = {k: v for k, v in profile_data.items() if not str(k).startswith("_")} - qualification = [k for k in spec.gap_fill.qualification if not fields.get(k)] - next_optional = qualification[0] if qualification and not missing else None - project_scope = bool( - fields.get("project_description") or fields.get("project_location") + next_required = missing[0] if missing else None + optional_keys = ( + [] + if stop_optional + else optional_field_keys(fields, spec, ignored=tuple(ignored)) ) - project_next = None - if project_scope and not missing and not next_optional: - project_pending = [ - k for k in spec.gap_fill.project_qualification if not fields.get(k) - ] - project_next = project_pending[0] if project_pending else None - return { + next_optional = optional_keys[0] if optional_keys else None + refused_keys = tuple(refused or ()) + blocking_key = next( + ( + key + for key in refused_keys + if (lambda fd: fd is not None and fd.required and fd.decline_value is None)( + spec.get_field(key) + ) + ), + None, + ) + declined_key = next((key for key in refused_keys if key != blocking_key), None) + msgs = spec.messages + state: Dict[str, Any] = { "fields": fields, "missing_fields": missing, - "field_reference": fields_reference(spec), - "gap_fill_priority": spec.gap_fill.priority, - "next_ask": next_ask(spec, missing), - # First still-empty always-relevant qualification field, once the - # required fields are complete. Null means none remains; it never by - # itself authorizes a closing. + "next_required": next_required, + "optional_fields": optional_keys, "next_optional": next_optional, - # First still-empty project-only qualification field, exposed only when - # a project was described and the always-relevant set is complete. - "next_project_optional": project_next, + "stop_optional": bool(stop_optional), + "field_reference": fields_reference(spec), } + attach_reply_directives( + state, + next_ask_directive( + next_required, + optional_keys, + just_declined=just_declined, + ask_label=_visitor_label(spec, next_required), + stop_optional=stop_optional, + entity=msgs.entity, + visitor=msgs.visitor, + refused_label=_visitor_label(spec, blocking_key), + declined_label=_visitor_label(spec, declined_key), + ), + ) + return state async def handle_capture( @@ -280,16 +728,26 @@ async def handle_capture( return json.dumps({"error": "no active interaction"}) raw_fields: Dict[str, Any] = dict(fields or {}) + kwargs.pop("ask_next", None) + raw_fields.pop("ask_next", None) raw_fields.update( {k: v for k, v in kwargs.items() if k not in ("visitor", "skill")} ) + + spec = merge_spec_with_action_defaults(action, resolve_spec(action, skill)) if not raw_fields: return json.dumps({"status": "no-op", "reason": "no fields provided"}) - spec = merge_spec_with_action_defaults(action, resolve_spec(action, skill)) - raw_fields = canonicalize_fields(raw_fields, spec) + raw_fields, unknown_keys = canonicalize_fields(raw_fields, spec) - dedup_key = (user.user_id, json.dumps(raw_fields, sort_keys=True, default=str)) + dedup_key = ( + user.user_id, + json.dumps( + {"fields": raw_fields, "unknown": unknown_keys}, + sort_keys=True, + default=str, + ), + ) now = time.time() if now - _LAST_CAPTURE.get(dedup_key, 0) < _CAPTURE_DEDUP_TTL: # A repeated identical call still has to answer with the record. The @@ -298,63 +756,143 @@ async def handle_capture( # {"status": "deduplicated"} tells a post-capture gate nothing at all — # the same blindness the merged snapshot exists to fix, one exit over. record = await LeadRecord.get_or_create_for_user( - user, required_fields=spec.get_required_fields() or None + user, required_fields=spec.get_required_fields() ) + state = capture_state(record, spec) return json.dumps( { "status": "deduplicated", "fields_saved": [], - **capture_state(record, spec), + **state, } ) _LAST_CAPTURE[dedup_key] = now channel = getattr(interaction, "channel", "default") or "default" - if channel.lower() == "whatsapp": - if "phone" not in raw_fields and user.user_id: - raw_fields.setdefault("phone", user.user_id) - if not raw_fields.get("full_name") and getattr(user, "name", None): - raw_fields.setdefault("full_name", user.name) + # Track sentinel refusals before mapping so a real decline text (e.g. + # organization ``Personal``) is not mistaken for a refusal signal. + sentinel_keys: set = set() + for key, value in raw_fields.items(): + if not _is_decline_sentinel(value): + continue + fdef = spec.get_field(key) + if fdef is not None and fdef.decline_value is not None: + sentinel_keys.add(key) + if not sentinel_keys: + _apply_channel_defaults(raw_fields, spec, user, channel) - validated, err = await validate_fields(raw_fields, spec) - if err: - return json.dumps({"error": err, "status": "invalid-argument"}) + validated, validation_errors = await validate_fields(raw_fields, spec) + for key in unknown_keys: + validation_errors.setdefault(key, "unknown field") + just_declined = bool(sentinel_keys) record = await LeadRecord.get_or_create_for_user( - user, required_fields=spec.get_required_fields() or None + user, required_fields=spec.get_required_fields() ) profile_data = record.get_yaml() or {} + prev_offered = str(profile_data.get("_leadgen_offered") or "") + prev_ignored = list(profile_data.get("_leadgen_ignored") or []) + prev_declined = bool(profile_data.get("_leadgen_declined")) + refused_keys: list = [] + for key, value in raw_fields.items(): + fdef = spec.get_field(key) + if fdef is None: + continue + current = str(value or "").strip().casefold() + is_refusal = _is_decline_sentinel(value) or ( + fdef.decline_value is not None + and current == str(fdef.decline_value).strip().casefold() + ) + if not is_refusal: + continue + if current and current == str(profile_data.get(key) or "").strip().casefold(): + continue # already recorded earlier; not a new refusal + refused_keys.append(key) + changed = False + if validated: + ctx = HookExecutionContext( + spec=spec, + record=record, + profile_data=profile_data, + fields=validated, + visitor=visitor, + user=user, + ) + if spec.handlers.post_capture: + ctx = await call_hook(spec, spec.handlers.post_capture, ctx) + validated = ctx.fields - ctx = HookExecutionContext( - spec=spec, - record=record, - profile_data=profile_data, - fields=validated, - visitor=visitor, - user=user, - ) - if spec.handlers.post_capture: - ctx = await call_hook(spec, spec.handlers.post_capture, ctx) - validated = ctx.fields - - if spec.handlers.qualify: - ctx = await call_hook(spec, spec.handlers.qualify, ctx) - if ctx.blocked: - return json.dumps( - { + if spec.handlers.qualify: + ctx = await call_hook(spec, spec.handlers.qualify, ctx) + if ctx.blocked: + # Save locally; CRM push does not run. Hand the model a + # failed-hand-off directive naming sales_contact when set. + validated = apply_merge_fields( + validated, profile_data, spec.merge_fields() + ) + if validated: + await record.update_yaml(validated) + msgs = spec.messages + blocked: Dict[str, Any] = { "status": "blocked", "reason": ctx.block_reason or "qualification failed", } - ) + attach_reply_directives( + blocked, + failed_sync_directive( + spec.sync.sales_contact, + contact_label=msgs.contact_label, + entity=msgs.entity, + visitor=msgs.visitor, + ), + ) + return json.dumps(blocked) + + validated = apply_merge_fields(validated, profile_data, spec.merge_fields()) + changed = await record.update_yaml(validated) - validated = apply_merge_fields(validated, profile_data, spec.merge_fields()) - changed = await record.update_yaml(validated) + profile_data = record.get_yaml() or {} + ignored = list(prev_ignored) + # Sentinel refusals close the optional line. A real answer that equals a + # decline string is not a refusal. + declined_flag = prev_declined or bool(sentinel_keys) + if ( + prev_offered + and not changed + and not declined_flag + and not _field_filled(profile_data, prev_offered) + and prev_offered not in ignored + ): + ignored.append(prev_offered) + stop_optional = declined_flag or len(ignored) >= 2 + state = capture_state( + record, + spec, + refused=tuple(refused_keys), + just_declined=just_declined, + stop_optional=stop_optional, + ignored=tuple(ignored), + ) + if hasattr(record, "update_state"): + await record.update_state( + { + "_leadgen_offered": state.get("next_optional") or "", + "_leadgen_ignored": ignored, + "_leadgen_declined": declined_flag, + } + ) result: Dict[str, Any] = { - "status": "updated" if changed else "no-op", + "status": ( + "updated" + if changed + else ("invalid-argument" if validation_errors else "no-op") + ), "fields_saved": list(validated.keys()) if changed else [], - **capture_state(record, spec), + **state, } + if validation_errors: + result["validation_errors"] = validation_errors if changed: await record.append_to_section( @@ -374,6 +912,44 @@ async def handle_capture( ) result["sync_result"] = sync_result + if sync_result.get("status") == "sync-complete": + # The hand-off owns this reply; one optional may ride along when + # the pool is still open, and the pool resumes on the next capture. + # After the first hand-off the sentence is not repeated. + already_stated = handoff_already_stated(profile_data) + msgs = spec.messages + attach_reply_directives( + result, + handoff_directive( + result.get("optional_fields") or [], + already_stated=already_stated, + just_declined=just_declined, + stop_optional=stop_optional, + entity=msgs.entity, + visitor=msgs.visitor, + handoff_team=msgs.handoff_team, + ), + ) + snapshot = _public_fields(profile_data) + profile_data[HANDOFF_STATED_KEY] = True + profile_data[HANDOFF_SNAPSHOT_KEY] = snapshot + await record.update_yaml( + {HANDOFF_STATED_KEY: True, HANDOFF_SNAPSHOT_KEY: snapshot} + ) + elif not result.get("missing_fields"): + # Required fields are complete but the hand-off did not run. Say it + # is saved and not sent; never let the reply claim otherwise. + msgs = spec.messages + attach_reply_directives( + result, + failed_sync_directive( + spec.sync.sales_contact, + contact_label=msgs.contact_label, + entity=msgs.entity, + visitor=msgs.visitor, + ), + ) + if spec.handlers.on_sync: ctx = HookExecutionContext( spec=spec, @@ -424,16 +1000,12 @@ async def handle_retrieve( ) profile_data = record.get_yaml() or {} clean = {k: v for k, v in profile_data.items() if not k.startswith("_")} + state = capture_state(record, spec) - missing = record.get_missing_fields() return json.dumps( { "status": "ok" if clean else "empty_profile", - "fields": clean, - "missing_fields": missing, - "field_reference": fields_reference(spec), - "gap_fill_priority": spec.gap_fill.priority, - "next_ask": next_ask(spec, missing), + **state, "score": record.score, "enrichment_status": record.enrichment_status, } @@ -480,7 +1052,7 @@ async def handle_sync( spec = merge_spec_with_action_defaults(action, resolve_spec(action, skill)) record = await LeadRecord.get_or_create_for_user( - user, required_fields=spec.get_required_fields() or None + user, required_fields=spec.get_required_fields() ) profile_data = record.get_yaml() or {} if not profile_data: diff --git a/jvagent/action/leadgen/examples/example_leadgen/SKILL.md b/jvagent/action/leadgen/examples/example_leadgen/SKILL.md index f78c212c7..0fe4d8431 100644 --- a/jvagent/action/leadgen/examples/example_leadgen/SKILL.md +++ b/jvagent/action/leadgen/examples/example_leadgen/SKILL.md @@ -18,6 +18,11 @@ leadgen: summary: >- Reference leadgen skill for product inquiries. Copy to agents/.../skills// and register in agent.yaml orchestrator skills. + messages: + entity: request + handoff_team: sales team + contact_label: sales contact + visitor: visitor fields: - key: full_name required: true @@ -47,7 +52,6 @@ leadgen: guidance: Brief description of their project or need gap_fill: batch: true - priority: [full_name, phone, email, organization] sync: mode: on_capture min_fields: [full_name] @@ -77,4 +81,4 @@ leadgen: ### Tone - Weave data collection into helpful answers — never interrogate. -- When the user declines email, save `email="N/A"` immediately. +- When the user declines email, send `email: decline_value` (maps to `N/A`). diff --git a/jvagent/action/leadgen/leadgen_action.py b/jvagent/action/leadgen/leadgen_action.py index 066cb58a3..b63de86f2 100644 --- a/jvagent/action/leadgen/leadgen_action.py +++ b/jvagent/action/leadgen/leadgen_action.py @@ -56,16 +56,24 @@ class LeadGenAction(Action): ), ) sync_min_fields: List[str] = attribute( - default_factory=lambda: ["full_name"], + default_factory=list, description=( - "Fields that must all be present before an action-level sync fires." + "Fields that must all be present before an action-level sync fires. " + "Empty means no min-field gate (skills declare their own)." ), ) sync_require_any: List[str] = attribute( - default_factory=lambda: ["phone", "email"], + default_factory=list, description=( "At least one of these must be present before an action-level sync " - "fires." + "fires. Empty means no require-any gate." + ), + ) + sales_contact: str = attribute( + default="", + description=( + "Optional contact named when a hand-off did not run. Empty omits " + "the offer. A skill sync.sales_contact overrides this." ), ) @@ -156,7 +164,7 @@ async def _handle_custom_tool( from .store import LeadRecord record = await LeadRecord.get_or_create_for_user( - user, required_fields=spec.get_required_fields() or None + user, required_fields=spec.get_required_fields() ) fn = load_hook_function(spec, tdef.function or tdef.name) if fn is None: diff --git a/jvagent/action/leadgen/spec.py b/jvagent/action/leadgen/spec.py index f69b8f932..21be17481 100644 --- a/jvagent/action/leadgen/spec.py +++ b/jvagent/action/leadgen/spec.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Union @@ -15,17 +16,35 @@ ) from jvagent.action.skill_spec.registry import BaseSkillRegistry +from .validators import known_validators + +logger = logging.getLogger(__name__) + LEADGEN_FRONTMATTER_KEY = "leadgen" SyncMode = Literal["on_capture", "on_complete", "manual"] +#: No channel autofill unless the skill declares ``channel_defaults``. +DEFAULT_CHANNEL_DEFAULTS: Dict[str, Dict[str, str]] = {} + _LEADGEN_KEYS = frozenset( - {"title", "summary", "fields", "gap_fill", "sync", "handlers", "skill_tools"} + { + "title", + "summary", + "fields", + "gap_fill", + "sync", + "handlers", + "skill_tools", + "messages", + "channel_defaults", + } ) _FIELD_KEYS = frozenset( { "key", "guidance", + "label", "required", "aliases", "validator", @@ -33,19 +52,30 @@ "decline_value", "merge", "phone_locale", + "relevant_when", + "capture_only", } ) -_GAP_FILL_KEYS = frozenset( - {"batch", "priority", "qualification", "project_qualification"} +# ``priority``, ``qualification`` and ``project_qualification`` used to order +# the ask. Declaration order replaced them. They are still accepted so an +# existing skill parses; the values are ignored. +_GAP_FILL_DEPRECATED = frozenset({"priority", "qualification", "project_qualification"}) +_GAP_FILL_KEYS = frozenset({"batch"}) | _GAP_FILL_DEPRECATED +_RELEVANT_WHEN_KEYS = frozenset({"any_present", "not_declined", "values_not"}) +_SYNC_KEYS = frozenset( + {"mode", "min_fields", "require_any", "destinations", "sales_contact", "timezone"} ) -_SYNC_KEYS = frozenset({"mode", "min_fields", "require_any", "destinations"}) _HANDLER_KEYS = frozenset({"post_capture", "qualify", "on_sync"}) +_MESSAGES_KEYS = frozenset({"entity", "handoff_team", "contact_label", "visitor"}) +_CHANNEL_DEFAULT_SOURCES = frozenset({"user_id", "user_name"}) @dataclass class FieldDef: key: str guidance: str = "" + # Short visitor-facing name for directives when guidance is long. + label: str = "" required: bool = False aliases: List[str] = field(default_factory=list) validator: str = "" @@ -53,28 +83,42 @@ class FieldDef: decline_value: Optional[str] = None merge: bool = False phone_locale: str = "" + # Captured only when volunteered; never asked, never offered in the pool. + capture_only: bool = False + # Eligibility gate the catalogue carries for the model to honour: the field + # is askable only once at least one ``any_present`` key is filled, and never + # while a ``not_declined`` key holds its own ``decline_value``. ``values_not`` + # maps a filled key to banned values (case-insensitive) that keep the field + # ineligible. Absent = always eligible. + relevant_when: Optional[Dict[str, Any]] = None @dataclass class GapFillDef: batch: bool = True - priority: List[str] = field(default_factory=list) - # Optional fields that apply to every request cycle (e.g. role, industry, - # company size). capture_state names the first empty one as next_optional so - # the agent has a structured ask once the required fields are complete. - qualification: List[str] = field(default_factory=list) - # Qualification fields that apply only once a project is described (budget, - # timeline, pain points, contact preference). capture_state names the first - # empty one as next_project_optional after the always-relevant set is done. - project_qualification: List[str] = field(default_factory=list) @dataclass class SyncDef: mode: SyncMode = "on_capture" - min_fields: List[str] = field(default_factory=lambda: ["full_name"]) - require_any: List[str] = field(default_factory=lambda: ["phone", "email"]) + min_fields: List[str] = field(default_factory=list) + require_any: List[str] = field(default_factory=list) destinations: List[Dict[str, Any]] = field(default_factory=list) + # Offered in the failed-hand-off directive. Empty means the directive + # does not name a contact. + sales_contact: str = "" + # IANA timezone for ``{last_updated}`` in sync templates. + timezone: str = "UTC" + + +@dataclass +class MessagesDef: + """Neutral hand-off vocabulary. Skills override for domain wording.""" + + entity: str = "request" + handoff_team: str = "team" + contact_label: str = "contact" + visitor: str = "visitor" @dataclass @@ -94,6 +138,9 @@ class LeadGenSpec: sync: SyncDef = field(default_factory=SyncDef) handlers: HandlersDef = field(default_factory=HandlersDef) skill_tools: List[SkillToolDef] = field(default_factory=list) + messages: MessagesDef = field(default_factory=MessagesDef) + # None → DEFAULT_CHANNEL_DEFAULTS; {} → disable autofill. + channel_defaults: Optional[Dict[str, Dict[str, str]]] = None source_dir: str = "" def get_required_fields(self) -> List[str]: @@ -119,8 +166,19 @@ def alias_map(self) -> Dict[str, str]: def merge_fields(self) -> List[str]: return [f.key for f in self.fields if f.merge] + def resolved_channel_defaults(self) -> Dict[str, Dict[str, str]]: + if self.channel_defaults is None: + return dict(DEFAULT_CHANNEL_DEFAULTS) + return dict(self.channel_defaults) + def fields_reference(spec: LeadGenSpec) -> List[Dict[str, Any]]: + """The catalogue the model reads: every declared field, declaration order. + + Filled fields stay in the list so the model can correct or refresh a value; + ``relevant_when`` travels with the entry and is honoured by the SOP, not + filtered here. + """ out: List[Dict[str, Any]] = [] for f in spec.fields: entry: Dict[str, Any] = { @@ -128,27 +186,72 @@ def fields_reference(spec: LeadGenSpec) -> List[Dict[str, Any]]: "guidance": f.guidance, "required": f.required, } + if f.label: + entry["label"] = f.label if f.decline_value is not None: entry["decline_value"] = f.decline_value + if f.capture_only: + entry["capture_only"] = True + if f.relevant_when: + entry["relevant_when"] = dict(f.relevant_when) out.append(entry) return out +def _parse_relevant_when(data: Any, *, path: str) -> Optional[Dict[str, Any]]: + if data is None or data == "": + return None + if not isinstance(data, dict): + raise ValueError(f"{path} must be a mapping") + reject_unknown_keys(data, _RELEVANT_WHEN_KEYS, path=path) + any_present = [str(x) for x in (data.get("any_present") or []) if x] + not_declined = [str(x) for x in (data.get("not_declined") or []) if x] + raw_values_not = data.get("values_not") or {} + if raw_values_not and not isinstance(raw_values_not, dict): + raise ValueError(f"{path}.values_not must be a mapping of field → list") + values_not: Dict[str, List[str]] = {} + for key, vals in raw_values_not.items(): + banned = [str(v) for v in (vals or []) if v] + if banned: + values_not[str(key)] = banned + if not any_present and not not_declined and not values_not: + return None + gate: Dict[str, Any] = {} + if any_present: + gate["any_present"] = any_present + if not_declined: + gate["not_declined"] = not_declined + if values_not: + gate["values_not"] = values_not + return gate + + def _parse_field(data: Dict[str, Any], *, index: int) -> FieldDef: path = f"fields[{index}]" if not isinstance(data, dict): raise ValueError(f"Field at {path} must be a mapping") reject_unknown_keys(data, _FIELD_KEYS, path=path) + validator = str(data.get("validator", "") or "").strip() + if validator and validator.lower() not in known_validators(): + raise ValueError( + f"{path}.validator unknown '{validator}'; " + f"known: {', '.join(sorted(known_validators()))}" + ) return FieldDef( key=str(data.get("key", "") or "").strip(), guidance=str(data.get("guidance", "") or ""), + label=str(data.get("label", "") or "").strip(), required=bool(data.get("required", False)), aliases=[str(a) for a in (data.get("aliases") or []) if a], - validator=str(data.get("validator", "") or "").strip(), + validator=validator, validator_args=dict(data.get("validator_args") or {}), decline_value=data.get("decline_value"), merge=bool(data.get("merge", False)), phone_locale=str(data.get("phone_locale", "") or ""), + capture_only=bool(data.get("capture_only", False)), + relevant_when=_parse_relevant_when( + data.get("relevant_when"), path=f"{path}.relevant_when" + ), ) @@ -158,14 +261,13 @@ def _parse_gap_fill(data: Any) -> GapFillDef: if not isinstance(data, dict): raise ValueError("gap_fill must be a mapping") reject_unknown_keys(data, _GAP_FILL_KEYS, path="gap_fill") - return GapFillDef( - batch=bool(data.get("batch", True)), - priority=[str(x) for x in (data.get("priority") or []) if x], - qualification=[str(x) for x in (data.get("qualification") or []) if x], - project_qualification=[ - str(x) for x in (data.get("project_qualification") or []) if x - ], - ) + stale = sorted(k for k in _GAP_FILL_DEPRECATED if k in data) + if stale: + logger.warning( + "leadgen gap_fill.%s is ignored; ask order is field declaration order", + ", ".join(stale), + ) + return GapFillDef(batch=bool(data.get("batch", True))) def _parse_sync(data: Any) -> SyncDef: @@ -177,16 +279,68 @@ def _parse_sync(data: Any) -> SyncDef: mode = str(data.get("mode") or "on_capture").strip().lower() if mode not in ("on_capture", "on_complete", "manual"): raise ValueError("sync.mode must be on_capture, on_complete, or manual") + # Omitted keys → empty lists (agent-agnostic). Explicit empty list stays empty. + if "min_fields" in data: + min_fields = [str(x) for x in (data.get("min_fields") or []) if x] + else: + min_fields = [] + if "require_any" in data: + require_any = [str(x) for x in (data.get("require_any") or []) if x] + else: + require_any = [] return SyncDef( mode=mode, # type: ignore[arg-type] - min_fields=[str(x) for x in (data.get("min_fields") or ["full_name"]) if x], - require_any=[ - str(x) for x in (data.get("require_any") or ["phone", "email"]) if x - ], + min_fields=min_fields, + require_any=require_any, destinations=list(data.get("destinations") or []), + sales_contact=str(data.get("sales_contact") or "").strip(), + timezone=str(data.get("timezone") or "UTC").strip() or "UTC", ) +def _parse_messages(data: Any) -> MessagesDef: + if not data: + return MessagesDef() + if not isinstance(data, dict): + raise ValueError("messages must be a mapping") + reject_unknown_keys(data, _MESSAGES_KEYS, path="messages") + return MessagesDef( + entity=str(data.get("entity") or "request").strip() or "request", + handoff_team=str(data.get("handoff_team") or "team").strip() or "team", + contact_label=str(data.get("contact_label") or "contact").strip() or "contact", + visitor=str(data.get("visitor") or "visitor").strip() or "visitor", + ) + + +def _parse_channel_defaults(data: Any) -> Optional[Dict[str, Dict[str, str]]]: + """None when omitted (use framework default); ``{}`` disables autofill.""" + if data is None: + return None + if not isinstance(data, dict): + raise ValueError("channel_defaults must be a mapping") + out: Dict[str, Dict[str, str]] = {} + for channel, mapping in data.items(): + ch = str(channel or "").strip().lower() + if not ch: + continue + if not isinstance(mapping, dict): + raise ValueError(f"channel_defaults.{ch} must be a mapping") + resolved: Dict[str, str] = {} + for field_key, source in mapping.items(): + key = str(field_key or "").strip() + src = str(source or "").strip().lower() + if not key: + continue + if src not in _CHANNEL_DEFAULT_SOURCES: + raise ValueError( + f"channel_defaults.{ch}.{key} source must be " + f"user_id or user_name, got '{source}'" + ) + resolved[key] = src + out[ch] = resolved + return out + + def _parse_handlers(data: Any) -> HandlersDef: def _build(raw: Dict[str, Any]) -> HandlersDef: return HandlersDef( @@ -222,6 +376,12 @@ def parse_leadgen_spec( require_mapping=False, ) + channel_defaults: Optional[Dict[str, Dict[str, str]]] + if "channel_defaults" in data: + channel_defaults = _parse_channel_defaults(data.get("channel_defaults")) + else: + channel_defaults = None + return LeadGenSpec( name=default_name, title=str(data.get("title", "") or ""), @@ -231,6 +391,8 @@ def parse_leadgen_spec( sync=_parse_sync(data.get("sync")), handlers=_parse_handlers(data.get("handlers")), skill_tools=skill_tools, + messages=_parse_messages(data.get("messages")), + channel_defaults=channel_defaults, source_dir=source_dir, ) diff --git a/jvagent/action/leadgen/store.py b/jvagent/action/leadgen/store.py index baa27b3e5..577f9b277 100644 --- a/jvagent/action/leadgen/store.py +++ b/jvagent/action/leadgen/store.py @@ -15,28 +15,9 @@ logger = logging.getLogger(__name__) -DEFAULT_REQUIRED_FIELDS: List[str] = [ - "full_name", - "organization", - "email", - "phone", -] - -DEFAULT_OPTIONAL_FIELDS: List[str] = [ - "project_description", - "project_location", - "contact_role", - "company_industry", - "company_size", - "project_budget", - "project_timeline", - "project_pain_points", - "current_tools", - "communication_preference", - "quote_items", - "order_items", - "feedback", -] +#: No default field vocabulary: the skill spec is the only source of field +#: names. A record created without an explicit list carries no required fields. +DEFAULT_REQUIRED_FIELDS: List[str] = [] @compound_index( @@ -144,6 +125,23 @@ def get_missing_fields(self) -> List[str]: missing.append(field) return missing + async def update_state(self, updates: Dict[str, Any]) -> bool: + """Merge underscore-only state keys without marking the lead changed. + + ``update_yaml`` sets ``changed=True`` for every underscore key, which + would drive an auto-sync and a "Set:" summary line on a turn that saved + no lead field. State bookkeeping must not do that. + """ + current = self.get_yaml() + merged = dict(current) + for key, value in updates.items(): + if str(key).startswith("_"): + merged[key] = value + if merged == current: + return False + await self.set_yaml(merged) + return False + async def update_yaml(self, updates: Dict[str, Any]) -> bool: current = self.get_yaml() changed = False @@ -248,7 +246,11 @@ async def get_for_user(cls, user: "User") -> Optional["LeadRecord"]: async def get_or_create_for_user( cls, user: "User", required_fields: Optional[List[str]] = None ) -> "LeadRecord": - field_list = required_fields or list(DEFAULT_REQUIRED_FIELDS) + field_list = ( + list(required_fields) + if required_fields is not None + else list(DEFAULT_REQUIRED_FIELDS) + ) fields_csv = ", ".join(field_list) existing = await cls.get_for_user(user) @@ -258,7 +260,7 @@ async def get_or_create_for_user( existing.user_node_id = user.id await existing.save() current = existing._get_list_field("required_fields") - if required_fields and current != field_list: + if required_fields is not None and current != field_list: existing.required_fields = fields_csv missing = existing.get_missing_fields() existing.missing_fields = ", ".join(missing) diff --git a/jvagent/action/leadgen/sync.py b/jvagent/action/leadgen/sync.py index 9e82609c2..962a68911 100644 --- a/jvagent/action/leadgen/sync.py +++ b/jvagent/action/leadgen/sync.py @@ -6,18 +6,23 @@ import json import logging import re -from datetime import datetime, timedelta, timezone +from datetime import datetime, timezone, tzinfo from typing import Any, Dict, List, Optional, Tuple +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError logger = logging.getLogger(__name__) DIGEST_KEY = "_leadgen_sync_digest" LEGACY_DIGEST_KEY = "_lead_sync_mcp_DIGEST" -UTC_MINUS_4 = timezone(timedelta(hours=-4)) -def _now_utc_minus_4() -> str: - return datetime.now(UTC_MINUS_4).strftime("%Y-%m-%d %H:%M") +def _now_in_timezone(tz_name: str = "UTC") -> str: + tz: tzinfo + try: + tz = ZoneInfo(str(tz_name or "UTC").strip() or "UTC") + except (ZoneInfoNotFoundError, KeyError, ValueError): + tz = timezone.utc + return datetime.now(tz).strftime("%Y-%m-%d %H:%M") def compute_digest(data: Dict[str, Any]) -> str: @@ -37,7 +42,13 @@ def get_stored_digest(profile_data: Dict[str, Any]) -> Optional[str]: return profile_data.get(DIGEST_KEY) or profile_data.get(LEGACY_DIGEST_KEY) -def substitute(val: Any, profile_data: Dict[str, Any], user_id: str) -> Any: +def substitute( + val: Any, + profile_data: Dict[str, Any], + user_id: str, + *, + timezone_name: str = "UTC", +) -> Any: # Exclude internal, underscore-prefixed keys (e.g. the stored sync digest) # from every template — they are bookkeeping, not lead data, and must not # leak into a synced destination. Matches profile_keys/profile_row. @@ -45,13 +56,14 @@ def substitute(val: Any, profile_data: Dict[str, Any], user_id: str) -> Any: profile_json = json.dumps(public, default=str) profile_keys = sorted(public) profile_row = [str(public.get(k, "")) for k in profile_keys] + last_updated = _now_in_timezone(timezone_name) def _replace(s: str) -> str: s = s.replace("{user_id}", str(user_id)) s = s.replace("{profile_json}", profile_json) s = s.replace("{profile_keys}", json.dumps(profile_keys)) s = s.replace("{profile_row}", json.dumps(profile_row)) - s = s.replace("{last_updated}", _now_utc_minus_4()) + s = s.replace("{last_updated}", last_updated) for k, v in profile_data.items(): s = s.replace(f"{{{k}}}", str(v) if v is not None else "") # Any remaining {placeholder} refers to a field that has not been @@ -64,14 +76,22 @@ def _replace(s: str) -> str: try: parsed = json.loads(replaced) if isinstance(parsed, (list, dict)): - return substitute(parsed, profile_data, user_id) + return substitute( + parsed, profile_data, user_id, timezone_name=timezone_name + ) except (json.JSONDecodeError, ValueError): pass return replaced if isinstance(val, list): - return [substitute(item, profile_data, user_id) for item in val] + return [ + substitute(item, profile_data, user_id, timezone_name=timezone_name) + for item in val + ] if isinstance(val, dict): - return {k: substitute(v, profile_data, user_id) for k, v in val.items()} + return { + k: substitute(v, profile_data, user_id, timezone_name=timezone_name) + for k, v in val.items() + } return val @@ -98,6 +118,8 @@ async def sync_to_destinations( destinations: List[Dict[str, Any]], profile_data: Dict[str, Any], user_id: str, + *, + timezone_name: str = "UTC", ) -> Tuple[Dict[str, str], bool]: if not destinations: return {}, False @@ -142,10 +164,23 @@ async def sync_to_destinations( ) results[server_name] = "skipped: connector not configured" continue - ok, msg = await _sync_mcp(mcp_action, entry, profile_data, user_id) + ok, msg = await _sync_mcp( + mcp_action, + entry, + profile_data, + user_id, + timezone_name=timezone_name, + ) results[server_name] = "ok" if ok else msg if ok: any_success = True + else: + logger.warning( + "leadgen sync: destination=%s failed user=%s: %s", + server_name, + user_id, + msg, + ) return results, any_success @@ -155,6 +190,8 @@ async def _sync_mcp( entry: Dict[str, Any], profile_data: Dict[str, Any], uid: str, + *, + timezone_name: str = "UTC", ) -> Tuple[bool, str]: server_name = (entry.get("server") or "").strip() tool_name = (entry.get("tool") or "").strip() @@ -166,7 +203,7 @@ async def _sync_mcp( if not tool_name: return False, f"Missing 'tool' for MCP entry '{server_name}'." - resolved_args = substitute(raw_args, profile_data, uid) + resolved_args = substitute(raw_args, profile_data, uid, timezone_name=timezone_name) if hasattr(mcp_action, "ensure_servers"): try: diff --git a/jvagent/action/leadgen/tools.py b/jvagent/action/leadgen/tools.py index 68c59b488..c67200b67 100644 --- a/jvagent/action/leadgen/tools.py +++ b/jvagent/action/leadgen/tools.py @@ -41,7 +41,9 @@ def _field_properties(action: "LeadGenAction") -> Dict[str, Any]: } for key, cfg in (action.default_fields or {}).items(): if key not in props: - desc = cfg.get("description", "") if isinstance(cfg, dict) else "" + desc = "" + if isinstance(cfg, dict): + desc = str(cfg.get("guidance") or cfg.get("description") or "") props[key] = {"type": "string", "description": desc or f"Lead field: {key}"} return props @@ -62,7 +64,10 @@ async def _capture( **kwargs: Any, ) -> str: return await action._handle_capture( - fields=fields, skill=skill, visitor=visitor, **kwargs + fields=fields, + skill=skill, + visitor=visitor, + **kwargs, ) async def _retrieve( @@ -88,20 +93,17 @@ async def _sync(skill: Optional[str] = None, visitor: Any = None, **_: Any) -> s Tool( name="leadgen__capture", description=( - "Save or update lead fields from the latest user message. " - "Call when the user provides personal, business, or interest information. " - "Use decline values from field_reference when the user refuses a field " - "(e.g. email='N/A'). Auto-syncs to configured destinations when thresholds " - "are met — do not call leadgen__sync in on_capture mode. " - "STANDING GOAL: collecting the visitor's name and a way to reach them " - "(email or phone) comes first, then the qualification fields the skill " - "declares for every request. The response returns missing_fields + " - "gap_fill_priority + a next_ask hint for the next required contact field; " - "once required fields are complete, next_ask is null but next_optional " - "names the qualification field to ask next. Null next_ask is not a " - "finished request — ask next_optional before closing. When the customer " - "described a project, next_project_optional names the next project field " - "to ask after the always-relevant set is answered." + "Save or update lead fields from the latest message. Send every new value in " + "one call. For a refusal in any language pass that field's own decline value " + "(email -> N/A, organization -> Personal, contact_role -> Not provided, the " + "optional fields -> Not provided); a field with no decline value (full_name, " + "phone) takes nothing. Never pass the word decline_value itself. A non-answer " + "such as ok, anyway, or not sure is an ignore, not a decline: capture nothing. " + "Returns status, fields, " + "missing_fields, next_required, optional_fields, next_optional, " + "stop_optional, field_reference, validation_errors, sync_result, and a " + "directive. Follow the directive; stop_optional means ask no further " + "optional. A capture is not a close." ), parameters_schema={ "type": "object", @@ -113,14 +115,12 @@ async def _sync(skill: Optional[str] = None, visitor: Any = None, **_: Any) -> s Tool( name="leadgen__retrieve", description=( - "Load the current lead profile, missing_fields, field_reference, and a " - "next_ask hint. Use mid-conversation, once a request cycle is already " - "underway, when you need profile context and the visitor supplied no new " - "lead data. NEVER the first call on a post-sync turn: when the visitor " - 'returns after a sync — including a bare greeting like "hey" with no ' - "product named — leadgen__prepare_request runs first. Do not use retrieve to " - "restore the profile after a sync or to open a turn; it reads the cleared " - "record and re-asks for details the visitor already gave." + "Load the current lead profile, next_required, optional_fields, " + "next_optional, stop_optional, field_reference, " + "and the ask directive. Use mid-conversation when you need " + "profile context and the visitor supplied no new lead data. " + "Do not use retrieve to open a new capture cycle after a hand-off; " + "when the skill provides a prepare tool, that tool starts the next cycle." ), parameters_schema=optional_skill, execute=_retrieve, diff --git a/jvagent/action/leadgen/validators.py b/jvagent/action/leadgen/validators.py index e1a38a348..45e9c8c20 100644 --- a/jvagent/action/leadgen/validators.py +++ b/jvagent/action/leadgen/validators.py @@ -3,7 +3,8 @@ from __future__ import annotations import re -from typing import Any, Callable, Dict, Optional, Tuple +from datetime import datetime +from typing import Any, Callable, Dict, FrozenSet, List, Optional, Tuple ValidatorFn = Callable[..., Tuple[Optional[str], Optional[str]]] @@ -18,8 +19,6 @@ def validate_email(raw: str, **_: Any) -> Tuple[Optional[str], Optional[str]]: if not raw or not raw.strip(): return _result(None, "Email address cannot be empty.") cleaned = raw.strip() - if cleaned.upper() == "N/A": - return _result(cleaned, None) if cleaned.count("@") != 1: return _result( None, f"Invalid email '{cleaned}': must contain exactly one '@'." @@ -60,15 +59,139 @@ def validate_phone_gy(raw: str, **_: Any) -> Tuple[Optional[str], Optional[str]] return _result(cleaned, None) -def validate_person_name(raw: str, **_: Any) -> Tuple[Optional[str], Optional[str]]: +def validate_person_name( + raw: str, + *, + min_length: int = 2, + max_words: int = 4, + **_: Any, +) -> Tuple[Optional[str], Optional[str]]: if not raw or not str(raw).strip(): return _result(None, "Name cannot be empty.") name = str(raw).strip() - if len(name) < 2: + try: + min_len = int(min_length) + except (TypeError, ValueError): + min_len = 2 + try: + max_w = int(max_words) + except (TypeError, ValueError): + max_w = 4 + if len(name) < min_len: return _result(None, "Name is too short.") + if max_w > 0 and len(name.split()) > max_w: + return _result(None, "Name has too many words.") return _result(name, None) +def validate_enum( + raw: str, *, choices: Optional[List[Any]] = None, **_: Any +) -> Tuple[Optional[str], Optional[str]]: + if not choices: + return _result(None, "enum validator requires choices.") + cleaned = str(raw or "").strip() + if not cleaned: + return _result(None, "Value cannot be empty.") + lookup = { + str(c).strip().casefold(): str(c).strip() for c in choices if str(c).strip() + } + hit = lookup.get(cleaned.casefold()) + if hit is None: + return _result( + None, f"must be one of: {', '.join(str(c).strip() for c in choices)}" + ) + return _result(hit, None) + + +def validate_regex( + raw: str, + *, + pattern: str = "", + flags: str = "", + **_: Any, +) -> Tuple[Optional[str], Optional[str]]: + if not pattern: + return _result(None, "regex validator requires pattern.") + cleaned = str(raw or "").strip() + if not cleaned: + return _result(None, "Value cannot be empty.") + re_flags = 0 + for ch in str(flags or ""): + if ch == "i": + re_flags |= re.IGNORECASE + elif ch == "m": + re_flags |= re.MULTILINE + elif ch == "s": + re_flags |= re.DOTALL + try: + compiled = re.compile(pattern, re_flags) + except re.error as exc: + return _result(None, f"invalid regex pattern: {exc}") + if not compiled.fullmatch(cleaned): + return _result(None, f"does not match required pattern.") + return _result(cleaned, None) + + +def validate_number( + raw: str, + *, + min: Optional[float] = None, # noqa: A002 — matches validator_args key + max: Optional[float] = None, # noqa: A002 + **_: Any, +) -> Tuple[Optional[str], Optional[str]]: + cleaned = str(raw or "").strip() + if not cleaned: + return _result(None, "Value cannot be empty.") + try: + number = float(cleaned.replace(",", "")) + except ValueError: + return _result(None, f"'{cleaned}' is not a number.") + if min is not None and number < float(min): + return _result(None, f"must be at least {min}.") + if max is not None and number > float(max): + return _result(None, f"must be at most {max}.") + if number.is_integer(): + return _result(str(int(number)), None) + return _result(str(number), None) + + +_DEFAULT_DATE_FORMATS = ( + "%Y-%m-%d", + "%Y/%m/%d", + "%d-%m-%Y", + "%d/%m/%Y", + "%m/%d/%Y", + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%dT%H:%M:%SZ", +) + + +def validate_date( + raw: str, + *, + formats: Optional[List[str]] = None, + **_: Any, +) -> Tuple[Optional[str], Optional[str]]: + cleaned = str(raw or "").strip() + if not cleaned: + return _result(None, "Value cannot be empty.") + # Accept plain ISO date without going through strptime edge cases. + if re.fullmatch(r"\d{4}-\d{2}-\d{2}", cleaned): + try: + datetime.strptime(cleaned, "%Y-%m-%d") + return _result(cleaned, None) + except ValueError: + return _result(None, f"'{cleaned}' is not a valid date.") + tried = list(formats) if formats else list(_DEFAULT_DATE_FORMATS) + for fmt in tried: + try: + parsed = datetime.strptime(cleaned, fmt) + return _result(parsed.strftime("%Y-%m-%d"), None) + except ValueError: + continue + return _result(None, f"'{cleaned}' is not a recognised date.") + + _BUILTIN: Dict[str, ValidatorFn] = { "email": validate_email, "phone": validate_phone_e164, @@ -76,9 +199,31 @@ def validate_person_name(raw: str, **_: Any) -> Tuple[Optional[str], Optional[st "phone_gy": validate_phone_gy, "person_name": validate_person_name, "name": validate_person_name, + "enum": validate_enum, + "regex": validate_regex, + "number": validate_number, + "date": validate_date, } +def known_validators() -> FrozenSet[str]: + return frozenset(_BUILTIN) + + +def locale_validator(locale: str) -> str: + """Resolve a ``phone_locale`` to a registered ``phone_`` validator. + + Data-driven: any built-in named ``phone_`` works, so a deployment can + add a locale validator without touching the engine. Unknown or empty locale + returns ``""``; the caller falls back to E164. + """ + key = str(locale or "").strip().lower() + if not key: + return "" + name = f"phone_{key}" + return name if name in _BUILTIN else "" + + def get_validator(name: str) -> Optional[ValidatorFn]: if not name: return None @@ -92,6 +237,5 @@ def run_validator( ) -> Tuple[Optional[str], Optional[str]]: fn = get_validator(name) if fn is None: - text = str(value).strip() if value is not None else "" - return _result(text or None, None if text else "Value cannot be empty.") + return _result(None, f"unknown validator '{name}'.") return fn(str(value), **(validator_args or {})) diff --git a/jvagent/action/mcp/client.py b/jvagent/action/mcp/client.py index 53b5d7b5f..28401482f 100644 --- a/jvagent/action/mcp/client.py +++ b/jvagent/action/mcp/client.py @@ -186,7 +186,10 @@ async def _run_http_session() -> None: if self._http_client is not None else streamable_http_client(self._url) ) - async with transport_ctx as (read_stream, write_stream, _session_id): + async with transport_ctx as streams: + # mcp SDK yields (read, write[, get_session_id]); accept both + # shapes so the transport works across SDK versions. + read_stream, write_stream = streams[0], streams[1] self._read_stream = read_stream self._write_stream = write_stream async with ClientSession(read_stream, write_stream) as session: diff --git a/jvagent/action/mcp/integral_oauth_auth.py b/jvagent/action/mcp/integral_oauth_auth.py new file mode 100644 index 000000000..7f955e4fe --- /dev/null +++ b/jvagent/action/mcp/integral_oauth_auth.py @@ -0,0 +1,313 @@ +"""``httpx`` auth flow that authenticates MCP requests to Integral Core with OAuth. + +After the browser OAuth connect (see :mod:`jvagent.action.mcp_oauth.endpoints`), +Core issues an OAuth 2.1 access token scoped to the signed-in user. The mounted +``/api/mcp`` endpoint accepts it as ``Authorization: Bearer `` — the same +contract Core's resource-server auth middleware applies to any ``auth=True`` +endpoint (``accept_oauth_bearer=True``). + +``IntegralOAuthAuth`` loads the stored access token for a server/account, quietly +refreshes it when (near) expired, and stamps every request with the bearer. An +optional ``X-Integral-Scope: ws:`` header pins the workspace; Core honours it +only when the token's principal is a member, otherwise it fails closed to the +user's own default workspace. +""" + +from __future__ import annotations + +import asyncio +import logging +from datetime import datetime, timedelta, timezone +from typing import Any, AsyncGenerator, Dict, Optional, Tuple + +import httpx + +from jvagent.action.mcp.redirect_trust import ( + is_trusted_url, + make_redirect_validator, + origin_of, + strip_authorization_headers, +) +from jvagent.action.mcp_oauth.integral_provider import ( + DEFAULT_ACCOUNT, + INTEGRAL_SERVER, + INTEGRAL_SERVICE, + discover_authorization_server, + load_registered_client, + normalize_token_payload, + payload_is_expired, + refresh_access_token, + resolve_scope, +) + +logger = logging.getLogger(__name__) + +DEFAULT_CONNECT_TIMEOUT = 10.0 +DEFAULT_READ_TIMEOUT = 60.0 + + +class IntegralOAuthNotConnectedError(RuntimeError): + """Raised when no OAuth token is stored for the server/account.""" + + +async def _load_token_node( + server_name: str, account_name: str +) -> Tuple[Any, Optional[Dict[str, Any]]]: + """Return ``(node, payload)`` for the stored token, or ``(None, None)``. + + Tolerates both storage shapes: a flat payload, and one nested under + ``service_tokens`` (the shape ``apply_service_rebind`` writes). + """ + import json + + from jvspatial.core.context import GraphContext + from jvspatial.db import get_database_manager + + from jvagent.action.mcp_oauth.mcp_oauth_node import MCPOAuthToken + + manager = get_database_manager() + db = manager.get_database() + ctx = GraphContext(db) + nodes = await ctx.find_nodes( + MCPOAuthToken, + {"context.server_name": server_name, "context.account_name": account_name}, + ) + if not nodes: + return None, None + node = nodes[0] + if not node.token_json: + return node, None + try: + payload = json.loads(node.token_json) + except Exception: + return node, None + if not isinstance(payload, dict): + return node, None + return node, _flatten_service_tokens(payload) + + +def _flatten_service_tokens(payload: Dict[str, Any]) -> Dict[str, Any]: + """Return a flat view of a token payload, unwrapping ``service_tokens``.""" + st = payload.get("service_tokens") + if isinstance(st, dict): + for key in (INTEGRAL_SERVICE, *st.keys()): + blob = st.get(key) + if isinstance(blob, dict) and ( + blob.get("access_token") or blob.get("refresh_token") + ): + merged = dict(payload) + merged.update(blob) + return merged + return payload + + +async def _save_token_payload(node: Any, payload: Dict[str, Any]) -> None: + import json + + node.token_json = json.dumps(payload) + node.updated = datetime.now(timezone.utc) + await node.save() + + +class IntegralOAuthAuth(httpx.Auth): + """Bears the stored Integral OAuth access token, refreshing when stale.""" + + requires_request_body = False + requires_response_body = False + + def __init__( + self, + *, + server_name: str = INTEGRAL_SERVER, + account_name: str = DEFAULT_ACCOUNT, + scope_id: str = "", + scope: str = "", + issuer: str = "", + mcp_url: str = "", + ) -> None: + self._server_name = server_name + self._account_name = account_name or DEFAULT_ACCOUNT + self._scope_id = (scope_id or "").strip() + self._scope = (scope or "").strip() + self._issuer = (issuer or "").strip() + self._mcp_url = (mcp_url or "").strip() + self._lock = asyncio.Lock() + self._cached_token = "" + self._cached_expiry: Optional[datetime] = None + + def _cache_valid(self) -> bool: + if not self._cached_token: + return False + if self._cached_expiry is None: + return True + return self._cached_expiry > datetime.now(timezone.utc) + timedelta(seconds=30) + + @staticmethod + def _expiry_from_payload(payload: Dict[str, Any]) -> Optional[datetime]: + raw = payload.get("expiry") or "" + if not raw: + return None + try: + expiry = datetime.fromisoformat(str(raw).replace("Z", "+00:00")) + except ValueError: + return None + if expiry.tzinfo is None: + expiry = expiry.replace(tzinfo=timezone.utc) + return expiry + + async def _valid_token(self) -> str: + async with self._lock: + if self._cache_valid(): + return self._cached_token + node, payload = await _load_token_node( + self._server_name, self._account_name + ) + if payload and not payload_is_expired(payload): + self._cached_token = str( + payload.get("access_token") or payload.get("token") or "" + ) + self._cached_expiry = self._expiry_from_payload(payload) + if self._cached_token: + return self._cached_token + if not node or not payload: + raise IntegralOAuthNotConnectedError( + f"No Integral OAuth token stored for " + f"{self._server_name}/{self._account_name}. " + "Connect via the agent's MCPs panel first." + ) + return await self._refresh(node, payload) + + async def _refresh(self, node: Any, payload: Dict[str, Any]) -> str: + refresh_token = str(payload.get("refresh_token") or "") + client_id = str(payload.get("client_id") or "") + if not refresh_token: + raise IntegralOAuthNotConnectedError( + "Stored Integral token has no refresh_token; reconnect via the " + "agent's MCPs panel." + ) + if not client_id: + client = await load_registered_client(self._server_name) + client_id = client.client_id if client else "" + + meta = await discover_authorization_server( + mcp_url=self._mcp_url, issuer=self._issuer + ) + scope = self._scope or resolve_scope() + tokens = await refresh_access_token( + meta, + client_id=client_id, + refresh_token=refresh_token, + scope=scope, + ) + new_payload = normalize_token_payload( + tokens, + client_id=client_id, + token_uri=str(meta.get("token_endpoint") or payload.get("token_uri") or ""), + account_name=self._account_name, + scope=scope, + previous=payload, + ) + # Preserve display metadata from the original payload. + for key in ("account_alias", "email", "mcp_services", "type"): + if payload.get(key) is not None and new_payload.get(key) is None: + new_payload[key] = payload[key] + await _save_token_payload(node, new_payload) + + self._cached_token = str(new_payload.get("access_token") or "") + self._cached_expiry = self._expiry_from_payload(new_payload) + if not self._cached_token: + raise IntegralOAuthNotConnectedError( + "Integral token refresh returned no access token." + ) + logger.info( + "Refreshed Integral OAuth token for %s/%s", + self._server_name, + self._account_name, + ) + return self._cached_token + + async def apply_auth(self, request: httpx.Request) -> None: + """Set the bearer (and optional workspace scope) header on *request*.""" + token = await self._valid_token() + request.headers["Authorization"] = f"Bearer {token}" + if self._scope_id: + request.headers["X-Integral-Scope"] = f"ws:{self._scope_id}" + + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + await self.apply_auth(request) + yield request + + +def _resolve(value: str, env_name: str) -> str: + import os + + if value: + return value.strip() + if env_name: + return (os.getenv(env_name) or "").strip() + return "" + + +def build_integral_oauth_client( + *, + server_name: str = INTEGRAL_SERVER, + account: str = "", + account_env: str = "INTEGRAL_MCP_ACCOUNT", + scope_id: str = "", + scope_id_env: str = "INTEGRAL_MCP_WORKSPACE_ID", + scope: str = "", + issuer: str = "", + issuer_env: str = "INTEGRAL_OAUTH_ISSUER", + mcp_url: str = "", + connect_timeout: float = DEFAULT_CONNECT_TIMEOUT, + read_timeout: float = DEFAULT_READ_TIMEOUT, + transport: httpx.AsyncBaseTransport | None = None, +) -> httpx.AsyncClient: + """Build an ``httpx.AsyncClient`` that bears the stored Integral OAuth token.""" + resolved_account = _resolve(account, account_env) or DEFAULT_ACCOUNT + resolved_scope = _resolve(scope_id, scope_id_env) + resolved_issuer = _resolve(issuer, issuer_env) + timeout = httpx.Timeout( + connect=connect_timeout, read=read_timeout, write=read_timeout, pool=None + ) + auth = IntegralOAuthAuth( + server_name=server_name, + account_name=resolved_account, + scope_id=resolved_scope, + scope=scope, + issuer=resolved_issuer, + mcp_url=mcp_url, + ) + trusted = origin_of(mcp_url) + + async def _ensure_auth(request: httpx.Request) -> None: + # httpx strips ``Authorization`` on *cross-origin* redirects and does + # not re-run a custom Auth flow for that hop. Re-apply the bearer only + # for the configured MCP origin; never restore it on an untrusted hop. + url = str(request.url) + if trusted is not None and not is_trusted_url(url, trusted): + strip_authorization_headers(request) + return + if "authorization" in request.headers: + return + if trusted is None: + # Without a configured mcp_url we cannot safely re-attach credentials. + return + await auth.apply_auth(request) + + kwargs: dict = { + "auth": auth, + "timeout": timeout, + # The MCP SDK raises on any 3xx, so follow same-origin redirects; + # untrusted targets are rejected by the response hook. + "follow_redirects": True, + "event_hooks": { + "request": [_ensure_auth], + "response": [make_redirect_validator(trusted)], + }, + } + if transport is not None: + kwargs["transport"] = transport + return httpx.AsyncClient(**kwargs) diff --git a/jvagent/action/mcp/mcp_action.py b/jvagent/action/mcp/mcp_action.py index 37650319d..2c69c46ff 100644 --- a/jvagent/action/mcp/mcp_action.py +++ b/jvagent/action/mcp/mcp_action.py @@ -266,7 +266,15 @@ class MCPAction(Action): "sandbox_mode, sandbox_user_scoped, sandbox_root, " "show_tools (default true; false keeps the server hosted but omits " "its tools from get_tools / the orchestrator), " - "type (optional: jvspatial_fs | npx_filesystem for stdio filesystem servers)." + "type (optional: jvspatial_fs | npx_filesystem for stdio filesystem servers), " + "auth (optional: {type: service_key, key_env, user_id/user_id_env, " + "workspace_id/workspace_id_env} — signs every streamable_http request " + "with Core's service-key envelope; or {type: oauth, account/account_env, " + "scopes (list) / scope (space-separated string) — the Core OAuth scopes " + "(e.g. integral:read, integral:propose, integral:execute) passed through " + "verbatim; scope_id/scope_id_env, issuer/issuer_env} — bears a stored " + "Integral OAuth 2.1 access token from the MCPs-panel connect flow; the " + "entry url is used for refresh discovery)." ), ) native_read_tools: List[str] = attribute( @@ -431,7 +439,88 @@ async def _build_server_entries(self) -> None: ) args = a else: - if raw.get("auth"): + auth_cfg = ( + raw.get("auth") if isinstance(raw.get("auth"), dict) else None + ) + http_client = None + if ( + auth_cfg + and str(auth_cfg.get("type") or "").strip().lower() == "service_key" + ): + from jvagent.action.mcp.service_key_auth import ( + build_service_key_client, + ) + + try: + http_client = build_service_key_client( + service_key=str(auth_cfg.get("service_key") or ""), + key_env=str( + auth_cfg.get("key_env") or "INTEGRAL_SERVICE_KEY" + ), + user_id=str(auth_cfg.get("user_id") or ""), + user_id_env=str( + auth_cfg.get("user_id_env") + or "INTEGRAL_SERVICE_USER_ID" + ), + workspace_id=str(auth_cfg.get("workspace_id") or ""), + workspace_id_env=str( + auth_cfg.get("workspace_id_env") + or "INTEGRAL_WORKSPACE_ID" + ), + mcp_url=str(raw.get("url") or ""), + connect_timeout=connect_timeout, + read_timeout=call_timeout, + ) + except ValueError as exc: + logger.warning( + "MCPAction: disabling server '%s' — service-key auth " + "not configured: %s", + name, + exc, + ) + continue + elif ( + auth_cfg + and str(auth_cfg.get("type") or "").strip().lower() == "oauth" + ): + from jvagent.action.mcp.integral_oauth_auth import ( + build_integral_oauth_client, + ) + from jvagent.action.mcp_oauth.integral_provider import ( + resolve_scopes_from_auth, + ) + + resolved_scopes = resolve_scopes_from_auth(auth_cfg) + try: + http_client = build_integral_oauth_client( + server_name=name, + account=str(auth_cfg.get("account") or ""), + account_env=str( + auth_cfg.get("account_env") or "INTEGRAL_MCP_ACCOUNT" + ), + scope_id=str(auth_cfg.get("scope_id") or ""), + scope_id_env=str( + auth_cfg.get("scope_id_env") + or "INTEGRAL_MCP_WORKSPACE_ID" + ), + scope=resolved_scopes, + issuer=str(auth_cfg.get("issuer") or ""), + issuer_env=str( + auth_cfg.get("issuer_env") or "INTEGRAL_OAUTH_ISSUER" + ), + mcp_url=str(raw.get("url") or ""), + connect_timeout=connect_timeout, + read_timeout=call_timeout, + ) + except ValueError as exc: + logger.warning( + "MCPAction: disabling server '%s' — integral oauth " + "not configured: %s", + name, + exc, + ) + continue + elif auth_cfg: raise ValueError( "Vendor MCP auth profiles are unsupported; configure " "authentication through an external MCP integration" @@ -444,6 +533,7 @@ async def _build_server_entries(self) -> None: url=url, connect_timeout=connect_timeout, call_timeout=call_timeout, + http_client=http_client, ) ulock = asyncio.Lock() diff --git a/jvagent/action/mcp/redirect_trust.py b/jvagent/action/mcp/redirect_trust.py new file mode 100644 index 000000000..251b1fafe --- /dev/null +++ b/jvagent/action/mcp/redirect_trust.py @@ -0,0 +1,91 @@ +"""Trusted-origin checks for credentialed MCP httpx redirect hops. + +httpx follows redirects with ``follow_redirects=True``. It strips standard +``Authorization`` on cross-origin hops, but custom ``X-Integral-*`` headers are +forwarded. Request hooks that re-attach credentials must therefore only run for +the configured MCP origin, and untrusted 3xx targets must be rejected before the +next hop is sent. +""" + +from __future__ import annotations + +from typing import Optional, Tuple +from urllib.parse import urlsplit + +import httpx + +# (scheme_lower, hostname_lower, port) +Origin = Tuple[str, str, int] + +_SERVICE_KEY_HEADERS = ( + "x-integral-service-key", + "x-integral-user-id", + "x-integral-timestamp", + "x-integral-signature", + "x-integral-scope", +) + + +class UntrustedRedirectError(RuntimeError): + """Raised when a redirect would leave the trusted MCP origin.""" + + +def origin_of(url: str) -> Optional[Origin]: + """Return ``(scheme, host, port)`` for *url*, or ``None`` if incomplete.""" + raw = (url or "").strip() + if not raw: + return None + parts = urlsplit(raw) + scheme = (parts.scheme or "").lower() + host = (parts.hostname or "").lower() + if not scheme or not host: + return None + port = parts.port + if port is None: + port = 443 if scheme == "https" else 80 if scheme == "http" else 0 + return scheme, host, int(port) + + +def is_trusted_url(url: str, trusted: Optional[Origin]) -> bool: + """True when *url* matches *trusted* and is not an HTTPS→HTTP downgrade.""" + if trusted is None: + return False + current = origin_of(url) + if current is None: + return False + scheme, host, port = current + t_scheme, t_host, t_port = trusted + if scheme == "http" and t_scheme == "https": + return False + return scheme == t_scheme and host == t_host and port == t_port + + +def strip_authorization_headers(request: httpx.Request) -> None: + for name in ("authorization", "x-integral-scope"): + if name in request.headers: + del request.headers[name] + + +def strip_service_key_headers(request: httpx.Request) -> None: + for name in _SERVICE_KEY_HEADERS: + if name in request.headers: + del request.headers[name] + + +def make_redirect_validator(trusted: Optional[Origin]): + """Return an httpx response hook that rejects untrusted 3xx targets.""" + + async def _validate_redirect(response: httpx.Response) -> None: + if not (300 <= response.status_code < 400): + return + loc = response.headers.get("location") + if not loc: + return + target = str(httpx.URL(response.url).join(loc)) + baseline = trusted or origin_of(str(response.url)) + if not is_trusted_url(target, baseline): + raise UntrustedRedirectError( + f"Refusing credentialed MCP redirect to untrusted origin: {target}" + ) + + return _validate_redirect diff --git a/jvagent/action/mcp/service_key_auth.py b/jvagent/action/mcp/service_key_auth.py new file mode 100644 index 000000000..c5f1ca660 --- /dev/null +++ b/jvagent/action/mcp/service_key_auth.py @@ -0,0 +1,159 @@ +"""httpx auth flow that signs MCP requests with Core's service-key envelope. + +Integral Core's ``ServiceAuthMiddleware`` authenticates ``/api/mcp`` (and +``/api/agentive/*``) requests carrying:: + + X-Integral-Service-Key shared secret (== Core INTEGRAL_SERVICE_KEY) + X-Integral-User-Id the principal the key acts as + X-Integral-Timestamp unix seconds (within 300s of Core) + X-Integral-Signature HMAC-SHA256(key, "{timestamp}.{user_id}") + X-Integral-Scope optional "ws:" scope hint + +The timestamp + signature are per-request, so a static header dict cannot be +used. ``ServiceKeyAuth`` recomputes them on every request via httpx's auth flow, +and is installed on an ``httpx.AsyncClient`` that is passed to the MCP SDK's +``streamable_http_client``. +""" + +from __future__ import annotations + +import hashlib +import hmac +import os +import time +from typing import AsyncGenerator + +import httpx + +from jvagent.action.mcp.redirect_trust import ( + is_trusted_url, + make_redirect_validator, + origin_of, + strip_service_key_headers, +) + +DEFAULT_CONNECT_TIMEOUT = 10.0 +DEFAULT_READ_TIMEOUT = 60.0 + + +def compute_signature(service_key: str, timestamp: str, user_id: str) -> str: + """Canonical HMAC-SHA256 over ``{timestamp}.{user_id}`` (mirrors Core).""" + return hmac.new( + service_key.encode("utf-8"), + f"{timestamp}.{user_id}".encode("utf-8"), + hashlib.sha256, + ).hexdigest() + + +class ServiceKeyAuth(httpx.Auth): + """Signs every request with Core's service-key envelope.""" + + def __init__( + self, + service_key: str, + user_id: str, + workspace_id: str = "", + ) -> None: + if not service_key: + raise ValueError("service_key is required") + if not user_id: + raise ValueError("user_id is required") + self._service_key = service_key + self._user_id = user_id + self._workspace_id = (workspace_id or "").strip() + + def apply_auth(self, request: httpx.Request) -> None: + """Sign *request* with a fresh timestamp + HMAC.""" + timestamp = str(int(time.time())) + request.headers["X-Integral-Service-Key"] = self._service_key + request.headers["X-Integral-User-Id"] = self._user_id + request.headers["X-Integral-Timestamp"] = timestamp + request.headers["X-Integral-Signature"] = compute_signature( + self._service_key, timestamp, self._user_id + ) + if self._workspace_id: + request.headers["X-Integral-Scope"] = f"ws:{self._workspace_id}" + + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + self.apply_auth(request) + yield request + + +def _resolve(value: str, env_name: str) -> str: + """Return the literal *value*, else the env var named by *env_name*.""" + if value: + return value.strip() + if env_name: + return (os.getenv(env_name) or "").strip() + return "" + + +def build_service_key_client( + *, + service_key: str = "", + key_env: str = "INTEGRAL_SERVICE_KEY", + user_id: str = "", + user_id_env: str = "INTEGRAL_SERVICE_USER_ID", + workspace_id: str = "", + workspace_id_env: str = "INTEGRAL_WORKSPACE_ID", + mcp_url: str = "", + connect_timeout: float = DEFAULT_CONNECT_TIMEOUT, + read_timeout: float = DEFAULT_READ_TIMEOUT, + transport: httpx.AsyncBaseTransport | None = None, +) -> httpx.AsyncClient: + """Build an ``httpx.AsyncClient`` that signs every request for Core. + + Values may be given literally or via an env-var name (``*_env``). Raises + ``ValueError`` when the service key or user id cannot be resolved, so a + misconfigured server entry fails loudly at build time. + """ + resolved_key = _resolve(service_key, key_env) + resolved_user = _resolve(user_id, user_id_env) + resolved_ws = _resolve(workspace_id, workspace_id_env) + if not resolved_key: + raise ValueError( + "MCP service-key auth is not configured: " + f"set '{key_env}' (or a literal service_key)" + ) + if not resolved_user: + raise ValueError( + "MCP service-key auth is missing a user id: " + f"set '{user_id_env}' (or a literal user_id)" + ) + timeout = httpx.Timeout( + connect=connect_timeout, read=read_timeout, write=read_timeout, pool=None + ) + auth = ServiceKeyAuth(resolved_key, resolved_user, resolved_ws) + trusted = origin_of(mcp_url) + + async def _ensure_service_key(request: httpx.Request) -> None: + # Custom X-Integral-* headers are NOT stripped by httpx on cross-origin + # redirects. Only re-sign for the configured MCP origin; strip secrets + # and refuse to attach them on any other hop. + url = str(request.url) + if trusted is not None and not is_trusted_url(url, trusted): + strip_service_key_headers(request) + return + if "x-integral-service-key" in request.headers: + if trusted is None or is_trusted_url(url, trusted): + return + strip_service_key_headers(request) + return + if trusted is None: + return + auth.apply_auth(request) + + kwargs: dict = { + "auth": auth, + "timeout": timeout, + "follow_redirects": True, + "event_hooks": { + "request": [_ensure_service_key], + "response": [make_redirect_validator(trusted)], + }, + } + if transport is not None: + kwargs["transport"] = transport + return httpx.AsyncClient(**kwargs) diff --git a/jvagent/action/mcp_oauth/endpoints.py b/jvagent/action/mcp_oauth/endpoints.py index bad079369..272ab0a53 100644 --- a/jvagent/action/mcp_oauth/endpoints.py +++ b/jvagent/action/mcp_oauth/endpoints.py @@ -15,6 +15,22 @@ from jvagent.action.oauth.state import consume_oauth_state, create_oauth_state from jvagent.core.public_url import get_public_base_url +from .integral_provider import ( + INTEGRAL_LABEL, + INTEGRAL_SERVER, + INTEGRAL_SERVICE, + build_authorize_url, + discover_authorization_server, + ensure_registered_client, + exchange_authorization_code, + load_registered_client, + normalize_token_payload, + pkce_challenge, + pkce_verifier, + resolve_mcp_url, + resolve_scopes_from_auth, + resolve_token_identity, +) from .mcp_oauth_action import ( MCPOAuthAction, mcp_oauth_state_action_id, @@ -148,6 +164,52 @@ async def _enabled_microsoft_oauth_services( ) +async def _integral_mcp_url() -> str: + """Resolve the configured Integral MCP server URL from MCPAction.""" + try: + from jvspatial.core.context import GraphContext + from jvspatial.db import get_database_manager + + from jvagent.action.mcp.mcp_action import MCPAction + + manager = get_database_manager() + db = manager.get_database() + ctx = GraphContext(db) + nodes = await ctx.find_nodes(MCPAction, {}) + mcp = nodes[0] if nodes else None + for raw in getattr(mcp, "servers", None) or []: + if isinstance(raw, dict) and str(raw.get("name") or "") == INTEGRAL_SERVER: + url = str(raw.get("url") or "").strip() + if url: + return url + except Exception as exc: + logger.debug("Failed to read MCPAction Integral url: %s", exc) + return resolve_mcp_url() + + +async def _integral_auth_cfg() -> Dict[str, Any]: + """Return the ``integral_core`` server's ``auth`` block, if configured.""" + try: + from jvspatial.core.context import GraphContext + from jvspatial.db import get_database_manager + + from jvagent.action.mcp.mcp_action import MCPAction + + manager = get_database_manager() + db = manager.get_database() + ctx = GraphContext(db) + nodes = await ctx.find_nodes(MCPAction, {}) + mcp = nodes[0] if nodes else None + for raw in getattr(mcp, "servers", None) or []: + if isinstance(raw, dict) and str(raw.get("name") or "") == INTEGRAL_SERVER: + auth = raw.get("auth") + if isinstance(auth, dict): + return auth + except Exception as exc: + logger.debug("Failed to read MCPAction Integral auth: %s", exc) + return {} + + def _microsoft_client() -> Dict[str, str]: cid = microsoft_client_id() if not cid: @@ -390,7 +452,11 @@ def _oauth_error_html(message: str, status_code: int = 400) -> HTMLResponse: ) async def get_mcp_auth_status(server_name: str) -> Dict[str, Any]: """Return per-service connected emails for an MCP OAuth server.""" - supported = server_name in (GOOGLE_WORKSPACE_SERVER, MICROSOFT_365_SERVER) + supported = server_name in ( + GOOGLE_WORKSPACE_SERVER, + MICROSOFT_365_SERVER, + INTEGRAL_SERVER, + ) bindings: Dict[str, Dict[str, str]] = {} if supported: action = await _get_mcp_oauth_action() @@ -411,17 +477,22 @@ async def get_mcp_auth_status(server_name: str) -> Dict[str, Any]: summary="Get OAuth Authorization URL for MCP Server", ) async def get_mcp_auth_url( - server_name: str, account: str = "default", service: str = "" + server_name: str, account: str = "integral", service: str = "" ) -> HTMLResponse: """Generate the OAuth2 authorization page for a stdio MCP server.""" action = await _get_mcp_oauth_action() if not action or not action.enabled: raise ResourceNotFoundError(message="MCPOAuthAction not enabled or found.") - if server_name not in (GOOGLE_WORKSPACE_SERVER, MICROSOFT_365_SERVER): + if server_name not in ( + GOOGLE_WORKSPACE_SERVER, + MICROSOFT_365_SERVER, + INTEGRAL_SERVER, + ): return _oauth_error_html( f"OAuth is not supported for server '{server_name}'. " - f"Supported: '{GOOGLE_WORKSPACE_SERVER}', '{MICROSOFT_365_SERVER}'.", + f"Supported: '{GOOGLE_WORKSPACE_SERVER}', '{MICROSOFT_365_SERVER}', " + f"'{INTEGRAL_SERVER}'.", 400, ) @@ -436,6 +507,10 @@ async def get_mcp_auth_url( return await _microsoft_auth_page( action, account=account, service=service, redirect_uri=redirect_uri ) + if server_name == INTEGRAL_SERVER: + return await _integral_auth_page( + action, account=account, service=service, redirect_uri=redirect_uri + ) return await _google_auth_page( action, account=account, service=service, redirect_uri=redirect_uri ) @@ -549,6 +624,66 @@ async def _microsoft_auth_page( ) +async def _integral_auth_page( + action: MCPOAuthAction, + *, + account: str, + service: str, + redirect_uri: str, +) -> HTMLResponse: + """Build the Integral Core (OAuth 2.1 / DCR + PKCE) authorization page.""" + scope = resolve_scopes_from_auth(await _integral_auth_cfg()) + mcp_url = await _integral_mcp_url() + try: + client_id, meta = await ensure_registered_client( + server_name=INTEGRAL_SERVER, + redirect_uri=redirect_uri, + scope=scope, + mcp_url=mcp_url, + ) + except Exception as exc: + logger.error("Integral OAuth client registration failed: %s", exc) + return _oauth_error_html(str(exc), 400) + + verifier = pkce_verifier() + challenge = pkce_challenge(verifier) + state_token = await create_oauth_state( + action_id=mcp_oauth_state_action_id(account, service), + provider="mcp_integral", + code_verifier=verifier, + redirect_uri=redirect_uri, + ) + try: + auth_url = build_authorize_url( + meta, + client_id=client_id, + redirect_uri=redirect_uri, + state=state_token, + code_challenge=challenge, + scope=scope, + ) + except Exception as exc: + logger.error("Integral authorize URL build failed: %s", exc) + return _oauth_error_html(str(exc), 400) + + issuer = str(meta.get("issuer") or "").strip() + access_copy = ( + "Connect this agent to Integral Core. You'll be asked to sign in to " + "Integral and approve access, then the agent can file leads and query " + "entries on your behalf." + ) + if issuer: + access_copy = f"{access_copy} (Authorization server: {issuer})" + return await _grant_html( + action, + title="Integral Core Authorization", + heading="Connect to Integral Core", + access_copy=access_copy, + button_label="Authorize with Integral", + auth_url=auth_url, + ) + + async def _grant_html( action: MCPOAuthAction, *, @@ -610,6 +745,8 @@ async def mcp_oauth_callback(server_name: str, code: str, state: str) -> HTMLRes provider = "mcp_google" elif server_name == MICROSOFT_365_SERVER: provider = "mcp_microsoft" + elif server_name == INTEGRAL_SERVER: + provider = "mcp_integral" else: return _oauth_error_html( f"OAuth is not supported for server '{server_name}'.", @@ -627,6 +764,10 @@ async def mcp_oauth_callback(server_name: str, code: str, state: str) -> HTMLRes result = await _exchange_microsoft_code( action, code, record, account_name, service=service ) + elif server_name == INTEGRAL_SERVER: + result = await _exchange_integral_code( + action, code, record, account_name, service=service + ) else: result = await _exchange_google_code( action, code, record, account_name, service=service @@ -696,7 +837,10 @@ async def _exchange_google_code( ) scopes = granted_scopes_from_token_response(tokens, fallback_scopes) - # Preserve the upstream access-token expiry fix without a vendor provider. + # Persist the access-token expiry. Without it google-auth's + # ``from_authorized_user_info`` defaults expiry to ``utcnow() - 3:45`` and + # every freshly authorized token is treated as already expired, forcing an + # immediate refresh on first use. Mirror the Microsoft branch below. expires_in = int(tokens.get("expires_in") or 3600) expiry = datetime.now(timezone.utc) + timedelta(seconds=max(0, expires_in - 60)) @@ -853,3 +997,65 @@ async def _exchange_microsoft_code( else "Microsoft 365" ) return store_account, label + + +async def _exchange_integral_code( + action: MCPOAuthAction, + code: str, + record: Any, + account_name: str, + service: str = "", +) -> HTMLResponse | tuple[str, str]: + """Exchange an Integral authorization code (public client + PKCE).""" + mcp_url = await _integral_mcp_url() + try: + meta = await discover_authorization_server(mcp_url=mcp_url) + except Exception as exc: + return _oauth_error_html(f"Integral OAuth discovery failed: {exc}", 400) + + client = await load_registered_client(INTEGRAL_SERVER) + if not client or not client.client_id: + return _oauth_error_html( + "No registered Integral OAuth client. Restart the connect flow from " + "the MCPs panel.", + 400, + ) + + logger.info("Exchanging Integral auth code for tokens (account: %s)", account_name) + try: + tokens = await exchange_authorization_code( + meta, + client_id=client.client_id, + code=code, + code_verifier=record.code_verifier or "", + redirect_uri=record.redirect_uri, + ) + except Exception as exc: + logger.error("Integral token exchange failed: %s", exc) + return _oauth_error_html(str(exc), 400) + + store_account = (account_name or INTEGRAL_SERVICE).strip() or INTEGRAL_SERVICE + payload = normalize_token_payload( + tokens, + client_id=client.client_id, + token_uri=str(meta.get("token_endpoint") or ""), + account_name=store_account, + scope=resolve_scopes_from_auth(await _integral_auth_cfg()), + ) + if service: + payload["mcp_services"] = [service] + + # Label the connection with the Core account that authorized it. Without + # this the panel falls back to the storage key ("integral") because the + # token payload carries no email. + identity = await resolve_token_identity( + mcp_url, str(payload.get("access_token") or ""), meta + ) + if identity.get("email"): + payload["email"] = identity["email"] + + # Store the token flat (not nested under ``service_tokens``) so the bearer + # auth client can read ``access_token`` directly. ``mcp_services`` still + # drives the MCPs-panel binding display. + await action.save_oauth_token(INTEGRAL_SERVER, store_account, payload) + return identity.get("email") or store_account, INTEGRAL_LABEL diff --git a/jvagent/action/mcp_oauth/integral_provider.py b/jvagent/action/mcp_oauth/integral_provider.py new file mode 100644 index 000000000..0ba429b50 --- /dev/null +++ b/jvagent/action/mcp_oauth/integral_provider.py @@ -0,0 +1,660 @@ +"""Generic OAuth 2.1 provider for Integral Core's MCP endpoint. + +Unlike the Google/Microsoft providers (:mod:`hydrate`, :mod:`microsoft_hydrate`), +which use a *static* pre-registered ``client_id`` and hydrate token files onto a +stdio subprocess, Integral Core is an **OAuth 2.1 authorization server** in the +sense of the MCP authorization spec: + +* **Dynamic Client Registration** (RFC 7591) with open registration and public + clients (``token_endpoint_auth_method=none``) — no client secret. +* **PKCE** (RFC 7636) with ``S256`` — mandatory for public clients. +* **Discovery** via ``/.well-known/oauth-protected-resource`` (RFC 9728) and + ``/.well-known/oauth-authorization-server`` (RFC 8414), both served at the + Core root. +* The resulting access token is used directly as ``Authorization: Bearer`` on + the ``streamable_http`` MCP client (see :mod:`jvagent.action.mcp.integral_oauth_auth`); + there is no disk hydration step. + +Endpoints (Core defaults, see ``app/main.py`` / jvspatial ``oauth_prefix``): +authorize ``/api/oauth/authorize``, token ``/api/oauth/token``, register +``/api/oauth/register``. Discovery is preferred; the literal path layout is only +a fallback for when the ``/.well-known`` documents are not reachable (e.g. a +reverse proxy that forwards only ``/api``). +""" + +from __future__ import annotations + +import base64 +import hashlib +import logging +import os +import re +import secrets +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, Optional, Tuple, cast +from urllib.parse import urlencode, urlparse + +import httpx +from jvspatial.core import Node +from jvspatial.core.annotations import attribute + +logger = logging.getLogger(__name__) + +INTEGRAL_SERVER = "integral_core" +INTEGRAL_SERVICE = "integral" +INTEGRAL_LABEL = "Integral" +DEFAULT_ACCOUNT = "integral" + +# Fallback OAuth path prefix when discovery documents are unreachable. Matches +# jvspatial's advertised ``{issuer}/api/oauth/*`` layout (AuthConfig default +# ``oauth_prefix="/oauth"`` mounted under the ``/api`` API prefix). +_FALLBACK_OAUTH_PREFIX = "/api/oauth" + +DEFAULT_TIMEOUT = 15.0 + +# Treat a token as expired this many seconds before its real expiry so a +# request never races the clock. +_EXPIRY_SKEW_SECONDS = 60 + + +class IntegralOAuthServiceError(RuntimeError): + """Raised when discovery / registration / token exchange fails.""" + + +class IntegralOAuthClient(Node): + """Persisted Dynamic Client Registration for one Integral MCP server. + + A DCR registration is reusable across connect flows; persisting it avoids + re-registering on every auth-page load and sidesteps the server's DCR + rate limit. + """ + + server_name: str = attribute( + indexed=True, + default=INTEGRAL_SERVER, + description="MCP server name this registration belongs to.", + ) + client_id: str = attribute( + default="", + description="DCR-issued public client identifier.", + ) + redirect_uri: str = attribute( + default="", + description="Redirect URI the client was registered with.", + ) + scope: str = attribute( + default="", + description="Space-delimited scope registered with the client.", + ) + metadata_json: str = attribute( + default="", + description="Serialized authorization-server metadata discovered at register time.", + ) + + +# --------------------------------------------------------------------------- +# URL helpers +# --------------------------------------------------------------------------- + + +def mcp_integral_core_auth_url( + account: str = DEFAULT_ACCOUNT, + service: Optional[str] = None, + base_url: Optional[str] = None, +) -> str: + """Public browser URL for the Integral MCP OAuth start page.""" + from jvagent.core.public_url import get_public_base_url + + base = (base_url or get_public_base_url() or "").rstrip("/") + params = [] + if account: + params.append(f"account={account}") + if service: + params.append(f"service={service}") + q = f"?{'&'.join(params)}" if params else "" + return f"{base}/api/mcp/{INTEGRAL_SERVER}/auth{q}" + + +def _origin(url: str) -> str: + """Return ``scheme://host[:port]`` for *url* (no trailing slash).""" + parsed = urlparse((url or "").strip()) + if not parsed.scheme or not parsed.netloc: + return "" + return f"{parsed.scheme}://{parsed.netloc}" + + +def resolve_mcp_url(mcp_url: str = "") -> str: + """Resolve the Integral MCP URL from config or the environment. + + Priority: explicit *mcp_url* → ``INTEGRAL_CORE_MCP_URL`` → + ``INTEGRAL_MCP_URL`` → ``http://127.0.0.1:9006/api/mcp/`` (Core's stable web + port via the bundled reverse proxy). + """ + candidate = (mcp_url or "").strip() + if not candidate: + candidate = ( + os.environ.get("INTEGRAL_CORE_MCP_URL") + or os.environ.get("INTEGRAL_MCP_URL") + or "" + ).strip() + return candidate or "http://127.0.0.1:9006/api/mcp/" + + +def resolve_issuer_override(issuer: str = "") -> str: + """Resolve an explicit authorization-server issuer, if configured.""" + candidate = (issuer or "").strip() + if not candidate: + candidate = (os.environ.get("INTEGRAL_OAUTH_ISSUER") or "").strip() + return candidate.rstrip("/") + + +def resolve_scope(scope: str = "") -> str: + """Resolve the OAuth scope string (may legitimately be empty).""" + candidate = (scope or "").strip() + if not candidate: + candidate = (os.environ.get("INTEGRAL_OAUTH_SCOPE") or "").strip() + return candidate + + +# Scopes are authored on the MCP server entry (``auth.scopes`` / ``auth.scope``) +# and forwarded to Core *verbatim* — no aliasing or filtering. Core intersects +# the requested scope with its own ``OAUTH_SUPPORTED_SCOPES`` ceiling, so adding +# or renaming a scope never requires a code change here. + + +def join_scopes(value: Any) -> str: + """Join a scope config value into a space-separated string, verbatim. + + Accepts a list/tuple/set (or a space/comma-separated string). Each token is + stripped and passed through unchanged — no aliasing, case-folding, or + filtering — so any scope Core advertises (or later adds) can be authored + directly on the server entry. Order is preserved; empties are dropped. + """ + if value is None: + return "" + if isinstance(value, str): + tokens = [t for t in re.split(r"[,\s]+", value) if t] + elif isinstance(value, (list, tuple, set)): + tokens = [str(t) for t in value if str(t).strip()] + else: + tokens = [str(value)] + return " ".join(str(t).strip() for t in tokens if str(t).strip()) + + +def resolve_scopes_from_auth(auth_cfg: Optional[Dict[str, Any]]) -> str: + """Resolve the requested scope from a server ``auth`` block, else the env. + + Precedence: ``auth.scopes`` (list) → ``auth.scope`` (string) → + ``INTEGRAL_OAUTH_SCOPE`` env (via :func:`resolve_scope`). Values are passed + through verbatim. + """ + if isinstance(auth_cfg, dict): + if auth_cfg.get("scopes"): + return join_scopes(auth_cfg.get("scopes")) + if auth_cfg.get("scope"): + return join_scopes(auth_cfg.get("scope")) + return resolve_scope() + + +# --------------------------------------------------------------------------- +# Discovery +# --------------------------------------------------------------------------- + + +def fallback_metadata(origin: str) -> Dict[str, Any]: + """Construct AS metadata from the origin when discovery docs are unreachable.""" + base = origin.rstrip("/") + ep_base = f"{base}{_FALLBACK_OAUTH_PREFIX}" + return { + "issuer": base, + "authorization_endpoint": f"{ep_base}/authorize", + "token_endpoint": f"{ep_base}/token", + "registration_endpoint": f"{ep_base}/register", + "jwks_uri": f"{base}/.well-known/jwks.json", + "code_challenge_methods_supported": ["S256"], + "grant_types_supported": ["authorization_code", "refresh_token"], + } + + +async def _get_json(client: httpx.AsyncClient, url: str) -> Optional[Dict[str, Any]]: + """GET *url* and return a JSON object, or ``None`` on any failure.""" + try: + resp = await client.get(url, headers={"Accept": "application/json"}) + except Exception as exc: # network / DNS / TLS + logger.debug("Integral OAuth discovery GET failed (%s): %s", url, exc) + return None + if resp.status_code != 200: + logger.debug("Integral OAuth discovery GET %s -> %s", url, resp.status_code) + return None + try: + data = resp.json() + except Exception: + return None + return data if isinstance(data, dict) else None + + +async def discover_authorization_server( + *, + mcp_url: str = "", + issuer: str = "", + timeout: float = DEFAULT_TIMEOUT, +) -> Dict[str, Any]: + """Discover Core's authorization-server metadata. + + Order: explicit *issuer* override → ``/.well-known/oauth-protected-resource`` + → ``/.well-known/oauth-authorization-server`` → a constructed fallback based + on the MCP origin. Always returns a usable dict (raising only when no origin + can be determined). + """ + override = resolve_issuer_override(issuer) + if override: + return await _metadata_for_issuer(override, timeout=timeout) + + origin = _origin(resolve_mcp_url(mcp_url)) + if not origin: + raise IntegralOAuthServiceError( + "Cannot discover Integral OAuth endpoints: no MCP URL configured." + ) + + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client: + prm = await _get_json(client, f"{origin}/.well-known/oauth-protected-resource") + as_issuer = "" + if prm: + servers = prm.get("authorization_servers") or [] + if isinstance(servers, list) and servers: + as_issuer = str(servers[0]).strip().rstrip("/") + + if as_issuer and as_issuer != origin: + meta = await _metadata_for_issuer(as_issuer, timeout=timeout) + if meta.get("token_endpoint"): + return meta + + direct = await _get_json( + client, f"{origin}/.well-known/oauth-authorization-server" + ) + if direct and direct.get("token_endpoint"): + return direct + + logger.warning( + "Integral OAuth discovery docs unreachable at %s; " + "falling back to %s/* layout", + origin, + _FALLBACK_OAUTH_PREFIX, + ) + return fallback_metadata(origin) + + +async def _metadata_for_issuer( + issuer: str, *, timeout: float = DEFAULT_TIMEOUT +) -> Dict[str, Any]: + """Fetch AS metadata for a known *issuer*, else synthesize it.""" + issuer = issuer.rstrip("/") + async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client: + meta = await _get_json( + client, f"{issuer}/.well-known/oauth-authorization-server" + ) + if meta and meta.get("token_endpoint"): + return meta + return fallback_metadata(issuer) + + +# --------------------------------------------------------------------------- +# Dynamic Client Registration +# --------------------------------------------------------------------------- + + +async def register_client( + meta: Dict[str, Any], + *, + redirect_uri: str, + scope: str = "", + client_name: str = "jvagent", + timeout: float = DEFAULT_TIMEOUT, +) -> str: + """Register a public client via DCR; return the ``client_id``.""" + endpoint = str(meta.get("registration_endpoint") or "").strip() + if not endpoint: + raise IntegralOAuthServiceError( + "Authorization-server metadata has no registration_endpoint." + ) + body: Dict[str, Any] = { + "client_name": client_name, + "redirect_uris": [redirect_uri], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + } + if scope: + body["scope"] = scope + if "S256" in (meta.get("code_challenge_methods_supported") or []): + pass # PKCE S256 is advertised; nothing to declare at registration. + + async with httpx.AsyncClient(timeout=timeout) as client: + resp = await client.post( + endpoint, json=body, headers={"Accept": "application/json"} + ) + if resp.status_code not in (200, 201): + raise IntegralOAuthServiceError( + f"Dynamic client registration failed ({resp.status_code}): {resp.text}" + ) + data = resp.json() + client_id = str((data or {}).get("client_id") or "").strip() + if not client_id: + raise IntegralOAuthServiceError( + "Dynamic client registration response carried no client_id." + ) + return client_id + + +async def load_registered_client( + server_name: str = INTEGRAL_SERVER, +) -> Optional[IntegralOAuthClient]: + """Return the persisted DCR client for *server_name*, if any.""" + try: + rows = await IntegralOAuthClient.find({"context.server_name": server_name}) + except Exception as exc: + logger.debug("Integral DCR client lookup failed: %s", exc) + return None + return cast(IntegralOAuthClient, rows[0]) if rows else None + + +async def save_registered_client( + *, + server_name: str, + client_id: str, + redirect_uri: str, + scope: str, + meta: Dict[str, Any], +) -> None: + """Persist (or update) the DCR client for *server_name*.""" + import json + + existing = await load_registered_client(server_name) + payload = json.dumps(meta or {}) + if existing: + existing.client_id = client_id + existing.redirect_uri = redirect_uri + existing.scope = scope + existing.metadata_json = payload + await existing.save() + return + await IntegralOAuthClient.create( + server_name=server_name, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + metadata_json=payload, + ) + + +async def ensure_registered_client( + *, + server_name: str = INTEGRAL_SERVER, + redirect_uri: str, + scope: str = "", + mcp_url: str = "", + issuer: str = "", + force: bool = False, +) -> Tuple[str, Dict[str, Any]]: + """Return ``(client_id, as_metadata)``, registering via DCR when needed.""" + existing = None if force else await load_registered_client(server_name) + if ( + existing + and existing.client_id + and existing.redirect_uri == redirect_uri + and (existing.scope or "") == scope + ): + meta = await discover_authorization_server(mcp_url=mcp_url, issuer=issuer) + return existing.client_id, meta + + meta = await discover_authorization_server(mcp_url=mcp_url, issuer=issuer) + client_id = await register_client(meta, redirect_uri=redirect_uri, scope=scope) + await save_registered_client( + server_name=server_name, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + meta=meta, + ) + logger.info( + "Registered Integral OAuth client for %s (client_id=%s…)", + server_name, + client_id[:8], + ) + return client_id, meta + + +# --------------------------------------------------------------------------- +# PKCE +# --------------------------------------------------------------------------- + + +def pkce_verifier(nbytes: int = 64) -> str: + """Return an RFC 7636 ``code_verifier`` (43-128 unreserved characters).""" + return secrets.token_urlsafe(nbytes) + + +def pkce_challenge(verifier: str) -> str: + """Return the ``S256`` ``code_challenge`` for *verifier*.""" + digest = hashlib.sha256(verifier.encode("ascii")).digest() + return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") + + +# --------------------------------------------------------------------------- +# Authorization URL, token exchange, refresh +# --------------------------------------------------------------------------- + + +def build_authorize_url( + meta: Dict[str, Any], + *, + client_id: str, + redirect_uri: str, + state: str, + code_challenge: str, + scope: str = "", +) -> str: + """Build the authorization-code URL with a PKCE S256 challenge.""" + endpoint = str(meta.get("authorization_endpoint") or "").strip() + if not endpoint: + raise IntegralOAuthServiceError( + "Authorization-server metadata has no authorization_endpoint." + ) + params = { + "response_type": "code", + "client_id": client_id, + "redirect_uri": redirect_uri, + "state": state, + "code_challenge": code_challenge, + "code_challenge_method": "S256", + } + if scope: + params["scope"] = scope + return f"{endpoint}?{urlencode(params)}" + + +async def exchange_authorization_code( + meta: Dict[str, Any], + *, + client_id: str, + code: str, + code_verifier: str, + redirect_uri: str, + timeout: float = DEFAULT_TIMEOUT, +) -> Dict[str, Any]: + """Exchange an authorization code for tokens (public client + PKCE).""" + endpoint = str(meta.get("token_endpoint") or "").strip() + if not endpoint: + raise IntegralOAuthServiceError( + "Authorization-server metadata has no token_endpoint." + ) + data = { + "grant_type": "authorization_code", + "code": code, + "client_id": client_id, + "redirect_uri": redirect_uri, + "code_verifier": code_verifier, + } + async with httpx.AsyncClient(timeout=timeout) as client: + resp = await client.post( + endpoint, data=data, headers={"Accept": "application/json"} + ) + if resp.status_code != 200: + raise IntegralOAuthServiceError( + f"Integral token exchange failed ({resp.status_code}): {resp.text}" + ) + tokens = resp.json() + if not isinstance(tokens, dict) or not tokens.get("access_token"): + raise IntegralOAuthServiceError( + "Integral token exchange returned no access_token." + ) + return tokens + + +async def refresh_access_token( + meta: Dict[str, Any], + *, + client_id: str, + refresh_token: str, + scope: str = "", + timeout: float = DEFAULT_TIMEOUT, +) -> Dict[str, Any]: + """Refresh an access token (public client; no PKCE on refresh).""" + endpoint = str(meta.get("token_endpoint") or "").strip() + if not endpoint: + raise IntegralOAuthServiceError( + "Authorization-server metadata has no token_endpoint." + ) + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "client_id": client_id, + } + if scope: + data["scope"] = scope + async with httpx.AsyncClient(timeout=timeout) as client: + resp = await client.post( + endpoint, data=data, headers={"Accept": "application/json"} + ) + if resp.status_code != 200: + raise IntegralOAuthServiceError( + f"Integral token refresh failed ({resp.status_code}): {resp.text}" + ) + tokens = resp.json() + if not isinstance(tokens, dict) or not tokens.get("access_token"): + raise IntegralOAuthServiceError( + "Integral token refresh returned no access_token." + ) + return tokens + + +# --------------------------------------------------------------------------- +# Stored token payload helpers +# --------------------------------------------------------------------------- + + +def normalize_token_payload( + tokens: Dict[str, Any], + *, + client_id: str, + token_uri: str, + account_name: str, + scope: str = "", + previous: Optional[Dict[str, Any]] = None, +) -> Dict[str, Any]: + """Build the JSON payload persisted on :class:`MCPOAuthToken`. + + ``refresh`` tokens are rotated by some servers; keep the previous value when + the response omits a new one. + """ + expires_in = int(tokens.get("expires_in") or 3600) + expiry = datetime.now(timezone.utc) + timedelta(seconds=max(0, expires_in)) + refresh = tokens.get("refresh_token") or ( + (previous or {}).get("refresh_token") if previous else "" + ) + scopes = tokens.get("scope") + if isinstance(scopes, str): + scope_list = scopes.split() + else: + scope_list = list(scope.split()) if scope else [] + return { + "type": "oauth2", + "client_id": client_id, + "token": tokens.get("access_token") or "", + "access_token": tokens.get("access_token") or "", + "refresh_token": refresh or "", + "token_uri": token_uri, + "scopes": scope_list, + "account_alias": account_name, + "expiry": expiry.isoformat(), + } + + +_IDENTITY_TIMEOUT = 8.0 + + +async def resolve_token_identity( + mcp_url: str, + access_token: str, + meta: Optional[Dict[str, Any]] = None, +) -> Dict[str, str]: + """Resolve the Core account email behind an Integral MCP access token. + + The MCPs panel labels a connection with the token's ``email``; without one + it falls back to the storage key (``integral``). Core accepts the MCP + access token on its own API, so read the identity back after the exchange. + Best-effort: a failure returns ``{}`` and never fails the connect. + """ + token = (access_token or "").strip() + if not token: + return {} + base = "" + for candidate in ( + (meta or {}).get("issuer"), + (meta or {}).get("token_endpoint"), + mcp_url, + ): + base = _origin(str(candidate or "")) + if base: + break + if not base: + return {} + + try: + async with httpx.AsyncClient( + timeout=_IDENTITY_TIMEOUT, follow_redirects=True + ) as client: + resp = await client.get( + f"{base}/api/auth/me", + headers={"Authorization": f"Bearer {token}"}, + ) + if resp.status_code != 200: + return {} + body = resp.json() + except Exception as exc: + logger.debug("Integral identity lookup failed: %s", exc) + return {} + user = body.get("user") if isinstance(body, dict) else None + user = user if isinstance(user, dict) else {} + email = str(user.get("email") or "").strip() + return {"email": email} if email else {} + + +def payload_is_expired(payload: Optional[Dict[str, Any]]) -> bool: + """Return True when the stored access token is missing or (near) expired.""" + if not payload: + return True + if not payload.get("access_token") and not payload.get("token"): + return True + raw = payload.get("expiry") or "" + if not raw: + return False + try: + expiry = datetime.fromisoformat(str(raw).replace("Z", "+00:00")) + except ValueError: + return True + if expiry.tzinfo is None: + expiry = expiry.replace(tzinfo=timezone.utc) + return expiry <= datetime.now(timezone.utc) + timedelta( + seconds=_EXPIRY_SKEW_SECONDS + ) diff --git a/jvagent/action/mcp_oauth/mcp_oauth_action.py b/jvagent/action/mcp_oauth/mcp_oauth_action.py index 1a1b61bad..5cdbce865 100644 --- a/jvagent/action/mcp_oauth/mcp_oauth_action.py +++ b/jvagent/action/mcp_oauth/mcp_oauth_action.py @@ -49,10 +49,16 @@ def build_oauth_setup( *, google_enabled_services: Optional[Iterable[str]] = None, microsoft_enabled_services: Optional[Iterable[str]] = None, - account: str = "default", + account: str = "integral", ) -> List[Dict[str, Any]]: - """Per-service OAuth endpoints for configured Google/Microsoft MCP servers.""" + """Per-service OAuth endpoints for configured Google/Microsoft/Integral MCP servers.""" from .hydrate import mcp_google_workspace_auth_url + from .integral_provider import ( + INTEGRAL_LABEL, + INTEGRAL_SERVER, + INTEGRAL_SERVICE, + mcp_integral_core_auth_url, + ) from .microsoft_hydrate import mcp_microsoft_365_auth_url from .microsoft_scopes import ( MICROSOFT_365_SERVER, @@ -135,12 +141,20 @@ def _append( mcp_microsoft_365_auth_url, ) + if INTEGRAL_SERVER in names: + _append( + INTEGRAL_SERVER, + [INTEGRAL_SERVICE], + {INTEGRAL_SERVICE: INTEGRAL_LABEL}, + mcp_integral_core_auth_url, + ) + return setup def mcp_oauth_state_action_id(account: str, service: str = "") -> str: """``mcp_oauth:{account}`` or ``mcp_oauth:{account}:{service}`` for OAuth state.""" - name = (account or "default").strip() or "default" + name = (account or "integral").strip() or "integral" svc = (service or "").strip() if svc: return f"mcp_oauth:{name}:{svc}" @@ -150,7 +164,7 @@ def mcp_oauth_state_action_id(account: str, service: str = "") -> str: def parse_mcp_oauth_state_action_id(action_id: str) -> tuple[str, str]: """Return ``(account, service)`` from an MCP OAuth state action_id.""" parts = (action_id or "").split(":") - account = parts[1] if len(parts) > 1 and parts[1] else "default" + account = parts[1] if len(parts) > 1 and parts[1] else "integral" service = parts[2] if len(parts) > 2 else "" return account, service @@ -497,7 +511,7 @@ def token_row_for_service( rows: Sequence[Any], server_name: str, service: str, - fallback_account: str = "default", + fallback_account: str = "integral", ) -> tuple[Optional[str], Optional[Dict[str, Any]], Any]: """Pick the token that owns ``service``. Never steal another service's row. diff --git a/jvagent/action/orchestrator/loop.py b/jvagent/action/orchestrator/loop.py index 0b383cef6..af43783a7 100644 --- a/jvagent/action/orchestrator/loop.py +++ b/jvagent/action/orchestrator/loop.py @@ -151,8 +151,34 @@ def _grounding_corpus( parts.append(str(obs.get("args", ""))) return "\n".join(parts) + @staticmethod + def _handoff_in_observations(observations) -> bool: + """True only on the first hand-off statement this turn. + + ``Hand-off already stated`` must not arm the sales-sentence guard — + follow-up optional captures acknowledge the new detail without + restating that the request is with the team. The engine now marks those + directives explicitly, so a sync observation earlier in the same turn + cannot re-arm the guard against the capture that just ran. + """ + from jvagent.action.leadgen.engine import HANDOFF_ALREADY_STATED_MARKER + + texts = [] + for obs in observations or (): + text = str(obs.get("observation", "") if isinstance(obs, dict) else obs) + texts.append(text) + # Marker may appear alone on observation ``directive`` (no trailing space). + if any(HANDOFF_ALREADY_STATED_MARKER in text for text in texts): + return False + return any("Hand-off is complete" in text for text in texts) + def _grounding_deflection( - self, text: str, substantive_tool_calls: int, corpus: str = "", visitor=None + self, + text: str, + substantive_tool_calls: int, + corpus: str = "", + visitor=None, + handoff_required: bool = False, ): """Guard observation from any ``enforcement: guard`` parameter in force. @@ -172,6 +198,7 @@ def _grounding_deflection( context = { "substantive_tool_calls": substantive_tool_calls, "corpus": corpus, + "handoff_required": bool(handoff_required), } for param in parameters_with_enforcement(pool, ENFORCEMENT_GUARD): for detector in detectors_for(param, ENFORCEMENT_GUARD): @@ -1050,6 +1077,7 @@ async def _tick_final( str(get_prompt_cache().get("identity") or ""), ), visitor, + handoff_required=self._handoff_in_observations(state.observations), ) if nudge is not None: state.grounding_deflections += 1 @@ -1057,8 +1085,41 @@ async def _tick_final( return TickOutcome.CONTINUE_ if answer: await self._maybe_emit_final(visitor, answer) + return TickOutcome.done("final") + return await self._finish_empty_final(visitor, state) + + async def _finish_empty_final( + self, visitor: "InteractWalker", state: TurnState + ) -> TickOutcome: + """An empty final is never delivered: nudge once, then clarify. + + The model can stall on contradicting instructions (a directive that + forbids the sales sentence while turn context requires it). Deflect once + so it composes from the tools' directives; if it stalls again, send the + clarify line rather than ending the customer's turn with nothing. + """ + if state.empty_final_deflections < 1: + state.empty_final_deflections += 1 + state.observations.append(self._empty_final_nudge()) + return TickOutcome.CONTINUE_ + await self._maybe_emit_final(visitor, self.clarify_text) return TickOutcome.done("final") + @staticmethod + def _empty_final_nudge() -> Dict[str, Any]: + """Observation telling the model its empty final is not deliverable.""" + return { + "tool": "(guard)", + "guard": "empty_final", + "args": {}, + "observation": ( + "(Your last message was empty and nothing was sent to the " + "customer. Compose the reply now from the directive still in " + "context: one sentence carrying substance, never an empty " + "message.)" + ), + } + async def _tick_tool( self, visitor: "InteractWalker", @@ -1299,6 +1360,7 @@ async def _guard_tool_call( str(get_prompt_cache().get("identity") or ""), ), visitor, + handoff_required=self._handoff_in_observations(state.observations), ) if nudge is not None: state.grounding_deflections += 1 diff --git a/jvagent/action/orchestrator/loop_helpers.py b/jvagent/action/orchestrator/loop_helpers.py index b62c58578..7f8d35db1 100644 --- a/jvagent/action/orchestrator/loop_helpers.py +++ b/jvagent/action/orchestrator/loop_helpers.py @@ -226,12 +226,25 @@ def salvage_partial_answer(observations: Any) -> str: return "" +def _guard_missing_handoff_sentence(text: str, context: dict) -> str: + """A hand-off turn must say the request is with sales.""" + if not context.get("handoff_required"): + return "" + if "sales team" in (text or "").casefold(): + return "" + return ( + "This turn completes a hand-off: state in one sentence that the request " + "is with the sales team, then the rest of the reply." + ) + + def register_orchestrator_guard_detectors() -> None: """Register the loop's guard detectors with the parameter subsystem.""" from jvagent.action.parameters import register_guard_detector register_guard_detector("unsupported_source_claim", _guard_unsupported_source_claim) register_guard_detector("unsupported_specifics", _guard_unsupported_specifics) + register_guard_detector("missing_handoff_sentence", _guard_missing_handoff_sentence) register_orchestrator_guard_detectors() diff --git a/jvagent/action/orchestrator/orchestrator_interact_action.py b/jvagent/action/orchestrator/orchestrator_interact_action.py index b02dfcac3..b2e0be77f 100644 --- a/jvagent/action/orchestrator/orchestrator_interact_action.py +++ b/jvagent/action/orchestrator/orchestrator_interact_action.py @@ -744,7 +744,18 @@ class OrchestratorInteractAction( "agent did in earlier turns at the cost of resending those lines " "on every tick; history_statement_max_chars caps each line. The " "current interaction's events are never included — it is excluded " - "from its own history." + "from its own history. When with_event is true, hide_correlation " + "(default true) omits harness correlation [EVENT] lines." + ), + ) + hide_correlation: bool = attribute( + default=True, + description=( + "When with_event is true, omit harness correlation [EVENT] lines " + "(action_name=harness / corr-*). Default true keeps product " + "side-effect events without turn-correlation noise. Set false to " + "include correlation events. Ignored when with_event is false. " + "Channel-overridable." ), ) @@ -5845,6 +5856,11 @@ async def _history(self, visitor: "InteractWalker") -> List[Dict[str, str]]: with_event=bool( self._channel_cfg(visitor, "with_event", self.with_event) ), + hide_correlation=bool( + self._channel_cfg( + visitor, "hide_correlation", self.hide_correlation + ) + ), max_statement_length=( int(self.history_statement_max_chars) if int(self.history_statement_max_chars or 0) > 0 diff --git a/jvagent/action/orchestrator/turn_state.py b/jvagent/action/orchestrator/turn_state.py index c4853e721..9eec554dd 100644 --- a/jvagent/action/orchestrator/turn_state.py +++ b/jvagent/action/orchestrator/turn_state.py @@ -143,3 +143,6 @@ class TurnState: model_failures: int = 0 # Ticks that dispatched more than one tool call (max_concurrent_tools > 1). parallel_batches: int = 0 + # Empty-final deflections this turn: an empty final answer is never + # delivered, so it is nudged once before a lawful fallback is sent. + empty_final_deflections: int = 0 diff --git a/jvagent/action/pageindex/lexical_index.py b/jvagent/action/pageindex/lexical_index.py index 60e9dbc59..59cb0c3d2 100644 --- a/jvagent/action/pageindex/lexical_index.py +++ b/jvagent/action/pageindex/lexical_index.py @@ -31,6 +31,13 @@ _STATS_COLLECTION = "lexical_stats" _MAX_POSTINGS_PER_TERM = 2000 +#: A term is distinctive when the corpus uses it in at most this many nodes. +_RARE_DF = 2 +#: When unknown terms reach this share of the distinctive terms, the query is +#: about a concept the corpus does not cover: callers should use their +#: not-found path instead of receiving a match to a neighbouring question. +_UNKNOWN_TERM_RATIO = 0.5 + def _posting_id(collection_name: str, term: str) -> str: return f"lp.{collection_name}.{term}" @@ -315,6 +322,22 @@ async def search( if not postings_map: return [] + # Coverage floor: when unknown terms are at least half of the query's + # distinctive terms, every remaining match answers a neighbouring + # question. Return no candidates so callers use their not-found path. + rare_terms = [term for term in unique_terms if term_df_map.get(term, 0) <= _RARE_DF] + unknown_terms = [term for term in rare_terms if term_df_map.get(term, 0) == 0] + if rare_terms and len(unknown_terms) / len(rare_terms) >= _UNKNOWN_TERM_RATIO: + logger.debug( + "Lexical index: %d of %d distinctive terms unknown in collection %s " + "(%s); returning no candidates", + len(unknown_terms), + len(rare_terms), + collection_name, + unknown_terms, + ) + return [] + ranked = bm25_score( query_terms=unique_terms, postings_map=postings_map, diff --git a/jvagent/action/pageindex/pageindex_google_drive_sync_action/endpoints.py b/jvagent/action/pageindex/pageindex_google_drive_sync_action/endpoints.py index c15f1ff21..4116345e2 100644 --- a/jvagent/action/pageindex/pageindex_google_drive_sync_action/endpoints.py +++ b/jvagent/action/pageindex/pageindex_google_drive_sync_action/endpoints.py @@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional from fastapi import HTTPException, Request +from fastapi.responses import JSONResponse from jvspatial import create_task, is_serverless_mode from jvspatial.api import endpoint from jvspatial.api.endpoints.response import ResponseField, success_response @@ -13,6 +14,7 @@ from jvspatial.exceptions import ValidationError as SpatialValidationError from pydantic import Field +from jvagent.action.google.google_action import GoogleAuthRequiredError from jvagent.action.pageindex.endpoints import _resolve_docling_ocr_for_ingest from jvagent.action.utils.endpoint_helpers import require_typed_action from jvagent.core.agent import Agent @@ -726,6 +728,23 @@ async def pageindex_google_drive_sync_action_interact( "response": "Ingestion started in background", "result": {}, } + except GoogleAuthRequiredError as e: + logger.warning( + "Google Drive authorization required for PageIndex sync (agent %s): %s", + agent_id, + e, + ) + return JSONResponse( + status_code=401, + content={ + "error_code": "google_auth_required", + "message": str(e), + "service": e.service, + "reason": e.reason, + "missing_scopes": e.missing_scopes, + "auth_url": e.auth_url, + }, + ) except (ResourceNotFoundError, HTTPException): raise except DatabaseError as e: diff --git a/jvagent/action/pageindex/pageindex_google_drive_sync_action/pageindex_google_drive_sync_action.py b/jvagent/action/pageindex/pageindex_google_drive_sync_action/pageindex_google_drive_sync_action.py index 5a76bb9da..a4c96918d 100644 --- a/jvagent/action/pageindex/pageindex_google_drive_sync_action/pageindex_google_drive_sync_action.py +++ b/jvagent/action/pageindex/pageindex_google_drive_sync_action/pageindex_google_drive_sync_action.py @@ -1,6 +1,7 @@ import asyncio import copy import hashlib +import inspect import json import logging import os @@ -16,7 +17,7 @@ from jvspatial.db import get_prime_database from jvspatial.exceptions import DatabaseError, ValidationError -from jvagent.action.google.google_action import GoogleAction +from jvagent.action.google.google_action import GoogleAction, GoogleAuthRequiredError from jvagent.action.pageindex.adapter import strip_redundant_md_suffix from jvagent.action.pageindex.config import ( get_pageindex_node_summary, @@ -1234,6 +1235,13 @@ async def ingest_documents_from_google_drive( empty_result["message"] = f"No {self.page_index_action} found" return empty_result + # Fail here, before any folder listing or queue work, when the Drive + # credential cannot be used. ``inspect`` guards test doubles that are + # not real Actions and therefore have no coroutine preflight. + preflight = getattr(google_drive_action, "assert_authorized", None) + if inspect.iscoroutinefunction(preflight): + await preflight() + if not google_drive_folders: google_drive_folders = self.google_drive_folders if not google_drive_folders: @@ -1320,6 +1328,8 @@ def _invalidate_drive_service() -> None: ) folder_name = str(drive_meta.get("name") or "") drive_id = google_drive_folder_id + except GoogleAuthRequiredError: + raise except Exception: logger.warning( "Could not fetch Drive folder/drive name for " @@ -1336,6 +1346,10 @@ def _invalidate_drive_service() -> None: exc_info=True, ) _invalidate_drive_service() + except GoogleAuthRequiredError: + # A credential problem ends the run; continuing would only + # re-raise on the listing below with a less useful stack. + raise except Exception: logger.warning( "Could not fetch Drive folder/drive name for folder_id=%s", diff --git a/jvagent/action/parameters.py b/jvagent/action/parameters.py index cbe5c3e75..aa38a5fa7 100644 --- a/jvagent/action/parameters.py +++ b/jvagent/action/parameters.py @@ -202,6 +202,19 @@ def parameters_with_enforcement( CORE_PARAMETERS: List[Dict[str, Any]] = [ + { + "key": "reply.handoff_sentence", + "inviolable": True, + "enforcement": ENFORCEMENT_GUARD, + "detector": "missing_handoff_sentence", + "scope": SCOPE_RESPONSE, + "response": ( + "When this turn's directive says hand-off is complete (first " + "statement), say in one sentence that the request is with the " + "sales team before anything else. Do not require that sentence on " + "already-stated or follow-up update turns." + ), + }, { "key": "identity.self_disclosure", "inviolable": True, diff --git a/jvagent/action/reply/reply_action.py b/jvagent/action/reply/reply_action.py index 184bc6165..965b1ce35 100644 --- a/jvagent/action/reply/reply_action.py +++ b/jvagent/action/reply/reply_action.py @@ -822,18 +822,24 @@ def _collect_parameters(parameters: Optional[List[Any]], interaction: Any) -> st def _compose_parameters_text( self, parameters: Optional[List[Any]], interaction: Any ) -> str: - """The response-parameter set rendered for a compose: this action's native - response core (the baseline) merged with explicit + interaction-pooled - params, filtered to response scope and de-duplicated. - - The Orchestrator pools every action's response params onto the - interaction; this action's own native core is added too (so a standalone - reply, with no orchestrator accumulation, is still hardened). Only - ``response``-scoped rules render here — orchestration params stay in the - loop prompt. + """The response-parameter set rendered for a compose: the framework + response core (always, when ``apply_reply_rules``) merged with this + action's ``parameters``, explicit + interaction-pooled params, filtered + to response scope and de-duplicated. + + Always unioning ``reply_core_parameters()`` mirrors ``_reply_pool`` / + the orchestrator ``_parameter_pool``: an agent.yaml that replaces + ``ReplyAction.parameters`` with a custom list must not drop identity, + hand-off, closers, or grounding from the compose prompt. Keyed + operator rules still win via ``resolve_parameters``; inviolable core + cannot be weakened. Only ``response``-scoped rules render here — + orchestration params stay in the loop prompt. """ merged: List[Any] = [] if self.apply_reply_rules: + # Framework baseline first — not ``self.parameters`` alone — so a + # YAML replacement of the attribute cannot wipe core RESPONSE RULES. + merged.extend(reply_core_parameters()) merged.extend(self.parameters or []) if parameters: merged.extend(parameters) diff --git a/jvagent/action/tts_action/README.md b/jvagent/action/tts_action/README.md index 1921237aa..428cb7f9c 100644 --- a/jvagent/action/tts_action/README.md +++ b/jvagent/action/tts_action/README.md @@ -43,10 +43,12 @@ audio_bytes = await tts_action.invoke("Hello, world!") # Generate speech as base64 (for inline use, e.g. web players) audio_base64 = await tts_action.invoke("Hello, world!", as_base64=True) -# Generate speech as file URL (for adapters that fetch and send the file) +# Generate speech as file URL (signed proxy URL for adapters that fetch and send the file) audio_url = await tts_action.invoke("Hello, world!", as_url=True) ``` +`as_url=True` stores the audio and returns a signed proxy URL (`{JVSPATIAL_PROXY_PREFIX}/{code}`, default `/p/{code}`). The proxy route is anonymously readable and expires after one hour, so adapters such as WhatsApp and Messenger can fetch the media even when authentication is enabled. Set `JVSPATIAL_PROXY_ENABLED=true`; without it the action falls back to the auth-protected `/api/files/...` route and logs a warning. + ### Voice and Model Management ```python @@ -87,7 +89,7 @@ Synthesize speech from text. ```json { "success": true, - "audio": "https://example.com/audio.mp3", + "audio": "https://example.com/p/abc123", "format": "url", "provider": "ElevenLabsTTSAction", "model": "eleven_turbo_v2", @@ -107,7 +109,7 @@ Check TTS service health. ## API Methods ### `invoke(text: str, as_base64: bool = False, as_url: bool = False) -> Optional[Union[str, bytes]]` -Convert text to speech. Use `as_url=True` when output will be sent to adapters (e.g. WhatsApp). Use `as_base64=True` for inline audio (e.g. web players). +Convert text to speech. Use `as_url=True` when output will be sent to adapters (e.g. WhatsApp); it returns a signed proxy URL that expires after one hour. Use `as_base64=True` for inline audio (e.g. web players). ### `get_audio_as(audio: bytes, as_base64: bool = False, as_url: bool = False) -> Optional[Union[str, bytes]]` Convert audio bytes to different formats. @@ -128,3 +130,4 @@ Perform health check for the TTS service. ## Environment Variables - `ELEVENLABS_API_KEY`: Your ElevenLabs API key +- `JVSPATIAL_PROXY_ENABLED`: Set to `true` so `as_url=True` returns an anonymously fetchable proxy URL when authentication is enabled diff --git a/jvagent/action/tts_action/elevenlabs/elevenlabs.py b/jvagent/action/tts_action/elevenlabs/elevenlabs.py index fe1fefb14..4473041e8 100644 --- a/jvagent/action/tts_action/elevenlabs/elevenlabs.py +++ b/jvagent/action/tts_action/elevenlabs/elevenlabs.py @@ -7,6 +7,7 @@ import uuid from typing import Dict, List, Optional, Tuple, Union +from jvspatial.api.constants import APIRoutes from jvspatial.core.annotations import attribute from jvspatial.env import env @@ -97,7 +98,16 @@ async def get_audio_as( storage_path, audio, metadata={"type": "tts_audio"} ) if success: - url = await self.get_file_url(storage_path) + # Signed proxy URL: adapters and LLM providers fetch this + # anonymously, unlike the auth-protected /api/files route. + url = await self.get_short_file_url(storage_path, expires_in=3600) + if url and url.startswith(f"{APIRoutes.FILES_ROOT}/"): + logger.warning( + "TTS audio URL is the auth-protected file route (%s); " + "set JVSPATIAL_PROXY_ENABLED=true so media adapters can " + "fetch it without authentication.", + url, + ) return url except Exception as e: logger.error("Error saving audio file: %s", e, exc_info=True) diff --git a/jvagent/action/whatsapp/README.md b/jvagent/action/whatsapp/README.md index f3c8d10c9..2fdb1f0b9 100644 --- a/jvagent/action/whatsapp/README.md +++ b/jvagent/action/whatsapp/README.md @@ -227,7 +227,7 @@ Admin helpers: **Media and voice (meta provider):** - Inbound media: Meta sends a media id in the webhook; jvagent downloads via Graph and feeds the same pipeline as bridge providers (vision, STT, etc.). -- Outbound media: agent replies upload files from jvagent public URLs (`JVAGENT_PUBLIC_BASE_URL` + `/api/files/...`) to Meta before send. +- Outbound media: agent replies upload files from jvagent signed proxy URLs (`JVAGENT_PUBLIC_BASE_URL` + `/p/{code}`, or `/api/files/...` when public reads are enabled) to Meta before send. - Typing: uses inbound `wamid` (`message_id`) with Meta’s read + typing_indicator API. - Outbound voice notes (native PTT bubble): requires OGG/OPUS; when TTS returns MP3, jvagent transcodes via **ffmpeg** on PATH (`libopus` → OGG) before upload when available; otherwise sends as a basic audio file. @@ -249,6 +249,9 @@ Bridge-only variables (`WHATSAPP_API_URL`, `WHATSAPP_API_KEY`, `WHATSAPP_SESSION # to absolute URLs when the adapter fetches files for sending JVAGENT_PUBLIC_BASE_URL=https://your-app.com +# Signed proxy URLs for outbound media (TTS voice notes). Required when auth is enabled. +JVSPATIAL_PROXY_ENABLED=true + # Session Registration Timeout (optional, default: 120 seconds) # HTTP client timeout for session registration during startup # Allows time for slow WhatsApp API responses (registration can take 30-60+ seconds) @@ -293,7 +296,7 @@ When `stt_action` and `tts_action` are configured, the action supports voice mes - **Inbound PTT**: Voice messages are transcribed via the STT action. The adapter passes the correct audio format (WhatsApp voice uses OGG-Opus) to the generic STT layer. - **Outbound voice reply**: When the user sends a PTT, the agent can respond with a synthesized voice message. ReplyAction applies voice-optimized formatting (short replies, no markdown), and the TTS action generates audio. The adapter sends the result as a voice message. -- **Media URLs**: TTS and other media may return relative URLs (e.g. `/api/files/...` under the default `JVSPATIAL_API_PREFIX`). The adapter prepends `base_url` (from `JVAGENT_PUBLIC_BASE_URL`) to produce absolute URLs before fetching for delivery. Ensure `JVAGENT_PUBLIC_BASE_URL` is set and publicly reachable. +- **Media URLs**: TTS and other media return relative URLs. With `JVSPATIAL_PROXY_ENABLED=true`, TTS returns a signed proxy URL (e.g. `/p/{code}`) that adapters and LLM providers can fetch anonymously. The adapter prepends `base_url` (from `JVAGENT_PUBLIC_BASE_URL`) to produce absolute URLs before fetching for delivery. Ensure `JVAGENT_PUBLIC_BASE_URL` is set and publicly reachable. Direct `/api/files/...` URLs require authentication when auth is enabled unless `JVSPATIAL_FILES_PUBLIC_READ=true`. ## Images and Vision @@ -447,11 +450,13 @@ After routing works, deferred logs should include **`Deferred whatsapp media bat **Symptoms**: - TTS voice replies or other media fail with fetch errors -- Log shows relative URL path (e.g. `/api/files/...`) +- Log shows relative URL path (e.g. `/api/files/...`) and a `401` for the media request **Solutions**: -1. **Set JVAGENT_PUBLIC_BASE_URL**: The adapter needs an absolute URL to fetch media. Ensure `JVAGENT_PUBLIC_BASE_URL` is set (e.g. `https://your-app.com`) and is publicly reachable. -2. **Configure base_url on action**: In agent.yaml, set `base_url: "${JVAGENT_PUBLIC_BASE_URL}"` for the WhatsApp action. +1. **Enable signed proxy URLs**: Set `JVSPATIAL_PROXY_ENABLED=true`. TTS `as_url=True` then returns `/p/{code}`, which the adapter can fetch anonymously. +2. **Set JVAGENT_PUBLIC_BASE_URL**: The adapter needs an absolute URL to fetch media. Ensure `JVAGENT_PUBLIC_BASE_URL` is set (e.g. `https://your-app.com`) and is publicly reachable. +3. **Configure base_url on action**: In agent.yaml, set `base_url: "${JVAGENT_PUBLIC_BASE_URL}"` for the WhatsApp action. +4. **Fallback only**: `JVSPATIAL_FILES_PUBLIC_READ=true` makes direct `/api/files/...` reads anonymous, but exposes every stored file by path. Prefer proxy URLs. #### Problem: Lambda batch mode - media not processed until follow-up message diff --git a/jvagent/action/whatsapp/whatsapp_action.py b/jvagent/action/whatsapp/whatsapp_action.py index 87adf1c38..fab618190 100644 --- a/jvagent/action/whatsapp/whatsapp_action.py +++ b/jvagent/action/whatsapp/whatsapp_action.py @@ -686,9 +686,20 @@ async def on_reload(self) -> None: ) async def _warn_lambda_local_storage(self) -> None: - """Log warning when on Lambda with local file storage and non-/tmp path.""" + """Log warning when on Lambda with local file storage and non-/tmp path. + + Skips when ``JVSPATIAL_FILE_STORAGE_SERVERLESS_SHARED`` is set (operator + asserts durable shared storage such as EFS), matching LocalFileInterface. + """ if not os.environ.get("AWS_LAMBDA_FUNCTION_NAME"): return + shared = ( + os.environ.get("JVSPATIAL_FILE_STORAGE_SERVERLESS_SHARED", "") + .strip() + .lower() + ) + if shared in ("1", "true", "yes", "on"): + return try: from jvagent.core.app import App @@ -700,9 +711,11 @@ async def _warn_lambda_local_storage(self) -> None: if provider == "local" and root and not root.startswith("/tmp"): logger.warning( "WhatsApp media on Lambda: file_storage is local with " - "root_dir=%r. Lambda /var/task is read-only. Configure " - "file_storage.provider: s3 (or JVSPATIAL_FILE_INTERFACE=s3) " - "or set JVSPATIAL_FILES_ROOT_PATH=/tmp for ephemeral storage.", + "root_dir=%r. Lambda /var/task is read-only. Use EFS under " + "/mnt and set JVSPATIAL_FILE_STORAGE_SERVERLESS_SHARED=1, " + "configure file_storage.provider: s3 " + "(or JVSPATIAL_FILE_INTERFACE=s3), or set " + "JVSPATIAL_FILES_ROOT_PATH=/tmp for ephemeral storage.", root, ) except Exception: diff --git a/jvagent/cli/skill_commands.py b/jvagent/cli/skill_commands.py index dd66a5b9d..0a5f85d89 100644 --- a/jvagent/cli/skill_commands.py +++ b/jvagent/cli/skill_commands.py @@ -18,12 +18,28 @@ def _skill_dir_for_agent(agent_dir: Path, skill_name: str) -> Path: def _build_skill_stub(skill_name: str, description: str) -> str: + # Description is the pre-activation selection cue (≤60 words): scope + + # when to use + Not for exclusions (siblings, greetings/acks for catch-alls). + desc = (description or "").strip() or ( + f"Handle {skill_name.replace('-', ' ')} requests for this agent. " + "Not for greetings, small talk, or work owned by sibling skills." + ) return f"""--- name: {skill_name} -description: {description} +description: >- + {desc} allowed-tools: [] --- +## When to use + +- Trigger categories that should select this skill (category rules, not example lists). + +## Do not use + +- Greetings, small talk, or bare thanks/ok with no task for this skill. +- Work owned by a sibling skill (name the sibling). + ## Workflow 1. Clarify the objective and constraints. diff --git a/jvagent/memory/conversation.py b/jvagent/memory/conversation.py index 8ca86a407..79b72e42d 100644 --- a/jvagent/memory/conversation.py +++ b/jvagent/memory/conversation.py @@ -43,6 +43,22 @@ def _cap_event_entries(events: Any, max_event_length: Optional[int]) -> Any: return capped +def _events_for_history(events: Any, *, hide_correlation: bool = True) -> Any: + """Return events for LLM/history replay, optionally dropping harness lines. + + Harness correlation (``action_name == \"harness\"``) is persisted for debug + but is not needed in model context. Default ``hide_correlation=True`` omits + those entries; set ``hide_correlation=False`` to keep them. + """ + if not hide_correlation or not isinstance(events, list): + return events + return [ + event + for event in events + if not (isinstance(event, dict) and event.get("action_name") == "harness") + ] + + # Compound field names are model fields (``session_id``); jvspatial maps them to # ``context.`` in MongoDB. A ``context.`` prefix on the model field becomes # ``context.context.*``. @@ -809,6 +825,7 @@ async def _format_interactions( with_response: bool = True, with_interpretation: bool = False, with_event: bool = False, + hide_correlation: bool = True, with_posture: bool = False, max_statement_length: Optional[int] = None, max_event_length: Optional[int] = None, @@ -824,6 +841,9 @@ async def _format_interactions( with_response: If True, include AI responses as assistant messages with_interpretation: If True, include interpretations as system messages with_event: If True, include events as system messages + hide_correlation: When ``with_event`` is true, omit harness + correlation events (``action_name == \"harness\"`` / ``corr-*``). + Default True; set False to include them with other events. with_posture: If True, prepend SUPPRESS/DEFER system messages when response_posture is set max_statement_length: Optional maximum length for utterance and response strings. If provided and content exceeds this length, it will be truncated with "..." appended. @@ -924,7 +944,9 @@ async def _format_interactions( # Events ignore ``max_statement_length`` by contract; they honour the # explicit ``max_event_length`` cap when the caller sets one. if with_event and interaction.events: - for event in interaction.events: + for event in _events_for_history( + interaction.events, hide_correlation=hide_correlation + ): # Extract content from event dict structure if isinstance(event, dict): event_str = event.get("content", str(event)) @@ -950,6 +972,7 @@ async def get_interaction_history( with_response: bool = True, with_interpretation: bool = False, with_event: bool = False, + hide_correlation: bool = True, with_posture: bool = False, formatted: bool = True, max_statement_length: Optional[int] = None, @@ -970,6 +993,8 @@ async def get_interaction_history( with_response: If True, include AI responses (default: True) with_interpretation: If True, include interpretations (default: False) with_event: If True, include events (default: False) + hide_correlation: When ``with_event`` is true, omit harness correlation + events (``action_name == \"harness\"`` / ``corr-*``). Default True. with_posture: If True, include response_posture (SUPPRESS/DEFER) as system messages formatted: If True, format as role/content pairs for language models. If False, return raw format with metadata. Default: True. @@ -1026,6 +1051,7 @@ async def get_interaction_history( with_response=with_response, with_interpretation=with_interpretation, with_event=with_event, + hide_correlation=hide_correlation, with_posture=with_posture, max_statement_length=max_statement_length, max_event_length=max_event_length, @@ -1067,7 +1093,11 @@ async def get_interaction_history( # Events ignore ``max_statement_length`` by contract; they # honour ``max_event_length`` when the caller sets one. entry["events"] = _cap_event_entries( - interaction.events, max_event_length + _events_for_history( + interaction.events, + hide_correlation=hide_correlation, + ), + max_event_length, ) if with_posture and getattr(interaction, "response_posture", None): diff --git a/jvagent/scaffold/static/env.example.txt b/jvagent/scaffold/static/env.example.txt index 9aa818a7f..a65eee0f5 100644 --- a/jvagent/scaffold/static/env.example.txt +++ b/jvagent/scaffold/static/env.example.txt @@ -109,6 +109,9 @@ JVSPATIAL_CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000,http://localh JVSPATIAL_FILE_STORAGE_ENABLED=true # JVSPATIAL_FILES_PUBLIC_READ=true JVSPATIAL_FILE_STORAGE_PROVIDER=local +# Signed proxy URLs for anonymous media delivery (TTS/WhatsApp). Required when auth is enabled. +JVSPATIAL_PROXY_ENABLED=true +# JVSPATIAL_PROXY_PREFIX=/p # JVSPATIAL_FILES_ROOT_PATH=./.files # JVSPATIAL_FILE_STORAGE_BASE_URL=http://localhost:8000 # JVSPATIAL_FILE_STORAGE_MAX_SIZE=104857600 diff --git a/jvagent/skills/README.md b/jvagent/skills/README.md index 92783cf4f..215af8c59 100644 --- a/jvagent/skills/README.md +++ b/jvagent/skills/README.md @@ -76,8 +76,9 @@ Two parts: YAML frontmatter (between `---`) and a Markdown SOP body. --- name: research # lowercase, numbers, hyphens (Claude rule) description: >- - Investigate a topic with evidence-first synthesis and citations. Include - what it does AND when to use it (third person — it's injected into the prompt). + Investigate a topic with evidence-first synthesis and citations. Use when + the visitor asks for researched answers with sources. Not for greetings, + small talk, or live catalogue facts owned by a sibling skill. spec: jv # jv (default) | claude allowed-tools: - web_search__search @@ -87,18 +88,35 @@ metadata: tags: [research] --- +## When to use + +- Research questions that need evidence and citations. + +## Do not use + +- Greetings or small talk with no research ask. +- Work owned by a sibling skill (name it). + ## Workflow 1. Clarify the question and success criteria. 2. Search, then read top sources in full with web_fetch__fetch. 3. Reconcile conflicts and synthesize a cited answer. ``` +**Selection contract (description):** Before activation the model sees only +`name: description`. Keep the description ≤ ~60 words, third person, derived from +`## When to use` / `## Do not use` — trigger categories plus named exclusions +(sibling skills). Catch-all / faq / fallback skills must exclude greetings, small +talk, and bare acks in the description itself; do not rely on body text or +`system_prompt_extra` alone. House Coder authors: follow +`~/.config/kilo/skills/coder-prompt/references/writing-descriptions.md`. + ## Frontmatter keys | Key | Specs | Notes | |-----|-------|-------| | `name` | both | Lowercase letters, numbers, hyphens (Claude rule); defaults to folder name. | -| `description` | both | Drives discovery; third person; what it does + when to use it. | +| `description` | both | Selection cue before activation; third person; what it does + when to use + Not for exclusions (≤ ~60 words). | | `spec` | both | `jv` (default) or `claude`. Unknown values fall back to `jv`. | | `allowed-tools` | mostly JV | Runtime tool names the SOP uses (e.g. `gmail__send_email`, `web_fetch__fetch`, `code_execution__bash`). Surfaced into the visible set on activation. | | `requires-actions` | JV | Action class names that must resolve (enabled) on the agent, each with an **optional inline version constraint** (PEP 508-style — the comparison operator is the delimiter): `CodeExecutionAction`, `PageIndexAction>=2.0`, `WebFetchAction==1.4.0`, `GmailAction>=1.0,<2.0`. **Hard gate, enforced:** if any declared type is absent — or its `get_version()` doesn't satisfy the constraint — the orchestrator hides the skill entirely for that turn (not listed, found, activated, or always-active-pinned). Replaces the old `requires-action-versions` map. **Not lifecycle binding:** listing multiple actions (e.g. `InterviewAction` + `ZoonAPIAction`) gates on all of them; which Action runs `on_skill_activate` / `prepare_task_lock_turn` is resolved separately (see below). | diff --git a/jvchat/src/components/DebugInteractions.tsx b/jvchat/src/components/DebugInteractions.tsx index 7abc883f9..991a8030d 100644 --- a/jvchat/src/components/DebugInteractions.tsx +++ b/jvchat/src/components/DebugInteractions.tsx @@ -420,7 +420,8 @@ export function DebugInteractions({ .map((log: any) => { const interactionData = log.log_data?.interaction_data || {}; const metrics = (interactionData.observability_metrics || []).filter( - (m: any) => !isHarnessJournalMetric(m), + (m: any) => + !isHarnessJournalMetric(m) && m?.event_type !== "model_attempt", ); const utterance = interactionData.utterance; const conversationHistory = diff --git a/tests/action/google/test_google_sheets_mcp_oauth.py b/tests/action/google/test_google_sheets_mcp_oauth.py index a2197f904..11d7d2d16 100644 --- a/tests/action/google/test_google_sheets_mcp_oauth.py +++ b/tests/action/google/test_google_sheets_mcp_oauth.py @@ -87,6 +87,9 @@ def _ensure_google_stubs() -> None: _ensure_google_stubs() +from jvagent.action.google.google_action import ( # noqa: E402 + GoogleAuthRequiredError, +) from jvagent.action.google.google_calendar_action.google_calendar_action import ( # noqa: E402 GoogleCalendarAction, ) @@ -112,6 +115,13 @@ def _ensure_google_stubs() -> None: ) +def _stub_auth_url(cls): + return ( + "https://x/api/mcp/google_workspace/auth" + f"?account=integral&service={cls._MCP_SERVICE}" + ) + + @pytest.mark.parametrize("cls", _ACTIONS) @pytest.mark.asyncio async def test_get_credentials_uses_mcp_oauth_token(cls): @@ -472,3 +482,125 @@ def test_credentials_from_payload_without_expiry_is_expired(cls): } creds = action._credentials_from_mcp_payload(token_data) assert creds.expired is True + + +# ── typed auth failures (one error shape for all Google actions) ── + + +def _expired_mock_creds(refresh_token: str = "rtok") -> MagicMock: + creds = MagicMock() + creds.valid = False + creds.expired = True + creds.refresh_token = refresh_token + return creds + + +@pytest.mark.parametrize("cls", _ACTIONS) +@pytest.mark.asyncio +async def test_missing_scope_raises_typed_error(cls): + """A token bound to this service but without its scope is `missing_scope`.""" + action = cls() + token = { + "refresh_token": "rtok", + "scopes": ["openid", "https://www.googleapis.com/auth/userinfo.email"], + } + with ( + patch.object( + action, + "_load_mcp_token", + new=AsyncMock(return_value=("ops@example.com", token, None)), + ), + patch.object( + action, + "_credentials_from_mcp_payload", + return_value=_expired_mock_creds(), + ), + patch( + "jvagent.action.mcp_oauth.hydrate.mcp_google_workspace_auth_url", + return_value=_stub_auth_url(cls), + ), + ): + with pytest.raises(GoogleAuthRequiredError) as exc: + await action._get_credentials() + + err = exc.value + assert err.reason == "missing_scope" + assert err.service == cls._MCP_SERVICE + assert err.missing_scopes == list(cls.SCOPES) + assert cls.SCOPES[0] in str(err) + assert cls._MCP_SERVICE in err.auth_url + assert isinstance(err, ValueError) + + +@pytest.mark.parametrize("cls", _ACTIONS) +@pytest.mark.asyncio +async def test_no_token_raises_not_connected(cls): + action = cls() + with ( + patch.object( + action, "_load_mcp_token", new=AsyncMock(return_value=(None, None, None)) + ), + patch( + "jvagent.action.mcp_oauth.hydrate.mcp_google_workspace_auth_url", + return_value=_stub_auth_url(cls), + ), + ): + with pytest.raises(GoogleAuthRequiredError) as exc: + await action._get_credentials() + + err = exc.value + assert err.reason == "not_connected" + assert err.service == cls._MCP_SERVICE + assert err.auth_url == _stub_auth_url(cls) + + +@pytest.mark.parametrize("cls", _ACTIONS) +@pytest.mark.asyncio +async def test_refresh_failure_raises_typed_error(cls): + action = cls() + token = {"refresh_token": "rtok", "scopes": list(cls.SCOPES)} + creds = _expired_mock_creds() + creds.refresh.side_effect = RuntimeError("invalid_grant") + with ( + patch.object( + action, + "_load_mcp_token", + new=AsyncMock(return_value=("ops@example.com", token, None)), + ), + patch.object(action, "_credentials_from_mcp_payload", return_value=creds), + patch( + "jvagent.action.mcp_oauth.hydrate.mcp_google_workspace_auth_url", + return_value=_stub_auth_url(cls), + ), + patch("jvagent.action.oauth.audit._audit_log_oauth_event", return_value=None), + ): + with pytest.raises(GoogleAuthRequiredError) as exc: + await action._get_credentials() + + err = exc.value + assert err.reason == "refresh_failed" + assert err.service == cls._MCP_SERVICE + assert err.missing_scopes == [] + assert isinstance(err.__cause__, RuntimeError) + + +@pytest.mark.parametrize("cls", _ACTIONS) +@pytest.mark.asyncio +async def test_assert_authorized_returns_credentials(cls): + action = cls() + sentinel = MagicMock() + with patch.object(action, "_get_credentials", new=AsyncMock(return_value=sentinel)): + assert await action.assert_authorized() is sentinel + + +@pytest.mark.parametrize("cls", _ACTIONS) +@pytest.mark.asyncio +async def test_assert_authorized_propagates_typed_error(cls): + action = cls() + err = GoogleAuthRequiredError( + "no", service=cls._MCP_SERVICE, auth_url="https://x", reason="not_connected" + ) + with patch.object(action, "_get_credentials", new=AsyncMock(side_effect=err)): + with pytest.raises(GoogleAuthRequiredError) as exc: + await action.assert_authorized() + assert exc.value is err diff --git a/tests/action/intro/test_intro_interact_action.py b/tests/action/intro/test_intro_interact_action.py index c8d90786c..84ab014b4 100644 --- a/tests/action/intro/test_intro_interact_action.py +++ b/tests/action/intro/test_intro_interact_action.py @@ -1,14 +1,15 @@ """Tests for IntroInteractAction. -The intro contributes its first-message self-introduction as a response-shaping -*parameter* (HOW), not a *directive* (WHAT), so ReplyAction weaves the greeting -into the same reply as the substantive answer instead of emitting a separate -mandated section. These tests pin that contract with a lightweight fake visitor. +The intro contributes its first-message self-introduction as orchestration- +and response-scoped *parameters* (HOW), not a *directive* (WHAT), so the +executive sees the custom intro when authoring the reply and ReplyAction can +still weave the greeting into the same reply as the substantive answer. """ import pytest from jvagent.action.intro.intro_interact_action import IntroInteractAction +from jvagent.action.parameters import SCOPE_ORCHESTRATION, SCOPE_RESPONSE class _FakeVisitor: @@ -30,18 +31,20 @@ async def unrecord_action_execution(self): @pytest.mark.asyncio -async def test_new_user_adds_parameter_not_directive(): +async def test_new_user_adds_dual_scope_parameters_not_directive(): action = IntroInteractAction() visitor = _FakeVisitor(new_user=True) await action.execute(visitor) assert visitor.directives == [] # no standalone directive - assert len(visitor.parameters) == 1 - param = visitor.parameters[0] - assert param["response"] == action.directive - # Unconditional (interaction-scoped): the action already gates on new_user. - assert "condition" not in param or not param["condition"] + assert len(visitor.parameters) == 2 + scopes = {p["scope"] for p in visitor.parameters} + assert scopes == {SCOPE_ORCHESTRATION, SCOPE_RESPONSE} + for param in visitor.parameters: + assert param["key"] == "intro.first_message" + assert param["response"] == action.directive + assert "condition" not in param or not param["condition"] @pytest.mark.asyncio diff --git a/tests/action/intro/test_intro_orchestrator_egress.py b/tests/action/intro/test_intro_orchestrator_egress.py index a47c12695..7afb80626 100644 --- a/tests/action/intro/test_intro_orchestrator_egress.py +++ b/tests/action/intro/test_intro_orchestrator_egress.py @@ -1,8 +1,8 @@ """IntroInteractAction + orchestrator egress integration. -Pins the first-engagement contract: intro contributes a response parameter on -``visitor.new_user``, and orchestrator egress (via ReplyAction gather/respond) -honors it on the first reply. +Pins the first-engagement contract: intro contributes orchestration + response +parameters on ``visitor.new_user``, and orchestrator egress (via ReplyAction +gather/respond) honors the response-scoped one on the first reply. """ from __future__ import annotations @@ -16,6 +16,7 @@ from jvagent.action.orchestrator.orchestrator_interact_action import ( OrchestratorInteractAction, ) +from jvagent.action.parameters import SCOPE_ORCHESTRATION, SCOPE_RESPONSE from jvagent.action.reply.reply_action import ReplyAction pytest_plugins = ["tests.action.orchestrator.conftest"] @@ -75,13 +76,17 @@ def _set_response(content): return interaction -async def test_intro_adds_parameter_for_new_user_only(): +async def test_intro_adds_dual_scope_parameters_for_new_user_only(): intro = IntroInteractAction() interaction = _interaction_with_queues() await intro.execute(_IntroVisitor(new_user=True, interaction=interaction)) - assert len(interaction.parameters) == 1 - assert interaction.parameters[0]["response"] == intro.directive + assert len(interaction.parameters) == 2 + scopes = {p["scope"] for p in interaction.parameters} + assert scopes == {SCOPE_ORCHESTRATION, SCOPE_RESPONSE} + for param in interaction.parameters: + assert param["key"] == "intro.first_message" + assert param["response"] == intro.directive interaction.parameters.clear() visitor = _IntroVisitor(new_user=False, interaction=interaction) diff --git a/tests/action/leadgen/test_capture.py b/tests/action/leadgen/test_capture.py index 2d1311625..5586cd740 100644 --- a/tests/action/leadgen/test_capture.py +++ b/tests/action/leadgen/test_capture.py @@ -12,10 +12,9 @@ canonicalize_fields, handle_capture, merge_spec_with_action_defaults, - next_ask, ) from jvagent.action.leadgen.leadgen_action import LeadGenAction -from jvagent.action.leadgen.spec import FieldDef, GapFillDef, LeadGenSpec, SyncDef +from jvagent.action.leadgen.spec import FieldDef, HandlersDef, LeadGenSpec, SyncDef @pytest.fixture @@ -35,28 +34,6 @@ def leadgen_action_with_spec(): return action, spec -def test_next_ask_follows_priority_order(): - spec = LeadGenSpec( - name="t", - fields=[FieldDef(key="name"), FieldDef(key="phone"), FieldDef(key="email")], - gap_fill=GapFillDef(priority=["name", "phone", "email"]), - ) - # phone outranks email in priority - assert next_ask(spec, ["email", "phone"]) == "phone" - assert next_ask(spec, ["email"]) == "email" - - -def test_next_ask_none_when_complete(): - spec = LeadGenSpec(name="t", gap_fill=GapFillDef(priority=["name"])) - assert next_ask(spec, []) is None - - -def test_next_ask_falls_back_to_first_missing(): - spec = LeadGenSpec(name="t", gap_fill=GapFillDef(priority=["name"])) - # field not in priority list → fall back to first missing - assert next_ask(spec, ["budget"]) == "budget" - - def test_action_sync_config_applies_when_skill_has_none(): """Sync config on the action (agent.yaml) governs when the skill declares none.""" action = LeadGenAction() @@ -74,6 +51,9 @@ def test_action_sync_config_applies_when_skill_has_none(): assert merged.sync.mode == "on_complete" assert merged.sync.min_fields == ["name", "email"] assert merged.sync.require_any == ["phone"] + action.sales_contact = "555-0100" + merged = merge_spec_with_action_defaults(action, spec) + assert merged.sync.sales_contact == "555-0100" def test_skill_sync_wins_over_action_sync(): @@ -100,8 +80,9 @@ def test_canonicalize_aliases(): name="t", fields=[FieldDef(key="name", aliases=["full_name"])], ) - out = canonicalize_fields({"full_name": "Jane"}, spec) + out, unknown = canonicalize_fields({"full_name": "Jane", "nickname": "JJ"}, spec) assert out["name"] == "Jane" + assert unknown == ["nickname"] @pytest.mark.asyncio @@ -184,7 +165,6 @@ async def test_capture_result_includes_merged_fields(): ), FieldDef(key="interested_products", required=False), ], - gap_fill=GapFillDef(priority=["name", "email", "phone", "organization"]), sync=SyncDef(mode="manual"), ) action._registry._specs[spec.name] = spec @@ -239,7 +219,31 @@ async def test_capture_result_includes_merged_fields(): "organization", } assert second["missing_fields"] == [] - assert second["next_ask"] is None + assert "next_ask" not in second + assert second.get("next_optional") in ( + None, + "project_description", + "project_location", + "contact_role", + ) + assert "next_project_optional" not in second + assert "must_ask" not in second + assert "open_fields" not in second + assert second["next_required"] is None + assert second["optional_fields"] == [] + assert "directive" not in second + assert "no optional field is open" in second["response_directive"] + assert "gap_fill_priority" not in second + # The catalogue keeps filled fields, in declaration order, so the model can + # correct a stored value without a second list. + assert [e["key"] for e in second["field_reference"]] == [ + "name", + "email", + "phone", + "organization", + "interested_products", + ] + assert second["field_reference"][0]["required"] is True assert second["fields"]["interested_products"] == products assert second["fields"]["name"] == "Tharick Jairam" assert second["fields"]["email"] == "tharick@example.com" @@ -262,7 +266,6 @@ async def test_deduplicated_capture_still_returns_the_record(): FieldDef(key="name", required=True, validator="person_name"), FieldDef(key="interested_products", required=False), ], - gap_fill=GapFillDef(priority=["name"]), sync=SyncDef(mode="manual"), ) action._registry._specs[spec.name] = spec @@ -305,4 +308,218 @@ async def test_deduplicated_capture_still_returns_the_record(): assert repeated["fields"] == written["fields"] assert repeated["fields"]["interested_products"] == "mesh" assert repeated["missing_fields"] == [] - assert repeated["next_ask"] is None + assert "next_ask" not in repeated + assert "must_ask" not in repeated + assert "open_fields" not in repeated + assert repeated["next_required"] is None + assert repeated["optional_fields"] == [] + assert "gap_fill_priority" not in repeated + + +@pytest.mark.asyncio +async def test_unknown_field_is_reported_and_known_values_are_kept(): + action = LeadGenAction() + spec = LeadGenSpec( + name="quote_leads", + fields=[FieldDef(key="name", required=True, validator="person_name")], + sync=SyncDef(mode="manual"), + ) + action._registry._specs[spec.name] = spec + record = _FakeLeadRecord(required_fields=["name"]) + user = SimpleNamespace(user_id="u1", name=None) + interaction = SimpleNamespace(channel="default") + visitor = SimpleNamespace(interaction=interaction) + + with ( + patch( + "jvagent.action.leadgen.engine.get_user_and_interaction", + return_value=(user, interaction), + ), + patch( + "jvagent.action.leadgen.engine.LeadRecord.get_or_create_for_user", + return_value=record, + ), + patch("jvagent.action.leadgen.engine._LAST_CAPTURE", {}), + ): + result = json.loads( + await handle_capture( + action, + skill="quote_leads", + visitor=visitor, + name="Ann", + nickname="AJ", + ) + ) + + assert result["status"] == "updated" + assert result["fields"]["name"] == "Ann" + assert "nickname" not in result["fields"] + assert result["validation_errors"]["nickname"] == "unknown field" + + +@pytest.mark.asyncio +async def test_failed_handoff_names_configured_contact_only(): + action = LeadGenAction() + spec = LeadGenSpec( + name="quote_leads", + fields=[FieldDef(key="name", required=True, validator="person_name")], + sync=SyncDef( + mode="on_capture", + min_fields=["name"], + require_any=[], + sales_contact="555-0199", + ), + ) + action._registry._specs[spec.name] = spec + record = _FakeLeadRecord(required_fields=["name"]) + user = SimpleNamespace(user_id="u1", name=None) + interaction = SimpleNamespace(channel="default") + visitor = SimpleNamespace(interaction=interaction) + + with ( + patch( + "jvagent.action.leadgen.engine.get_user_and_interaction", + return_value=(user, interaction), + ), + patch( + "jvagent.action.leadgen.engine.LeadRecord.get_or_create_for_user", + return_value=record, + ), + patch("jvagent.action.leadgen.engine._LAST_CAPTURE", {}), + ): + result = json.loads( + await handle_capture( + action, skill="quote_leads", visitor=visitor, name="Ann" + ) + ) + + assert "directive" not in result + assert "555-0199" in result["response_directive"] + assert "saved but not yet sent" in result["response_directive"] + assert "592" not in result["response_directive"] + + +@pytest.mark.asyncio +async def test_handoff_sentence_returns_when_the_snapshot_changes(): + action = LeadGenAction() + spec = LeadGenSpec( + name="quote_leads", + fields=[ + FieldDef(key="name", required=True, validator="person_name"), + FieldDef(key="project_description"), + FieldDef(key="note"), + ], + sync=SyncDef(mode="on_capture"), + ) + action._registry._specs[spec.name] = spec + record = _FakeLeadRecord(required_fields=["name"]) + user = SimpleNamespace(user_id="u1", name=None) + interaction = SimpleNamespace(channel="default") + visitor = SimpleNamespace(interaction=interaction) + + async def _synced(*_args, **_kwargs): + return {"status": "sync-complete", "results": []} + + with ( + patch( + "jvagent.action.leadgen.engine.get_user_and_interaction", + return_value=(user, interaction), + ), + patch( + "jvagent.action.leadgen.engine.LeadRecord.get_or_create_for_user", + return_value=record, + ), + patch("jvagent.action.leadgen.engine.maybe_auto_sync", new=_synced), + patch("jvagent.action.leadgen.engine._LAST_CAPTURE", {}), + ): + first = json.loads( + await handle_capture( + action, + skill="quote_leads", + visitor=visitor, + name="Ann", + project_description="roof", + ) + ) + second = json.loads( + await handle_capture( + action, + skill="quote_leads", + visitor=visitor, + note="call after 4", + ) + ) + record._data.pop("project_description") + third = json.loads( + await handle_capture( + action, + skill="quote_leads", + visitor=visitor, + project_description="new job", + ) + ) + + assert first["directive"] == "Hand-off is complete." + assert first["response_directive"].startswith("Tell the user or ask the user:") + assert "Hand-off is complete" not in first["response_directive"] + assert ( + "ask no further field" in first["response_directive"] + or "ask for" in first["response_directive"] + ) + assert "do not repeat" not in first["response_directive"].casefold() + assert second["directive"] == "Hand-off already stated." + assert "do not repeat" in second["response_directive"].casefold() + assert "Hand-off already stated" not in second["response_directive"] + assert second["response_directive"].startswith("Tell the user or ask the user:") + assert third["directive"] == "Hand-off is complete." + assert "do not repeat" not in third["response_directive"].casefold() + assert third["response_directive"].startswith("Tell the user or ask the user:") + assert "Hand-off is complete" not in third["response_directive"] + + +@pytest.mark.asyncio +async def test_qualify_blocked_saves_locally_and_returns_failed_handoff_directive(): + """CRM qualify block: persist the capture, do not sync, hand the model a + failed-hand-off directive (with response_directive for Reply).""" + action = LeadGenAction() + spec = LeadGenSpec( + name="quote_leads", + fields=[FieldDef(key="name", required=True, validator="person_name")], + sync=SyncDef(mode="manual", sales_contact="555-0199"), + handlers=HandlersDef(qualify="block_handoff"), + ) + action._registry._specs[spec.name] = spec + record = _FakeLeadRecord(required_fields=["name"]) + user = SimpleNamespace(user_id="u1", name=None) + interaction = SimpleNamespace(channel="default") + visitor = SimpleNamespace(interaction=interaction) + + async def _block_hook(_spec, _handler, ctx): + ctx.block_sync("crm_handoff_blocked") + return ctx + + with ( + patch( + "jvagent.action.leadgen.engine.get_user_and_interaction", + return_value=(user, interaction), + ), + patch( + "jvagent.action.leadgen.engine.LeadRecord.get_or_create_for_user", + return_value=record, + ), + patch("jvagent.action.leadgen.engine.call_hook", side_effect=_block_hook), + patch("jvagent.action.leadgen.engine._LAST_CAPTURE", {}), + ): + result = json.loads( + await handle_capture( + action, skill="quote_leads", visitor=visitor, name="Ann" + ) + ) + + assert result["status"] == "blocked" + assert result["reason"] == "crm_handoff_blocked" + assert record.get_yaml().get("name") == "Ann" + assert "directive" not in result + assert "555-0199" in result["response_directive"] + assert "saved but not yet sent" in result["response_directive"] + assert result["response_directive"].startswith("Tell the user or ask the user:") diff --git a/tests/action/leadgen/test_open_fields.py b/tests/action/leadgen/test_open_fields.py new file mode 100644 index 000000000..1905ee58a --- /dev/null +++ b/tests/action/leadgen/test_open_fields.py @@ -0,0 +1,618 @@ +"""Tests for the leadgen field catalogue, capture state, and field validation.""" + +from __future__ import annotations + +import pytest + +from jvagent.action.leadgen.engine import ( + HANDOFF_ALREADY_STATED_MARKER, + HANDOFF_COMPLETE_MARKER, + HANDOFF_SNAPSHOT_KEY, + HANDOFF_STATED_KEY, + MAX_OPTIONAL_FIELDS, + SYNC_FAILED_DIRECTIVE, + attach_reply_directives, + capture_state, + handoff_already_stated, + handoff_directive, + next_ask_directive, + optional_field_keys, + payload_has_refusal, + to_response_directive, + validate_fields, +) +from jvagent.action.leadgen.spec import ( + FieldDef, + LeadGenSpec, + SyncDef, + fields_reference, + parse_leadgen_spec, +) + + +class _Record: + def __init__(self, data, missing=None): + self._data = dict(data) + self._missing = list(missing or []) + + def get_yaml(self): + return dict(self._data) + + def get_missing_fields(self): + return list(self._missing) + + +def _project_spec(): + return LeadGenSpec( + name="t", + fields=[ + FieldDef(key="full_name", required=True), + FieldDef(key="project_description"), + FieldDef(key="project_location"), + FieldDef(key="contact_role"), + FieldDef( + key="project_budget", + relevant_when={"any_present": ["project_description"]}, + ), + FieldDef( + key="project_timeline", + relevant_when={"any_present": ["project_description"]}, + ), + ], + sync=SyncDef(mode="manual"), + ) + + +def test_catalogue_lists_every_declared_field_in_order(): + spec = _project_spec() + ref = fields_reference(spec) + assert [e["key"] for e in ref] == [f.key for f in spec.fields] + by_key = {e["key"]: e for e in ref} + # A filled field stays in the catalogue so the model can correct it. + assert by_key["project_location"]["required"] is False + assert by_key["full_name"]["required"] is True + + +def test_catalogue_carries_relevant_when_as_data(): + by_key = {e["key"]: e for e in fields_reference(_project_spec())} + assert by_key["project_budget"]["relevant_when"] == { + "any_present": ["project_description"] + } + assert "relevant_when" not in by_key["full_name"] + + +def test_capture_state_points_at_the_next_ask(): + spec = _project_spec() + state = capture_state(_Record({"full_name": "Ann"}, missing=["email"]), spec) + assert set(state) == { + "fields", + "missing_fields", + "next_required", + "optional_fields", + "next_optional", + "stop_optional", + "field_reference", + "response_directive", + } + assert state["missing_fields"] == ["email"] + assert state["next_required"] == "email" + assert "directive" not in state + assert "`email`" in state["response_directive"] + assert state["fields"] == {"full_name": "Ann"} + # The optional pool is keys only; guidance stays in field_reference once. + assert state["optional_fields"] == [ + "project_description", + "project_location", + "contact_role", + ] + for removed in ("next_ask", "next_project_optional", "ask_next"): + assert removed not in state + assert state["next_optional"] == "project_description" + assert state["stop_optional"] is False + + +def test_capture_state_switches_to_the_optional_pool(): + state = capture_state(_Record({"full_name": "Ann"}, missing=[]), _project_spec()) + assert state["next_required"] is None + assert "directive" not in state + assert "Required fields are complete" in state["response_directive"] + assert "`project_description`" in state["response_directive"] + assert "one field, one question" in state["response_directive"] + assert "never rotate to another optional" in state["response_directive"] + + +def test_optional_pool_honours_relevant_when(): + fields = { + "full_name": "Ann", + "project_description": "slope repair after heavy rain", + "project_location": "Region 5", + } + keys = optional_field_keys(fields, _project_spec()) + assert "project_budget" in keys + assert "project_timeline" in keys + assert "project_location" not in keys + + +def test_directive_closes_when_nothing_is_open(): + directive = next_ask_directive(None, []) + assert "Do not ask" in directive + assert "no optional field is open" in directive + + +def test_directive_acknowledges_then_asks_the_required_field(): + directive = next_ask_directive("full_name", []) + assert "`full_name`" in directive + assert "do not ask any other field" in directive + assert "Never store a refusal" in directive + # The refusal sentence is not part of a normal ask (Q1). + assert "would you like to continue or cancel" not in directive + + +def test_required_refusal_sentence_names_the_refused_field(): + directive = next_ask_directive( + "phone", [], ask_label="phone number", refused_label="the email address" + ) + assert "the email address is needed" in directive + assert "would you like to continue or cancel" in directive + # Q2: the sentence names the refused field, not the next required one. + assert "phone number is needed" not in directive + + +def test_directive_acknowledges_then_asks_the_optional_field(): + directive = next_ask_directive(None, ["project_budget"]) + assert "`project_budget`" in directive + assert "answered with a value" in directive + assert "never rotate to another optional" in directive + assert "Optional fields never block the request" in directive + + +def test_handoff_directive_asks_the_one_the_request_needs(): + closed = handoff_directive([]) + assert "ask no further field" in closed + assert "Hand-off is complete" in closed + open_pool = handoff_directive(["contact_role", "company_industry"]) + assert "hand-off sentence" in open_pool + assert "ask for `contact_role` now" in open_pool + assert "`company_industry`" not in open_pool + assert "one field, one question" in open_pool + assert "A refusal" in open_pool + assert "ignore moves on" not in open_pool + + +def test_to_response_directive_frames_ask_none_for_reply_action(): + instruction = handoff_directive([]) + assert instruction.startswith("Hand-off is complete.") + rd = to_response_directive(instruction) + assert rd.startswith("Tell the user or ask the user:") + assert "Hand-off is complete" not in rd + assert "ask no further field" in rd + assert "hand-off sentence" in rd + + +def test_to_response_directive_strips_already_stated_marker(): + instruction = handoff_directive(["project_location"], already_stated=True) + assert instruction.startswith("Hand-off already stated.") + rd = to_response_directive(instruction) + assert rd.startswith("Tell the user or ask the user:") + assert "Hand-off already stated" not in rd + assert "ask for `project_location` now" in rd + + +def test_attach_reply_directives_keeps_observation_marker(): + target: dict = {} + instruction = handoff_directive([]) + attach_reply_directives(target, instruction) + assert target["directive"] == HANDOFF_COMPLETE_MARKER + assert target["response_directive"].startswith("Tell the user or ask the user:") + assert "ask no further field" in target["response_directive"] + assert "Hand-off is complete" not in target["response_directive"] + + +def test_attach_reply_directives_already_stated_is_marker_only(): + target: dict = {} + instruction = handoff_directive(["company_industry"], already_stated=True) + attach_reply_directives(target, instruction) + assert target["directive"] == HANDOFF_ALREADY_STATED_MARKER + assert "ask for `company_industry`" in target["response_directive"] + assert "Hand-off already stated" not in target["response_directive"] + assert target["directive"] not in target["response_directive"] + + +def test_attach_reply_directives_omits_directive_without_handoff_marker(): + target: dict = {"directive": "stale"} + instruction = next_ask_directive("email", []) + attach_reply_directives(target, instruction) + assert "directive" not in target + assert "`email`" in target["response_directive"] + assert target["response_directive"].startswith("Tell the user or ask the user:") + + +def test_capture_state_includes_response_directive(): + spec = LeadGenSpec( + name="t", + fields=[FieldDef(key="full_name", required=True)], + sync=SyncDef(), + ) + state = capture_state(_Record({"full_name": "Ann"}, missing=[]), spec) + assert "directive" not in state + assert state["response_directive"].startswith("Tell the user or ask the user:") + assert "Do not ask another field" in state["response_directive"] + + +def test_handoff_directive_is_agent_neutral_and_names_only_the_first(): + directive = handoff_directive(["budget_range", "preferred_contact"]) + assert "`budget_range`" in directive + assert "preferred_contact" not in directive + for key in ("contact_role", "quote_items", "order_items", "organization"): + assert key not in directive + + +def test_handoff_directive_does_not_repeat_after_the_first(): + repeat = handoff_directive(["project_location"], already_stated=True) + assert repeat.startswith("Hand-off already stated. ") + assert "Do not repeat the hand-off sentence." in repeat + assert "Briefly acknowledge" in repeat + assert "no sales-team or same-request restatement" in repeat + assert "added to the same request" not in repeat + assert "ask for `project_location` now" in repeat + assert "one field, one question" in repeat + assert "Use the skill's hand-off sentence, then ask" not in repeat + + +def test_handoff_directive_acknowledges_when_pool_closed_and_stated(): + repeat = handoff_directive([], already_stated=True) + assert repeat.startswith("Hand-off already stated. ") + assert "Do not repeat the hand-off sentence." in repeat + assert "Close in one natural sentence" in repeat + assert "will follow up" in repeat + assert "Ask no field" in repeat + assert "no invented field" in repeat + assert "up to date" not in repeat + + +def test_optional_pool_is_capped_at_max_optional_fields(): + keys = [f"opt_{i}" for i in range(MAX_OPTIONAL_FIELDS + 2)] + spec = LeadGenSpec( + name="t", + fields=[FieldDef(key="full_name", required=True)] + + [FieldDef(key=key) for key in keys], + sync=SyncDef(), + ) + pool = optional_field_keys({"full_name": "Ann"}, spec) + assert pool == keys[:MAX_OPTIONAL_FIELDS] + + +def test_optional_pool_drops_a_declined_gate_key(): + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="organization", required=True, decline_value="Personal"), + FieldDef( + key="contact_role", + relevant_when={ + "any_present": ["organization"], + "not_declined": ["organization"], + }, + ), + FieldDef( + key="company_industry", + relevant_when={"any_present": ["contact_role"]}, + ), + ], + sync=SyncDef(mode="manual"), + ) + retail = {"organization": "personal"} + assert optional_field_keys(retail, spec) == [] + business = {"organization": "GT Construction Ltd"} + assert optional_field_keys(business, spec) == ["contact_role"] + + +def test_optional_pool_never_offers_a_capture_only_field(): + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="full_name", required=True), + FieldDef(key="quote_items", capture_only=True), + FieldDef(key="additional_details", capture_only=True), + FieldDef(key="contact_role"), + ], + sync=SyncDef(mode="manual"), + ) + assert optional_field_keys({"full_name": "Ann"}, spec) == ["contact_role"] + + +def test_parse_relevant_when(): + spec = parse_leadgen_spec( + { + "fields": [ + {"key": "project_description"}, + { + "key": "project_budget", + "relevant_when": {"any_present": ["project_description"]}, + }, + ], + }, + source_dir="/tmp", + default_name="s", + ) + f = spec.get_field("project_budget") + assert f is not None + assert f.relevant_when == {"any_present": ["project_description"]} + ref = next(e for e in fields_reference(spec) if e["key"] == "project_budget") + assert ref["relevant_when"]["any_present"] == ["project_description"] + + +def test_parse_ignores_deprecated_gap_fill_keys(caplog): + """Old order keys must not break an existing skill. They are unused.""" + import logging + + with caplog.at_level(logging.WARNING): + spec = parse_leadgen_spec( + { + "fields": [{"key": "project_description"}], + "gap_fill": { + "batch": False, + "priority": ["project_description"], + "qualification": ["project_description"], + }, + }, + source_dir="/tmp", + default_name="s", + ) + assert spec.gap_fill.batch is False + assert "priority" in caplog.text + assert "qualification" in caplog.text + + +@pytest.mark.asyncio +async def test_validate_fields_keeps_valid_and_reports_errors(): + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="full_name", validator="person_name"), + FieldDef(key="email", validator="email"), + ], + ) + validated, errors = await validate_fields( + {"full_name": "Ann", "email": "bad"}, spec + ) + assert validated["full_name"] == "Ann" + assert "email" not in validated + assert "email" in errors + + +@pytest.mark.asyncio +async def test_validate_fields_accepts_decline_value(): + spec = LeadGenSpec( + name="t", + fields=[FieldDef(key="email", validator="email", decline_value="N/A")], + ) + validated, errors = await validate_fields({"email": "N/A"}, spec) + assert validated["email"] == "N/A" + assert errors == {} + + +@pytest.mark.asyncio +async def test_phone_locale_applies_to_any_phone_field(): + spec = LeadGenSpec(name="t", fields=[FieldDef(key="mobile", phone_locale="GY")]) + validated, errors = await validate_fields({"mobile": "6001234"}, spec) + assert errors == {} + assert validated["mobile"] == "+592 600 1234" + + +@pytest.mark.asyncio +async def test_unknown_phone_locale_falls_back_to_e164(): + spec = LeadGenSpec(name="t", fields=[FieldDef(key="mobile", phone_locale="ZZ")]) + validated, errors = await validate_fields({"mobile": "6001234"}, spec) + assert errors == {} + assert validated["mobile"] == "+6001234" + + +@pytest.mark.asyncio +async def test_literal_decline_sentinel_maps_to_the_field_value(): + spec = LeadGenSpec( + name="t", + fields=[FieldDef(key="company_industry", decline_value="Not provided")], + ) + validated, errors = await validate_fields( + {"company_industry": "decline_value"}, spec + ) + assert errors == {} + assert validated["company_industry"] == "Not provided" + + +@pytest.mark.asyncio +async def test_refusal_phrase_without_sentinel_is_stored_as_value(): + """Phrase dictionaries are gone; only the decline_value sentinel maps.""" + spec = LeadGenSpec( + name="t", + fields=[FieldDef(key="company_industry", decline_value="Not provided")], + ) + validated, errors = await validate_fields( + {"company_industry": "no quiero decir"}, spec + ) + assert errors == {} + assert validated["company_industry"] == "no quiero decir" + + +@pytest.mark.asyncio +async def test_sentinel_on_a_field_without_a_decline_value_is_rejected(): + spec = LeadGenSpec(name="t", fields=[FieldDef(key="full_name", required=True)]) + validated, errors = await validate_fields({"full_name": "decline_value"}, spec) + assert "full_name" not in validated + assert "full_name" in errors + + +def test_any_present_ignores_a_declined_prerequisite(): + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="project_description", decline_value="Not provided"), + FieldDef( + key="project_pain_points", + relevant_when={"any_present": ["project_description"]}, + ), + ], + ) + fields = {"project_description": "Not provided"} + assert "project_pain_points" not in optional_field_keys(fields, spec) + fields = {"project_description": "Slope repair after heavy rain"} + assert "project_pain_points" in optional_field_keys(fields, spec) + + +def test_optional_directive_closes_after_a_decline(): + text = next_ask_directive(None, ["company_size"], just_declined=True) + assert "ask no further" in text.lower() + assert "company_size" not in text + + +def test_optional_directive_is_conditional_without_a_decline(): + text = next_ask_directive(None, ["company_size"]) + assert "company_size" in text + assert "has not refused" in text + + +def test_handoff_directive_closes_after_a_decline(): + text = handoff_directive(["company_size"], just_declined=True) + assert "company_size" not in text + assert "ask no field" in text + + +def test_declined_close_names_the_handoff_state(): + text = handoff_directive(["company_size"], just_declined=True) + assert "Hand-off is complete" in text + assert "same request" in text + + +def test_declined_close_after_handoff_mentions_updates(): + text = handoff_directive(["company_size"], just_declined=True, already_stated=True) + assert text.startswith("Hand-off already stated. ") + assert "Do not repeat the hand-off sentence." in text + assert "Close in one natural sentence" in text + assert "will follow up" in text + assert "will update it" not in text + assert "same request" not in text + + +def test_pre_sync_declined_close_never_claims_sent(): + text = next_ask_directive(None, ["company_size"], just_declined=True) + assert "saved" in text + assert "Do not say it was sent" in text + + +def test_failed_sync_directive_is_truthful(): + from jvagent.action.leadgen.engine import failed_sync_directive + + assert "saved but not yet sent" in SYNC_FAILED_DIRECTIVE + assert "Never say sent" in SYNC_FAILED_DIRECTIVE + assert "Ask no further field" in SYNC_FAILED_DIRECTIVE + assert "592" not in SYNC_FAILED_DIRECTIVE + assert "sales contact" not in SYNC_FAILED_DIRECTIVE + named = failed_sync_directive("555-0100") + assert "555-0100" in named + assert "Offer the contact" in named + sales = failed_sync_directive( + "555-0100", contact_label="sales contact", entity="quote" + ) + assert "Offer the sales contact 555-0100" in sales + assert "The quote is saved" in sales + + +def test_handoff_after_statement_requires_flexible_ack_not_same_request_script(): + text = handoff_directive(["project_location"], already_stated=True) + assert "Briefly acknowledge" in text + assert "no sales-team or same-request restatement" in text + assert "added to the same request" not in text + assert text.startswith("Hand-off already stated. ") + assert "do not repeat the hand-off sentence" in text.casefold() + assert "ask for `project_location` now" in text + + +def test_declined_close_after_statement_pins_the_close_sentence(): + text = handoff_directive( + ["project_location"], already_stated=True, just_declined=True + ) + assert "Close in one natural sentence" in text + assert "will follow up" in text + assert "Ask no field" in text + assert "no invented field" in text + assert "exact sentence" not in text + assert "will update it" not in text + assert text.startswith("Hand-off already stated. ") + + +def test_refusal_signal_is_sentinel_only(): + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="organization", decline_value="Personal"), + FieldDef(key="project_description", decline_value="Not provided"), + ], + ) + assert payload_has_refusal({"organization": "Personal"}, spec) is False + assert payload_has_refusal({"organization": "no organization"}, spec) is False + assert payload_has_refusal({"organization": "decline_value"}, spec) is True + assert payload_has_refusal({"project_description": "decline_value"}, spec) is True + + +def test_handoff_flag_resets_when_a_snapshotted_value_changes(): + stated = { + HANDOFF_STATED_KEY: True, + HANDOFF_SNAPSHOT_KEY: {"name": "Ann", "project_description": "roof"}, + "name": "Ann", + "project_description": "roof", + "contact_role": "buyer", + } + assert handoff_already_stated(stated) is True + new_cycle = dict(stated) + del new_cycle["project_description"] + assert handoff_already_stated(new_cycle) is False + assert handoff_already_stated({HANDOFF_STATED_KEY: True, "name": "Ann"}) is False + + +def test_stop_optional_empties_the_pool_and_asks_nothing(): + state = capture_state( + _Record({"full_name": "Ann"}, missing=[]), _project_spec(), stop_optional=True + ) + assert state["optional_fields"] == [] + assert state["next_optional"] is None + assert state["stop_optional"] is True + assert "directive" not in state + assert "Ask no further field" in state["response_directive"] + + +def test_ignored_optional_is_never_offered_again(): + spec = _project_spec() + fields = {"full_name": "Ann"} + pool = optional_field_keys(fields, spec) + assert pool + after = optional_field_keys(fields, spec, ignored=(pool[0],)) + assert pool[0] not in after + + +def test_decline_sentinel_detection(): + from jvagent.action.leadgen.engine import _is_decline_sentinel + + assert _is_decline_sentinel("decline_value") + assert _is_decline_sentinel("Decline_Value") + assert not _is_decline_sentinel("No.") + assert not _is_decline_sentinel("me nah wah say") + assert not _is_decline_sentinel("Project Manager") + + +def test_visitor_label_uses_label_then_short_guidance_then_key(): + from jvagent.action.leadgen.engine import _visitor_label + from jvagent.action.leadgen.spec import FieldDef, LeadGenSpec + + spec = LeadGenSpec( + name="t", + fields=[ + FieldDef(key="full_name", label="full name", guidance="x" * 100), + FieldDef(key="contact_role", guidance="x" * 100), + FieldDef(key="email", guidance="email address"), + ], + ) + assert _visitor_label(spec, "full_name") == "full name" + assert _visitor_label(spec, "contact_role") == "contact role" + assert _visitor_label(spec, "email") == "email address" + assert _visitor_label(spec, None) == "" diff --git a/tests/action/leadgen/test_spec.py b/tests/action/leadgen/test_spec.py index d77857e3b..4dd372e8c 100644 --- a/tests/action/leadgen/test_spec.py +++ b/tests/action/leadgen/test_spec.py @@ -2,7 +2,10 @@ from pathlib import Path +import pytest + from jvagent.action.leadgen.spec import ( + DEFAULT_CHANNEL_DEFAULTS, load_leadgen_spec_from_skill, parse_leadgen_spec, ) @@ -41,3 +44,70 @@ def test_load_example_leadgen_skill(): assert spec.name == "example_leadgen" assert "full_name" in spec.field_keys() assert spec.sync.mode == "on_capture" + assert spec.messages.handoff_team == "sales team" + assert spec.sync.min_fields == ["full_name"] + + +def test_sync_defaults_are_empty_gates(): + spec = parse_leadgen_spec( + {"fields": [{"key": "issue"}], "sync": {"mode": "on_capture"}}, + source_dir="/tmp", + default_name="t", + ) + assert spec.sync.min_fields == [] + assert spec.sync.require_any == [] + assert spec.sync.timezone == "UTC" + + +def test_messages_and_timezone_parse(): + spec = parse_leadgen_spec( + { + "messages": { + "entity": "ticket", + "handoff_team": "support", + "contact_label": "help desk", + "visitor": "customer", + }, + "sync": {"timezone": "America/Guyana", "min_fields": ["issue"]}, + "fields": [{"key": "issue", "required": True}], + }, + source_dir="/tmp", + default_name="t", + ) + assert spec.messages.entity == "ticket" + assert spec.messages.handoff_team == "support" + assert spec.sync.timezone == "America/Guyana" + assert spec.sync.min_fields == ["issue"] + + +def test_channel_defaults_omitted_disables_autofill(): + spec = parse_leadgen_spec( + {"fields": [{"key": "phone"}]}, + source_dir="/tmp", + default_name="t", + ) + assert spec.channel_defaults is None + assert spec.resolved_channel_defaults() == {} + assert DEFAULT_CHANNEL_DEFAULTS == {} + + +def test_channel_defaults_empty_disables_autofill(): + spec = parse_leadgen_spec( + {"fields": [{"key": "phone"}], "channel_defaults": {}}, + source_dir="/tmp", + default_name="t", + ) + assert spec.channel_defaults == {} + assert spec.resolved_channel_defaults() == {} + + +def test_channel_defaults_rejects_bad_source(): + with pytest.raises(ValueError, match="user_id or user_name"): + parse_leadgen_spec( + { + "fields": [{"key": "phone"}], + "channel_defaults": {"whatsapp": {"phone": "email"}}, + }, + source_dir="/tmp", + default_name="t", + ) diff --git a/tests/action/leadgen/test_store_resolution.py b/tests/action/leadgen/test_store_resolution.py index 15b6d1fcc..5c9ca19cc 100644 --- a/tests/action/leadgen/test_store_resolution.py +++ b/tests/action/leadgen/test_store_resolution.py @@ -100,3 +100,13 @@ async def test_append_to_section_does_not_wipe_lead_record(): finally: await db.close() clear_default_context() + + +def test_no_core_field_vocabulary(): + """The action has no default field vocabulary; the skill spec is the source.""" + from jvagent.action.leadgen.store import DEFAULT_REQUIRED_FIELDS + + assert DEFAULT_REQUIRED_FIELDS == [] + record = LeadRecord() + assert record.get_required_fields() == [] + assert record.get_missing_fields() == [] diff --git a/tests/action/leadgen/test_sync_templates.py b/tests/action/leadgen/test_sync_templates.py index ce0f3bcfb..b53f5c3d2 100644 --- a/tests/action/leadgen/test_sync_templates.py +++ b/tests/action/leadgen/test_sync_templates.py @@ -82,6 +82,17 @@ def test_substitute_field_token(): assert sync_mod.substitute("{name}", data, "u1") == "Jane" +def test_substitute_last_updated_uses_timezone(): + from datetime import datetime + from zoneinfo import ZoneInfo + + out = sync_mod.substitute("{last_updated}", {}, "u1", timezone_name="UTC") + # YYYY-MM-DD HH:MM + assert len(out) == 16 + parsed = datetime.strptime(out, "%Y-%m-%d %H:%M").replace(tzinfo=ZoneInfo("UTC")) + assert abs((datetime.now(ZoneInfo("UTC")) - parsed).total_seconds()) < 120 + + def test_substitute_excludes_internal_keys(): """Internal (_) keys must not leak into synced output.""" data = {"name": "Jane", sync_mod.DIGEST_KEY: "deadbeef"} diff --git a/tests/action/leadgen/test_validators.py b/tests/action/leadgen/test_validators.py index 76f7fa3af..561e4224c 100644 --- a/tests/action/leadgen/test_validators.py +++ b/tests/action/leadgen/test_validators.py @@ -1,10 +1,18 @@ """Tests for leadgen validators.""" +import pytest + from jvagent.action.leadgen.validators import ( + locale_validator, + run_validator, + validate_date, validate_email, + validate_enum, + validate_number, validate_person_name, validate_phone_e164, validate_phone_gy, + validate_regex, ) @@ -14,10 +22,11 @@ def test_validate_email_normalizes(): assert val == "jane@example.com" -def test_validate_email_na_sentinel(): +def test_validate_email_rejects_na_without_at(): + """Decline text N/A is handled by the engine decline path, not the validator.""" val, err = validate_email("N/A") - assert err is None - assert val == "N/A" + assert val is None + assert err is not None def test_validate_phone_e164(): @@ -36,3 +45,74 @@ def test_validate_person_name(): val, err = validate_person_name("Jane Doe") assert err is None assert val == "Jane Doe" + + +def test_locale_validator_resolves_builtin(): + assert locale_validator("GY") == "phone_gy" + assert locale_validator("e164") == "phone_e164" + assert locale_validator("ZZ") == "" + assert locale_validator("") == "" + + +def test_validate_person_name_rejects_too_many_words(): + val, err = validate_person_name("One Two Three Four Five") + assert val is None + assert "too many words" in err + + +def test_validate_person_name_keeps_legitimate_names(): + for raw in ("Anne-Marie Jodhan", "Sonya Oodit", "Test User", "Oodit"): + val, err = validate_person_name(raw) + assert err is None + assert val == raw + + +def test_validate_enum(): + val, err = validate_enum("MEDIUM", choices=["low", "medium", "high"]) + assert err is None + assert val == "medium" + val, err = validate_enum("urgent", choices=["low", "medium", "high"]) + assert val is None + assert err is not None + + +def test_validate_regex(): + val, err = validate_regex("AB-12", pattern=r"[A-Z]{2}-\d{2}") + assert err is None + assert val == "AB-12" + val, err = validate_regex("ab-12", pattern=r"[A-Z]{2}-\d{2}") + assert val is None + + +def test_validate_number_range(): + val, err = validate_number("3.5", min=1, max=5) + assert err is None + assert val == "3.5" + val, err = validate_number("10", min=1, max=5) + assert val is None + + +def test_validate_date_iso(): + val, err = validate_date("2026-11-13") + assert err is None + assert val == "2026-11-13" + val, err = validate_date("13/11/2026", formats=["%d/%m/%Y"]) + assert err is None + assert val == "2026-11-13" + + +def test_unknown_validator_errors(): + val, err = run_validator("not_a_real_validator", "x") + assert val is None + assert "unknown validator" in err + + +def test_parse_rejects_unknown_validator(): + from jvagent.action.leadgen.spec import parse_leadgen_spec + + with pytest.raises(ValueError, match="unknown"): + parse_leadgen_spec( + {"fields": [{"key": "x", "validator": "emial"}]}, + source_dir="/tmp", + default_name="t", + ) diff --git a/tests/action/mcp/test_mcp_action_startup.py b/tests/action/mcp/test_mcp_action_startup.py index 23a1d5c92..e23b05c12 100644 --- a/tests/action/mcp/test_mcp_action_startup.py +++ b/tests/action/mcp/test_mcp_action_startup.py @@ -36,10 +36,7 @@ async def test_on_startup_rebuilds_server_registry(): @pytest.mark.asyncio -@pytest.mark.parametrize("auth_type", ["oauth", "service_key"]) -async def test_unsupported_http_auth_profile_fails_before_connect( - auth_type: str, -) -> None: +async def test_unknown_http_auth_profile_fails_before_connect() -> None: action = MCPAction( sandbox_mode=False, servers=[ @@ -47,7 +44,7 @@ async def test_unsupported_http_auth_profile_fails_before_connect( "name": "external", "transport": "streamable_http", "url": "https://example.test/mcp", - "auth": {"type": auth_type}, + "auth": {"type": "mystery"}, } ], ) diff --git a/tests/action/mcp/test_mcp_auth_clients.py b/tests/action/mcp/test_mcp_auth_clients.py new file mode 100644 index 000000000..e9bc39632 --- /dev/null +++ b/tests/action/mcp/test_mcp_auth_clients.py @@ -0,0 +1,350 @@ +"""MCP transport httpx clients must follow Core's ``/api/mcp`` trailing-slash 307. + +Core advertises the MCP endpoint without a trailing slash; its Starlette Mount +answers ``POST /api/mcp`` with a 307 to ``/api/mcp/``. The MCP SDK consumes the +client we pass as-is and raises on that response, so both auth clients must +follow redirects — but only to the configured trusted origin. +""" + +from __future__ import annotations + +import httpx +import pytest + +from jvagent.action.mcp.integral_oauth_auth import build_integral_oauth_client +from jvagent.action.mcp.redirect_trust import UntrustedRedirectError +from jvagent.action.mcp.service_key_auth import build_service_key_client + +_TRUSTED = "https://core.invalid/api/mcp" +_SERVICE_KEY = "k" * 32 + + +async def test_integral_oauth_client_follows_redirects(): + client = build_integral_oauth_client( + server_name="integral_core", + account="integral", + mcp_url=_TRUSTED, + connect_timeout=1.0, + read_timeout=1.0, + ) + try: + assert client.follow_redirects is True + finally: + await client.aclose() + + +async def test_service_key_client_follows_redirects(): + client = build_service_key_client( + service_key=_SERVICE_KEY, + user_id="u", + mcp_url=_TRUSTED, + connect_timeout=1.0, + read_timeout=1.0, + ) + try: + assert client.follow_redirects is True + finally: + await client.aclose() + + +async def test_integral_client_stores_configured_scope(): + client = build_integral_oauth_client( + server_name="integral_core", + account="integral", + scope="integral:read integral:execute", + mcp_url="http://127.0.0.1:54853/api/mcp/", + connect_timeout=1.0, + read_timeout=1.0, + ) + try: + assert client._auth._scope == "integral:read integral:execute" + assert client._auth._mcp_url == "http://127.0.0.1:54853/api/mcp/" + finally: + await client.aclose() + + +class _FakeNode: + pass + + +async def test_integral_refresh_prefers_configured_scope(monkeypatch): + import jvagent.action.mcp.integral_oauth_auth as mod + + captured = {} + + async def _fake_discover(**kwargs): + return {"token_endpoint": "http://core.invalid/api/oauth/token"} + + async def _fake_refresh(meta, *, client_id, refresh_token, scope): + captured["scope"] = scope + return {"access_token": "at", "expires_in": 3600, "refresh_token": "rt"} + + async def _fake_save(node, payload): + captured["payload"] = payload + + def _env_scope(*a, **k): + return "env:scope" + + monkeypatch.setattr(mod, "discover_authorization_server", _fake_discover) + monkeypatch.setattr(mod, "refresh_access_token", _fake_refresh) + monkeypatch.setattr(mod, "_save_token_payload", _fake_save) + monkeypatch.setattr(mod, "resolve_scope", _env_scope) + + auth = mod.IntegralOAuthAuth( + server_name="integral_core", + account_name="integral", + scope="integral:read integral:execute", + ) + payload = { + "refresh_token": "rt", + "client_id": "cid", + "access_token": "old", + "token_uri": "http://core.invalid/api/oauth/token", + "expiry": "2000-01-01T00:00:00Z", + } + token = await auth._refresh(_FakeNode(), payload) + assert token == "at" + assert captured["scope"] == "integral:read integral:execute" + + +async def test_integral_refresh_falls_back_to_env_scope(monkeypatch): + import jvagent.action.mcp.integral_oauth_auth as mod + + captured = {} + + async def _fake_discover(**kwargs): + return {"token_endpoint": "http://core.invalid/api/oauth/token"} + + async def _fake_refresh(meta, *, client_id, refresh_token, scope): + captured["scope"] = scope + return {"access_token": "at", "expires_in": 3600} + + async def _fake_save(node, payload): + pass + + def _env_scope(*a, **k): + return "integral:read" + + monkeypatch.setattr(mod, "discover_authorization_server", _fake_discover) + monkeypatch.setattr(mod, "refresh_access_token", _fake_refresh) + monkeypatch.setattr(mod, "_save_token_payload", _fake_save) + monkeypatch.setattr(mod, "resolve_scope", _env_scope) + + auth = mod.IntegralOAuthAuth(server_name="integral_core", account_name="integral") + payload = { + "refresh_token": "rt", + "client_id": "cid", + "access_token": "old", + "expiry": "2000-01-01T00:00:00Z", + } + await auth._refresh(_FakeNode(), payload) + assert captured["scope"] == "integral:read" + + +def _oauth_client_with_token(transport: httpx.MockTransport, mcp_url: str): + client = build_integral_oauth_client( + server_name="integral_core", + account="integral", + mcp_url=mcp_url, + connect_timeout=1.0, + read_timeout=1.0, + transport=transport, + ) + + async def _fake_token(): + return "tok" + + client._auth._valid_token = _fake_token + return client + + +def _service_key_client(transport: httpx.MockTransport, mcp_url: str): + return build_service_key_client( + service_key=_SERVICE_KEY, + user_id="u", + mcp_url=mcp_url, + connect_timeout=1.0, + read_timeout=1.0, + transport=transport, + ) + + +async def test_oauth_same_origin_trailing_slash_keeps_bearer(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("authorization"), + ) + ) + if request.url.path.rstrip("/") == "/api/mcp" and not request.url.path.endswith( + "/" + ): + return httpx.Response( + 307, headers={"location": "/api/mcp/"}, request=request + ) + return httpx.Response(200, json={"ok": True}, request=request) + + client = _oauth_client_with_token(httpx.MockTransport(handler), _TRUSTED) + try: + resp = await client.post(_TRUSTED) + assert resp.status_code == 200 + finally: + await client.aclose() + + assert len(seen) == 2 + assert seen[0][0] == "https://core.invalid/api/mcp" + assert seen[1][0] == "https://core.invalid/api/mcp/" + assert seen[0][1] == "Bearer tok" + assert seen[1][1] == "Bearer tok" + + +async def test_oauth_cross_origin_redirect_never_sends_bearer(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("authorization"), + ) + ) + if "core.invalid" in request.url.host: + return httpx.Response( + 307, + headers={"location": "https://other.invalid/api/mcp/"}, + request=request, + ) + return httpx.Response(200, json={"leaked": True}, request=request) + + client = _oauth_client_with_token(httpx.MockTransport(handler), _TRUSTED) + try: + with pytest.raises(UntrustedRedirectError): + await client.post(_TRUSTED) + finally: + await client.aclose() + + assert len(seen) == 1 + assert seen[0][0] == "https://core.invalid/api/mcp" + assert all("other.invalid" not in url for url, _ in seen) + + +async def test_oauth_https_to_http_downgrade_never_sends_bearer(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("authorization"), + request.url.scheme, + ) + ) + if request.url.scheme == "https": + return httpx.Response( + 307, + headers={"location": "http://core.invalid/api/mcp/"}, + request=request, + ) + return httpx.Response(200, json={"leaked": True}, request=request) + + client = _oauth_client_with_token(httpx.MockTransport(handler), _TRUSTED) + try: + with pytest.raises(UntrustedRedirectError): + await client.post(_TRUSTED) + finally: + await client.aclose() + + assert len(seen) == 1 + assert seen[0][2] == "https" + + +async def test_service_key_same_origin_trailing_slash_keeps_headers(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("x-integral-service-key"), + ) + ) + if request.url.path.rstrip("/") == "/api/mcp" and not request.url.path.endswith( + "/" + ): + return httpx.Response( + 307, headers={"location": "/api/mcp/"}, request=request + ) + return httpx.Response(200, json={"ok": True}, request=request) + + client = _service_key_client(httpx.MockTransport(handler), _TRUSTED) + try: + resp = await client.post(_TRUSTED) + assert resp.status_code == 200 + finally: + await client.aclose() + + assert len(seen) == 2 + assert seen[0][1] == _SERVICE_KEY + assert seen[1][1] == _SERVICE_KEY + + +async def test_service_key_cross_origin_redirect_never_sends_key(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("x-integral-service-key"), + ) + ) + if "core.invalid" in request.url.host: + return httpx.Response( + 307, + headers={"location": "https://other.invalid/api/mcp/"}, + request=request, + ) + return httpx.Response(200, json={"leaked": True}, request=request) + + client = _service_key_client(httpx.MockTransport(handler), _TRUSTED) + try: + with pytest.raises(UntrustedRedirectError): + await client.post(_TRUSTED) + finally: + await client.aclose() + + assert len(seen) == 1 + assert all("other.invalid" not in url for url, _ in seen) + + +async def test_service_key_https_to_http_downgrade_never_sends_key(): + seen = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append( + ( + str(request.url), + request.headers.get("x-integral-service-key"), + request.url.scheme, + ) + ) + if request.url.scheme == "https": + return httpx.Response( + 307, + headers={"location": "http://core.invalid/api/mcp/"}, + request=request, + ) + return httpx.Response(200, json={"leaked": True}, request=request) + + client = _service_key_client(httpx.MockTransport(handler), _TRUSTED) + try: + with pytest.raises(UntrustedRedirectError): + await client.post(_TRUSTED) + finally: + await client.aclose() + + assert len(seen) == 1 + assert seen[0][2] == "https" diff --git a/tests/action/mcp_oauth/test_integral_provider.py b/tests/action/mcp_oauth/test_integral_provider.py new file mode 100644 index 000000000..31d6a2f33 --- /dev/null +++ b/tests/action/mcp_oauth/test_integral_provider.py @@ -0,0 +1,379 @@ +"""Integral Core OAuth 2.1 provider: discovery, DCR, PKCE, exchange, refresh.""" + +import json + +import pytest + +from jvagent.action.mcp_oauth import integral_provider as ip +from jvagent.action.mcp_oauth.mcp_oauth_action import build_oauth_setup + +BASE = "https://agent.example.com" +MCP_URL = "http://127.0.0.1:9006/api/mcp/" +ORIGIN = "http://127.0.0.1:9006" +TOKEN_URL = f"{ORIGIN}/api/oauth/token" +REGISTER_URL = f"{ORIGIN}/api/oauth/register" +AUTHORIZE_URL = f"{ORIGIN}/api/oauth/authorize" + +AS_META = { + "issuer": ORIGIN, + "authorization_endpoint": AUTHORIZE_URL, + "token_endpoint": TOKEN_URL, + "registration_endpoint": REGISTER_URL, + "code_challenge_methods_supported": ["S256"], + "grant_types_supported": ["authorization_code", "refresh_token"], +} +PRM = {"resource": MCP_URL, "authorization_servers": [ORIGIN]} + + +class _Resp: + def __init__(self, status: int, payload: dict): + self.status_code = status + self._payload = payload + self.headers = {"content-type": "application/json"} + + @property + def text(self) -> str: + return json.dumps(self._payload) + + def json(self) -> dict: + return self._payload + + +def _install_fake(monkeypatch, *, get=None, post=None): + """Replace ``httpx.AsyncClient`` with a canned-response stand-in.""" + calls = {"get": [], "post": []} + + class _Fake: + def __init__(self, *a, **k): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def get(self, url, **kw): + calls["get"].append(str(url)) + return (get or {}).get(str(url), _Resp(404, {})) + + async def post(self, url, **kw): + calls["post"].append((str(url), kw)) + return (post or {}).get(str(url), _Resp(404, {})) + + monkeypatch.setattr(ip.httpx, "AsyncClient", _Fake) + return calls + + +# --------------------------------------------------------------------------- +# PKCE (RFC 7636 appendix B test vector) +# --------------------------------------------------------------------------- + + +def test_pkce_challenge_matches_rfc7636_vector(): + verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + assert ip.pkce_challenge(verifier) == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + + +def test_pkce_verifier_length_is_within_rfc_bounds(): + verifier = ip.pkce_verifier() + assert 43 <= len(verifier) <= 128 + + +# --------------------------------------------------------------------------- +# Discovery +# --------------------------------------------------------------------------- + + +async def test_discovery_prefers_protected_resource(monkeypatch): + _install_fake( + monkeypatch, + get={ + f"{ORIGIN}/.well-known/oauth-protected-resource": _Resp(200, PRM), + f"{ORIGIN}/.well-known/oauth-authorization-server": _Resp(200, AS_META), + }, + ) + meta = await ip.discover_authorization_server(mcp_url=MCP_URL) + assert meta["token_endpoint"] == TOKEN_URL + assert meta["registration_endpoint"] == REGISTER_URL + + +async def test_discovery_falls_back_when_docs_unreachable(monkeypatch): + _install_fake(monkeypatch, get={}) + meta = await ip.discover_authorization_server(mcp_url=MCP_URL) + assert meta["token_endpoint"] == TOKEN_URL + assert meta["authorization_endpoint"] == AUTHORIZE_URL + + +async def test_discovery_uses_explicit_issuer(monkeypatch): + _install_fake( + monkeypatch, + get={f"{ORIGIN}/.well-known/oauth-authorization-server": _Resp(200, AS_META)}, + ) + meta = await ip.discover_authorization_server(issuer=ORIGIN) + assert meta["token_endpoint"] == TOKEN_URL + + +# --------------------------------------------------------------------------- +# Dynamic Client Registration +# --------------------------------------------------------------------------- + + +async def test_register_client_posts_public_client(monkeypatch): + calls = _install_fake( + monkeypatch, + post={REGISTER_URL: _Resp(201, {"client_id": "dcr_client_123"})}, + ) + client_id = await ip.register_client( + AS_META, + redirect_uri=f"{BASE}/api/mcp/integral_core/auth/callback", + scope="", + ) + assert client_id == "dcr_client_123" + url, kw = calls["post"][0] + assert url == REGISTER_URL + body = kw["json"] + assert body["token_endpoint_auth_method"] == "none" + assert body["grant_types"] == ["authorization_code", "refresh_token"] + assert body["redirect_uris"] == [f"{BASE}/api/mcp/integral_core/auth/callback"] + + +async def test_register_client_raises_on_error(monkeypatch): + _install_fake(monkeypatch, post={REGISTER_URL: _Resp(400, {"error": "x"})}) + with pytest.raises(ip.IntegralOAuthServiceError): + await ip.register_client(AS_META, redirect_uri="https://x/cb") + + +# --------------------------------------------------------------------------- +# Authorize URL +# --------------------------------------------------------------------------- + + +def test_build_authorize_url_carries_pkce_s256(): + url = ip.build_authorize_url( + AS_META, + client_id="cid", + redirect_uri="https://x/cb", + state="st", + code_challenge="ch", + scope="", + ) + assert url.startswith(AUTHORIZE_URL + "?") + assert "code_challenge_method=S256" in url + assert "code_challenge=ch" in url + assert "client_id=cid" in url + + +# --------------------------------------------------------------------------- +# Token exchange + refresh +# --------------------------------------------------------------------------- + + +async def test_exchange_authorization_code(monkeypatch): + calls = _install_fake( + monkeypatch, + post={ + TOKEN_URL: _Resp( + 200, + { + "access_token": "at_1", + "refresh_token": "rt_1", + "expires_in": 3600, + "token_type": "Bearer", + }, + ) + }, + ) + tokens = await ip.exchange_authorization_code( + AS_META, + client_id="cid", + code="code", + code_verifier="verifier", + redirect_uri="https://x/cb", + ) + assert tokens["access_token"] == "at_1" + _url, kw = calls["post"][0] + assert kw["data"]["grant_type"] == "authorization_code" + assert kw["data"]["code_verifier"] == "verifier" + assert kw["data"]["client_id"] == "cid" + + +async def test_refresh_access_token(monkeypatch): + calls = _install_fake( + monkeypatch, + post={TOKEN_URL: _Resp(200, {"access_token": "at_2", "expires_in": 3600})}, + ) + tokens = await ip.refresh_access_token( + AS_META, client_id="cid", refresh_token="rt_1" + ) + assert tokens["access_token"] == "at_2" + _url, kw = calls["post"][0] + assert kw["data"]["grant_type"] == "refresh_token" + assert kw["data"]["refresh_token"] == "rt_1" + + +# --------------------------------------------------------------------------- +# Stored payload helpers +# --------------------------------------------------------------------------- + + +def test_normalize_token_payload_keeps_previous_refresh(): + payload = ip.normalize_token_payload( + {"access_token": "at", "expires_in": 3600}, + client_id="cid", + token_uri=TOKEN_URL, + account_name="integral", + previous={"refresh_token": "rt_old"}, + ) + assert payload["refresh_token"] == "rt_old" + assert payload["access_token"] == "at" + assert payload["type"] == "oauth2" + + +def test_payload_is_expired(): + assert ip.payload_is_expired(None) is True + assert ip.payload_is_expired({"access_token": "x"}) is False + assert ( + ip.payload_is_expired({"access_token": "x", "expiry": "2000-01-01T00:00:00Z"}) + is True + ) + + +# --------------------------------------------------------------------------- +# URL helpers + oauth_setup exposure +# --------------------------------------------------------------------------- + + +def test_mcp_integral_core_auth_url(): + url = ip.mcp_integral_core_auth_url(account="integral", base_url=BASE) + assert url == f"{BASE}/api/mcp/integral_core/auth?account=integral" + + +def test_build_oauth_setup_includes_integral(): + setup = build_oauth_setup(BASE, [{"name": "integral_core"}]) + assert len(setup) == 1 + entry = setup[0] + assert entry["server"] == "integral_core" + assert entry["service"] == "integral" + assert entry["label"] == "Integral" + assert entry["redirect_uri"] == f"{BASE}/api/mcp/integral_core/auth/callback" + assert entry["auth_url"] == ( + f"{BASE}/api/mcp/integral_core/auth?account=integral&service=integral" + ) + + +def test_build_oauth_setup_absent_when_not_configured(): + setup = build_oauth_setup(BASE, [{"name": "google_workspace"}]) + assert all(item["server"] != "integral_core" for item in setup) + + +# --------------------------------------------------------------------------- +# Scope passthrough (verbatim — authored on the server entry) +# --------------------------------------------------------------------------- + + +def test_join_scopes_verbatim_from_list(): + assert ip.join_scopes(["integral:read", "integral:execute"]) == ( + "integral:read integral:execute" + ) + + +def test_join_scopes_passes_through_unknown_tokens(): + # No aliasing/filtering: whatever is authored is forwarded (Core validates). + assert ip.join_scopes(["entry.create", "integral:admin"]) == ( + "entry.create integral:admin" + ) + assert ip.join_scopes(["integral:write"]) == "integral:write" + + +def test_join_scopes_accepts_string_and_splits_commas_or_spaces(): + assert ip.join_scopes("integral:read, integral:execute") == ( + "integral:read integral:execute" + ) + assert ip.join_scopes(" integral:propose integral:read ") == ( + "integral:propose integral:read" + ) + + +def test_join_scopes_empty(): + assert ip.join_scopes(None) == "" + assert ip.join_scopes([]) == "" + assert ip.join_scopes([" ", ""]) == "" + + +def test_resolve_scopes_from_auth_precedence(monkeypatch): + monkeypatch.setenv("INTEGRAL_OAUTH_SCOPE", "integral:propose") + # auth.scopes (list) wins, verbatim + assert ( + ip.resolve_scopes_from_auth({"scopes": ["integral:read", "integral:execute"]}) + == "integral:read integral:execute" + ) + # auth.scope (string) verbatim + assert ip.resolve_scopes_from_auth({"scope": "integral:read"}) == "integral:read" + # env fallback when the auth block has neither + assert ip.resolve_scopes_from_auth({}) == "integral:propose" + # scopes wins over scope + assert ( + ip.resolve_scopes_from_auth( + {"scopes": ["entry.create"], "scope": "integral:propose"} + ) + == "entry.create" + ) + + +async def test_resolve_token_identity_reads_core_account_email(monkeypatch): + """The panel label comes from Core, not the storage key ``integral``.""" + seen = {} + + class _Client: + def __init__(self, *args, **kwargs): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url, headers=None): + seen["url"] = url + seen["auth"] = (headers or {}).get("Authorization") + return _Resp( + 200, + { + "user": { + "email": "admin@integral.com", + "display_name": "Admin", + "active_workspace_id": "n.Workspace.1", + } + }, + ) + + monkeypatch.setattr(ip.httpx, "AsyncClient", _Client) + identity = await ip.resolve_token_identity(MCP_URL, "tok", AS_META) + + assert identity == {"email": "admin@integral.com"} + assert seen["url"] == f"{ORIGIN}/api/auth/me" + assert seen["auth"] == "Bearer tok" + + +async def test_resolve_token_identity_without_token_is_empty(): + assert await ip.resolve_token_identity(MCP_URL, "") == {} + + +async def test_resolve_token_identity_falls_back_on_error(monkeypatch): + class _Boom: + def __init__(self, *args, **kwargs): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url, headers=None): + raise RuntimeError("core unreachable") + + monkeypatch.setattr(ip.httpx, "AsyncClient", _Boom) + assert await ip.resolve_token_identity(MCP_URL, "tok", AS_META) == {} diff --git a/tests/action/mcp_oauth/test_mcp_oauth_action.py b/tests/action/mcp_oauth/test_mcp_oauth_action.py index eec60ac29..fd25bf5f7 100644 --- a/tests/action/mcp_oauth/test_mcp_oauth_action.py +++ b/tests/action/mcp_oauth/test_mcp_oauth_action.py @@ -30,10 +30,10 @@ def test_sheets_and_drive_tools_build_two_dicts(): callback = f"{BASE}/api/mcp/google_workspace/auth/callback" assert {item["redirect_uri"] for item in setup} == {callback} assert setup[0]["auth_url"] == ( - f"{BASE}/api/mcp/google_workspace/auth?account=default&service=sheets" + f"{BASE}/api/mcp/google_workspace/auth?account=integral&service=sheets" ) assert setup[1]["auth_url"] == ( - f"{BASE}/api/mcp/google_workspace/auth?account=default&service=drive" + f"{BASE}/api/mcp/google_workspace/auth?account=integral&service=drive" ) assert all(item["server"] == "google_workspace" for item in setup) @@ -75,7 +75,7 @@ def test_unconfigured_google_workspace_is_generic_entry(): assert setup[0]["server"] == "google_workspace" assert "service" not in setup[0] assert setup[0]["auth_url"] == ( - f"{BASE}/api/mcp/google_workspace/auth?account=default" + f"{BASE}/api/mcp/google_workspace/auth?account=integral" ) @@ -125,7 +125,7 @@ def test_sheets_scopes_do_not_bind_drive(): "google_workspace", [ { - "account_name": "default", + "account_name": "integral", "token": {"email": "ops@example.com", "scopes": SHEETS_SCOPES}, } ], @@ -141,7 +141,7 @@ def test_drive_scope_binds_drive_and_email_from_payload(): "google_workspace", [ { - "account_name": "default", + "account_name": "integral", "token": {"email": "ops@example.com", "scopes": scopes}, } ], @@ -186,15 +186,15 @@ def test_microsoft_files_scope_binds_onedrive_and_excel(): def test_mcp_oauth_state_action_id_roundtrip(): - assert mcp_oauth_state_action_id("default", "sheets") == ( - "mcp_oauth:default:sheets" + assert mcp_oauth_state_action_id("integral", "sheets") == ( + "mcp_oauth:integral:sheets" ) - assert parse_mcp_oauth_state_action_id("mcp_oauth:default:sheets") == ( - "default", + assert parse_mcp_oauth_state_action_id("mcp_oauth:integral:sheets") == ( + "integral", "sheets", ) - assert parse_mcp_oauth_state_action_id("mcp_oauth:default") == ("default", "") - assert parse_mcp_oauth_state_action_id("") == ("default", "") + assert parse_mcp_oauth_state_action_id("mcp_oauth:integral") == ("integral", "") + assert parse_mcp_oauth_state_action_id("") == ("integral", "") def test_empty_mcp_services_does_not_reclaim_sheets_from_scopes(): @@ -424,7 +424,7 @@ def test_gmail_does_not_use_sheets_only_token(): } ] account, token, _node = token_row_for_service( - rows, "google_workspace", "gmail", "default" + rows, "google_workspace", "gmail", "integral" ) assert account is None assert token is None @@ -446,7 +446,7 @@ def test_poisoned_merged_token_is_not_used_for_gmail(): } ] account, token, _node = token_row_for_service( - rows, "google_workspace", "gmail", "default" + rows, "google_workspace", "gmail", "integral" ) assert account is None assert token is None @@ -474,13 +474,13 @@ def test_token_row_returns_service_blob_not_sibling(): } rows = [{"account_name": "a@example.com", "token": parent, "node": None}] account, sheets, _node = token_row_for_service( - rows, "google_workspace", "sheets", "default" + rows, "google_workspace", "sheets", "integral" ) assert account == "a@example.com" assert sheets["refresh_token"] == "rt-sheets" assert sheets["client_id"] == "cid" assert "https://www.googleapis.com/auth/spreadsheets" in sheets["scopes"] - _, gmail, _ = token_row_for_service(rows, "google_workspace", "gmail", "default") + _, gmail, _ = token_row_for_service(rows, "google_workspace", "gmail", "integral") assert gmail["refresh_token"] == "rt-gmail" assert gmail["scopes"] == ["https://www.googleapis.com/auth/gmail.send"] @@ -517,3 +517,60 @@ def test_same_email_microsoft_keeps_outlook_and_onedrive_tokens(): assert tok["service_tokens"]["onedrive"]["refresh_token"] == "rt-files" assert "Files.ReadWrite.All" not in tok["service_tokens"]["outlook"]["scopes"] assert "Mail.Send" not in tok["service_tokens"]["onedrive"]["scopes"] + + +async def test_integral_exchange_stores_resolved_identity(monkeypatch): + from types import SimpleNamespace + + from jvagent.action.mcp_oauth import endpoints as ep + + async def fake_mcp_url(): + return "https://core.example.com/api/mcp/integral_core" + + async def fake_discover(**kwargs): + return { + "issuer": "https://core.example.com", + "token_endpoint": "https://core.example.com/api/oauth/token", + } + + async def fake_client(server): + return SimpleNamespace(client_id="cid") + + async def fake_exchange(meta, **kwargs): + return {"access_token": "tok", "expires_in": 3600} + + async def fake_identity(mcp_url, access_token, meta=None): + assert access_token == "tok" + return {"email": "admin@integral.com"} + + async def fake_auth_cfg(): + return {} + + def fake_scopes(cfg): + return "" + + saved = {} + + class FakeAction: + async def save_oauth_token(self, server, account, payload): + saved.update(server=server, account=account, payload=payload) + + monkeypatch.setattr(ep, "_integral_mcp_url", fake_mcp_url) + monkeypatch.setattr(ep, "discover_authorization_server", fake_discover) + monkeypatch.setattr(ep, "load_registered_client", fake_client) + monkeypatch.setattr(ep, "exchange_authorization_code", fake_exchange) + monkeypatch.setattr(ep, "resolve_token_identity", fake_identity) + monkeypatch.setattr(ep, "_integral_auth_cfg", fake_auth_cfg) + monkeypatch.setattr(ep, "resolve_scopes_from_auth", fake_scopes) + + record = SimpleNamespace(code_verifier="v", redirect_uri="https://a/cb") + account, label = await ep._exchange_integral_code( + FakeAction(), "code", record, "integral" + ) + + assert saved["server"] == "integral_core" + assert saved["account"] == "integral" + assert saved["payload"]["email"] == "admin@integral.com" + assert "display_name" not in saved["payload"] + assert account == "admin@integral.com" + assert label == "Integral" diff --git a/tests/action/orchestrator/test_grounding_guard.py b/tests/action/orchestrator/test_grounding_guard.py index f986f44a0..63b54488b 100644 --- a/tests/action/orchestrator/test_grounding_guard.py +++ b/tests/action/orchestrator/test_grounding_guard.py @@ -61,6 +61,40 @@ def _orchestrator(): return OrchestratorInteractAction() +def test_handoff_in_observations_only_on_first_complete(): + """Already-stated must not arm the sales-sentence guard.""" + ex = _orchestrator() + assert ex._handoff_in_observations( + [{"observation": '{"directive": "Hand-off is complete."}'}] + ) + assert not ex._handoff_in_observations( + [ + { + "observation": ( + "Do not repeat the hand-off sentence. Briefly acknowledge " + "the detail just captured." + ) + } + ] + ) + assert not ex._handoff_in_observations([]) + assert not ex._handoff_in_observations( + [{"observation": '{"directive": "Hand-off already stated."}'}] + ) + + +def test_already_stated_capture_disarms_an_earlier_complete_observation(): + """A sync observation earlier in the turn must not re-arm the guard.""" + ex = _orchestrator() + observations = [ + {"observation": '{"directive": "Hand-off is complete."}'}, + {"observation": '{"directive": "Hand-off already stated."}'}, + ] + assert not ex._handoff_in_observations(observations) + # The first-hand-off turn (no already-stated marker) still arms it. + assert ex._handoff_in_observations(observations[:1]) + + def test_guard_fires_only_when_no_substantive_tool_ran(): ex = _orchestrator() claim = "Yes, that was retrieved from the knowledge base." diff --git a/tests/action/orchestrator/test_history_events.py b/tests/action/orchestrator/test_history_events.py index 67337296d..01eec4138 100644 --- a/tests/action/orchestrator/test_history_events.py +++ b/tests/action/orchestrator/test_history_events.py @@ -18,23 +18,29 @@ async def test_history_omits_events_by_default_and_honors_with_event_knob( ex = OrchestratorInteractAction() ex.history_limit = 20 assert ex.with_event is False + assert ex.hide_correlation is True visitor = make_visitor() await ex._history(visitor) visitor.conversation.get_interaction_history.assert_awaited_once() - assert ( - visitor.conversation.get_interaction_history.call_args.kwargs["with_event"] - is False - ) + kwargs = visitor.conversation.get_interaction_history.call_args.kwargs + assert kwargs["with_event"] is False + assert kwargs["hide_correlation"] is True ex.with_event = True visitor = make_visitor() await ex._history(visitor) - assert ( - visitor.conversation.get_interaction_history.call_args.kwargs["with_event"] - is True - ) + kwargs = visitor.conversation.get_interaction_history.call_args.kwargs + assert kwargs["with_event"] is True + assert kwargs["hide_correlation"] is True + + ex.hide_correlation = False + visitor = make_visitor() + await ex._history(visitor) + kwargs = visitor.conversation.get_interaction_history.call_args.kwargs + assert kwargs["with_event"] is True + assert kwargs["hide_correlation"] is False @pytest.mark.asyncio @@ -103,6 +109,26 @@ async def test_with_event_honours_channel_override(make_visitor): assert kwargs["with_event"] is False +@pytest.mark.asyncio +async def test_hide_correlation_honours_channel_override(make_visitor): + ex = OrchestratorInteractAction() + ex.with_event = True + ex.hide_correlation = True + ex.channel_overrides = {"whatsapp": {"hide_correlation": False}} + + visitor = make_visitor() + visitor.channel = "whatsapp" + await ex._history(visitor) + kwargs = visitor.conversation.get_interaction_history.call_args.kwargs + assert kwargs["hide_correlation"] is False + + visitor = make_visitor() + visitor.channel = "web" + await ex._history(visitor) + kwargs = visitor.conversation.get_interaction_history.call_args.kwargs + assert kwargs["hide_correlation"] is True + + @pytest.mark.asyncio async def test_event_lines_carry_the_same_per_statement_cap(make_visitor): """An [EVENT] line is free-form text with no length contract of its own, and diff --git a/tests/action/orchestrator/test_turn_boundary.py b/tests/action/orchestrator/test_turn_boundary.py index c889c7fcb..c5c6b9ae1 100644 --- a/tests/action/orchestrator/test_turn_boundary.py +++ b/tests/action/orchestrator/test_turn_boundary.py @@ -36,6 +36,7 @@ "_run_loop", "_tick", "_tick_final", + "_finish_empty_final", "_tick_tool", "_guarded_siblings", "_dispatch_batch", diff --git a/tests/action/pageindex/test_lexical_index.py b/tests/action/pageindex/test_lexical_index.py index c362022bc..8b48c4495 100644 --- a/tests/action/pageindex/test_lexical_index.py +++ b/tests/action/pageindex/test_lexical_index.py @@ -190,6 +190,43 @@ async def test_search_empty_index(pageindex_temp_db): assert results == [] +@pytest.mark.asyncio +async def test_search_unknown_concept_returns_nothing(pageindex_temp_db): + """Half the distinctive terms unknown means the corpus cannot answer it.""" + await index_node("n1", "doc_a", "cov_col", title="Delivery coverage") + await index_node("n2", "doc_a", "cov_col", title="Delivery times") + + assert await search("helicopter delivery policy", "cov_col") == [] + + +@pytest.mark.asyncio +async def test_search_keeps_hits_when_unknown_terms_are_a_minority( + pageindex_temp_db, +): + """One stray word must not empty a query the corpus can answer.""" + await index_node( + "n1", + "doc_a", + "known_col", + title="Payment terms", + text="We accept bank transfer, cash, cheques and payment methods.", + ) + + results = await search( + "payment terms methods bank transfer cash cheques balance due", + "known_col", + ) + + assert results + + +@pytest.mark.asyncio +async def test_search_single_unknown_term_returns_nothing(pageindex_temp_db): + await index_node("n1", "doc_a", "single_col", title="Delivery coverage") + + assert await search("brochure", "single_col") == [] + + @pytest.mark.asyncio async def test_search_filters_by_doc_name(pageindex_temp_db): await index_node("n1", "doc_a", "col", title="Finance report") diff --git a/tests/action/reply/test_reply_action.py b/tests/action/reply/test_reply_action.py index a61ce3fe9..63a538dfb 100644 --- a/tests/action/reply/test_reply_action.py +++ b/tests/action/reply/test_reply_action.py @@ -482,6 +482,25 @@ async def _ma(self, required=False): assert "invitation closers" in text # native response core present +def test_custom_reply_parameters_still_surface_core_in_compose(): + """Replacing ReplyAction.parameters (as agent.yaml does) must not drop the + framework RESPONSE RULES from compose — same union as _reply_pool.""" + ra = ReplyAction() + ra.parameters = [ + { + "scope": "response", + "response": "Custom agent voice: keep replies short.", + } + ] + text = ra._compose_parameters_text(None, None) + assert "Custom agent voice: keep replies short." in text + # Core hand-off + identity hardening still present despite YAML replacement + assert "sales team" in text + assert "hand-off is complete" in text + assert "invitation closers" in text + assert "knowledge or training cutoff" in text + + async def test_publish_scrubs_composed_leak(monkeypatch): """A model-composed reply that appends a self-identity leak is scrubbed at the egress choke point before it reaches the user.""" diff --git a/tests/action/tts_action/test_elevenlabs_media_url.py b/tests/action/tts_action/test_elevenlabs_media_url.py new file mode 100644 index 000000000..106bb5777 --- /dev/null +++ b/tests/action/tts_action/test_elevenlabs_media_url.py @@ -0,0 +1,80 @@ +"""Tests for ElevenLabs TTS media URL generation.""" + +import logging +from unittest.mock import AsyncMock, patch + +import pytest + +from jvagent.action.tts_action.elevenlabs.elevenlabs import ElevenLabsTTSAction + + +@pytest.mark.asyncio +async def test_get_audio_as_url_uses_signed_proxy_url(): + action = ElevenLabsTTSAction() + with ( + patch.object( + ElevenLabsTTSAction, "save_file", new=AsyncMock(return_value=True) + ) as save, + patch.object( + ElevenLabsTTSAction, + "get_short_file_url", + new=AsyncMock(return_value="/p/abc123"), + ) as proxy_url, + patch.object( + ElevenLabsTTSAction, "get_file_url", new=AsyncMock() + ) as direct_url, + ): + result = await action.get_audio_as(b"audio-bytes", as_url=True) + + assert result == "/p/abc123" + save.assert_awaited_once() + storage_path, content = save.await_args.args + assert storage_path.startswith("tts_audio/tts_audio_") + assert storage_path.endswith(".mp3") + assert content == b"audio-bytes" + proxy_url.assert_awaited_once_with(storage_path, expires_in=3600) + direct_url.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_get_audio_as_url_warns_when_proxy_url_disabled(caplog): + action = ElevenLabsTTSAction() + direct = "/api/files/actions/agent/elevenlabs_tts/tts_audio/voice.mp3" + with ( + patch.object( + ElevenLabsTTSAction, "save_file", new=AsyncMock(return_value=True) + ), + patch.object( + ElevenLabsTTSAction, + "get_short_file_url", + new=AsyncMock(return_value=direct), + ), + ): + with caplog.at_level( + logging.WARNING, + logger="jvagent.action.tts_action.elevenlabs.elevenlabs", + ): + result = await action.get_audio_as(b"audio-bytes", as_url=True) + + assert result == direct + assert "JVSPATIAL_PROXY_ENABLED=true" in caplog.text + + +@pytest.mark.asyncio +async def test_get_audio_as_base64_does_not_touch_url_helpers(): + action = ElevenLabsTTSAction() + with ( + patch.object(ElevenLabsTTSAction, "save_file", new=AsyncMock()) as save, + patch.object( + ElevenLabsTTSAction, "get_short_file_url", new=AsyncMock() + ) as proxy_url, + patch.object( + ElevenLabsTTSAction, "get_file_url", new=AsyncMock() + ) as direct_url, + ): + result = await action.get_audio_as(b"audio-bytes", as_base64=True) + + assert result == "YXVkaW8tYnl0ZXM=" + save.assert_not_awaited() + proxy_url.assert_not_awaited() + direct_url.assert_not_awaited() diff --git a/tests/memory/test_history_harness_event.py b/tests/memory/test_history_harness_event.py new file mode 100644 index 000000000..1f5197096 --- /dev/null +++ b/tests/memory/test_history_harness_event.py @@ -0,0 +1,103 @@ +"""``hide_correlation``: omit harness correlation from [EVENT] history.""" + +from __future__ import annotations + +import uuid + +import pytest + +from jvagent.memory.conversation import Conversation + +PRODUCT = "Report form was sent to the user." +HARNESS = "internal turn correlation (not a request_id): corr-abc123" + + +def _session() -> str: + return f"test-sess-{uuid.uuid4().hex[:12]}" + + +async def _conv_with_mixed_events() -> Conversation: + conv = await Conversation.create( + session_id=_session(), user_id="user1", channel="default" + ) + interaction = await conv.add_interaction(utterance="hello") + interaction.response = "Hi." + interaction.events.extend( + [ + {"action_name": "harness", "content": HARNESS}, + {"action_name": "ReportAction", "content": PRODUCT}, + ] + ) + await interaction.save() + return conv + + +@pytest.mark.asyncio +async def test_with_event_omits_harness_by_default(test_db): + conv = await _conv_with_mixed_events() + try: + hist = await conv.get_interaction_history( + limit=10, formatted=True, with_event=True + ) + events = [e["content"] for e in hist if e["content"].startswith("[EVENT]")] + assert events == [f"[EVENT] {PRODUCT}"] + finally: + await conv.delete(cascade=True) + + +@pytest.mark.asyncio +async def test_hide_correlation_false_keeps_correlation(test_db): + conv = await _conv_with_mixed_events() + try: + hist = await conv.get_interaction_history( + limit=10, + formatted=True, + with_event=True, + hide_correlation=False, + ) + events = [e["content"] for e in hist if e["content"].startswith("[EVENT]")] + assert events == [f"[EVENT] {HARNESS}", f"[EVENT] {PRODUCT}"] + finally: + await conv.delete(cascade=True) + + +@pytest.mark.asyncio +async def test_with_event_false_emits_no_events_even_when_correlation_shown( + test_db, +): + conv = await _conv_with_mixed_events() + try: + hist = await conv.get_interaction_history( + limit=10, + formatted=True, + with_event=False, + hide_correlation=False, + ) + assert not any(e["content"].startswith("[EVENT]") for e in hist) + finally: + await conv.delete(cascade=True) + + +@pytest.mark.asyncio +async def test_raw_history_also_filters_harness(test_db): + conv = await _conv_with_mixed_events() + try: + raw = await conv.get_interaction_history( + limit=10, formatted=False, with_event=True + ) + entry = next(e for e in raw if e.get("events")) + assert [ev["action_name"] for ev in entry["events"]] == ["ReportAction"] + + raw_keep = await conv.get_interaction_history( + limit=10, + formatted=False, + with_event=True, + hide_correlation=False, + ) + entry = next(e for e in raw_keep if e.get("events")) + assert [ev["action_name"] for ev in entry["events"]] == [ + "harness", + "ReportAction", + ] + finally: + await conv.delete(cascade=True)