Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
112 changes: 92 additions & 20 deletions jvagent/action/google/google_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions jvagent/action/handoff_action/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <app> --agent <persisted-agent-id> --channel web \
--run "<request>|<contact>|<second request>|<repeat>|<new intent>|thanks"
python3 "$HOME/.config/kilo/skills/jv_prompt/scripts/db_read.py" \
python3 "$HOME/.config/kilo/skills/jv-prompt/scripts/db_read.py" \
--db <app> --entity HandoffQuestion --limit 5
```

Expand Down
44 changes: 30 additions & 14 deletions jvagent/action/intro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,37 +26,46 @@ 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`) |

## Flow

```
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)
Expand Down
Loading