Skip to content

The agent that grows with you

feat(connectors): the backend API for the desktop Connectors page; connect an app without a chat session (#115191)

Siddharth Balyan70f5dc5f46d6
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 90d7cc6fc04..cd8700f147b 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1080,6 +1080,10 @@ def _load_tools(agent, enabled_toolsets, disabled_toolsets):
# A finite -q run has no later session to learn for: no skill authoring tool (agent/oneshot_footprint.py).
from agent.oneshot_footprint import prune_oneshot_tools
agent.tools = prune_oneshot_tools(agent.tools or [])
+ from tools.connectors.turn import side_agent_tool_drops
+ drops = side_agent_tool_drops(agent)
+ if drops:
+ agent.tools = [t for t in agent.tools if t["function"]["name"] not in drops]
agent.valid_tool_names = {tool["function"]["name"] for tool in agent.tools} if agent.tools else set()
# Kanban guidance is session-static for the dispatcher-owned worker only. Profiles may
@@ -2286,6 +2290,7 @@ _PASSTHROUGH_PARAMS = (
"enabled_toolsets", "disabled_toolsets",
# Model response configuration (None = provider/model default)
"max_tokens", "reasoning_config", "service_tier",
+ "side_agent",
)
# Gateway identity params stored as ``agent._<name>``. gateway_session_key is the stable
# per-chat key (e.g. agent:main:telegram:dm:123).
@@ -2339,22 +2344,8 @@ def init_agent(
checkpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,
checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,
requested_provider: str = None, capabilities: Optional[Dict[str, bool]] = None, cwd: Optional[str] = None,
+ side_agent: bool = False,
):
- """Initialize the AI Agent (body of :meth:`AIAgent.__init__`).
-
- Non-obvious parameters:
- max_iterations: default unlimited (sys.maxsize); the budget is shared with subagents.
- requested_provider: provider identity before runtime canonicalization.
- cwd: logical session workspace, available to memory providers during construction;
- None or empty leaves the runtime cwd resolver unpinned.
- openrouter_min_coding_score: coding-score floor for ``openrouter/pareto-code`` only.
- clarify_callback: ``(question, choices) -> str``; None → the clarify tool errors.
- reasoning_config: None → ``{"enabled": True, "effort": "medium"}`` on OpenRouter.
- prefill_messages: priming history. Anthropic Sonnet/Opus 4.6+ 400 on a trailing
- assistant message — use structured outputs there instead.
- skip_context_files: skip SOUL.md/.hermes.md/AGENTS.md/CLAUDE.md/.cursorrules injection;
- load_soul_identity keeps ~/.hermes/SOUL.md as identity regardless.
- """
_install_safe_stdio()
_params = locals()
diff --git a/agent/display.py b/agent/display.py
index 16d087f411f..4eace0251d0 100644
--- a/agent/display.py
+++ b/agent/display.py
@@ -9,7 +9,7 @@ import re
import sys
import threading
import time
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from difflib import unified_diff
from pathlib import Path
from typing import Any, Iterator
@@ -436,6 +436,16 @@ def _preview_skill_view(args: dict, max_len: int) -> str | None:
return _tail_trunc(label, max_len) or None
+def _preview_bridge_call(tool_name: str):
+ def _build(args: dict, max_len: int) -> str | None:
+ labels = bridge_tool_labels(tool_name, args)
+ if not labels:
+ return _primary_arg_preview(tool_name, args, max_len)
+ extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
+ return _tail_trunc(f"{labels[0].text}{extra}", max_len) or None
+ return _build
+
+
# Tool-specific preview builders: f(args, max_len) -> preview. Tools not listed
# fall through to the primary-argument lookup in build_tool_preview.
_PREVIEW_BUILDERS = {
@@ -445,6 +455,9 @@ _PREVIEW_BUILDERS = {
"read_file": _preview_read_file, "memory": _preview_memory, "send_message": _preview_send_message,
"skill_view": _preview_skill_view,
"session_search": lambda args, _m: f"recall: \"{_clip(_oneline(args.get('query', '')), 25)}\"",
+ "tool_call": _preview_bridge_call("tool_call"),
+ "tool_search": _preview_bridge_call("tool_search"),
+ "tool_describe": _preview_bridge_call("tool_describe"),
}
@@ -461,6 +474,10 @@ def build_tool_preview(tool_name: str, args: dict, max_len: int | None = None) -
builder = _PREVIEW_BUILDERS.get(tool_name)
if builder is not None:
return builder(args, max_len)
+ return _primary_arg_preview(tool_name, args, max_len)
+
+
+def _primary_arg_preview(tool_name: str, args: dict, max_len: int) -> str | None:
key = _PRIMARY_ARGS.get(tool_name) or next((k for k in _FALLBACK_PREVIEW_KEYS if k in args), None)
if not key or key not in args:
return None
@@ -500,6 +517,37 @@ _TOOL_VERBS_NO_PREVIEW: frozenset[str] = frozenset({"skills_list", "session_sear
# Verbs joined to the preview with " for " (search-style phrasing).
_TOOL_VERBS_FOR_CONNECTOR: frozenset[str] = frozenset({"web_search", "search_files"})
+_BRIDGE_GENERATING = {
+ "tool_call": "a tool call", "tool_search": "a tool search", "tool_describe": "tool details",
+}
+
+
+def bridge_generating_phrase(tool_name: str) -> str | None:
+ return _BRIDGE_GENERATING.get(tool_name) if _friendly_tool_labels else None
+
+
+def tool_labels_for_call(tool_name: str, args: dict | None) -> list:
+ try:
+ from tools.tool_labels import labels_for_call
+ labels = labels_for_call(tool_name, args or {})
+ except Exception as exc: # noqa: BLE001 — display must never abort a turn
+ logger.debug("bridge labels failed for %s: %s", tool_name, exc)
+ return []
+ skin = _get_skin()
+ overrides = (skin.tool_emojis if skin and skin.tool_emojis else None) or {}
+ return [replace(label, emoji=overrides[label.name]) if label.name in overrides else label
+ for label in labels]
+
+
+def bridge_tool_labels(tool_name: str, args: dict | None) -> list:
+ return tool_labels_for_call(tool_name, args) if _friendly_tool_labels else []
+
+
+def tool_row_emoji(tool_name: str, args: dict | None = None, default: str = "⚡") -> str:
+ labels = bridge_tool_labels(tool_name, args) if args else []
+ return labels[0].emoji if labels else get_tool_emoji(tool_name, default)
+
+
def get_tool_verb(tool_name: str) -> str | None:
"""Friendly verb for a built-in tool, or None (labels disabled / no curated verb);
callers compose ``f"{verb}{tool_verb_connector(tool)}{preview}"`` themselves."""
@@ -535,8 +583,12 @@ def build_status_phrase(tool_name: str, args: dict | None, max_len: int = 49) ->
def build_tool_label(tool_name: str, args: dict, max_len: int | None = None) -> str | None:
- """Human-phrased label ("Searching the web for ...") for curated built-ins; other
- tools (or labels disabled) get the raw preview, so it is a drop-in for build_tool_preview."""
+ labels = bridge_tool_labels(tool_name, args)
+ if labels:
+ label = labels[0]
+ preview = _tail_trunc(label.preview, max_len if max_len is not None else _tool_preview_max_len)
+ extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
+ return f"{label.text}{f' {preview}' if preview else ''}{extra}"
verb = get_tool_verb(tool_name)
if verb and tool_name in _TOOL_VERBS_NO_PREVIEW:
return verb
@@ -1085,15 +1137,59 @@ _CUTE_LINES = {
}
+def _cute_bridge_rows(tool_name: str, args: dict) -> list[str] | None:
+ labels = bridge_tool_labels(tool_name, args)
+ if not labels:
+ return None
+ return [f"┊ {label.emoji} {_cute_trunc(label.text)}"
+ f"{f' {_cute_trunc(label.preview)}' if label.preview else ''}" for label in labels]
+
+
+_BRIDGE_CALL_INDEX_RE = re.compile(r"calls\[(\d+)\]")
+
+
+def _entry_failure_suffix(entry: Any) -> str:
+ if not isinstance(entry, dict):
+ return ""
+ error = entry.get("error")
+ if isinstance(error, dict):
+ return f" [{_trim_error(str(error.get('message') or error.get('code') or 'error'))}]"
+ if not (error or entry.get("success") is False):
+ return ""
+ return _detect_tool_failure(str(entry.get("name") or ""), entry)[1]
+
+
+def _bridge_row_suffixes(rows: int, result: Any, call_suffix: str) -> list[str]:
+ suffixes = [""] * rows
+ data = result if isinstance(result, dict) else safe_json_loads(result)
+ entries = data.get("results") if isinstance(data, dict) else None
+ if isinstance(entries, list):
+ for position, entry in enumerate(entries[:rows]):
+ suffix = _entry_failure_suffix(entry)
+ if not suffix:
+ continue
+ index = entry.get("index")
+ suffixes[index if isinstance(index, int) and 0 <= index < rows else position] = suffix
+ if call_suffix and not any(suffixes):
+ match = _BRIDGE_CALL_INDEX_RE.search(call_suffix)
+ named = int(match.group(1)) if match else rows - 1
+ suffixes[named if 0 <= named < rows else rows - 1] = call_suffix
+ return suffixes
+
+
def _get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
- """Tool completion line for CLI quiet mode: ``| {emoji} {verb:9} {detail} {duration}``, plus a
- failure suffix from :func:`_detect_tool_failure`; the leading ``┊`` becomes the skin's tool prefix."""
args = redact_tool_args_for_display(tool_name, args) or args
is_failure, failure_suffix = _detect_tool_failure(tool_name, result)
render = _CUTE_LINES.get(tool_name)
- body = render(args, result) if render else f"┊ ⚡ {tool_name[:9]:9} {_cute_trunc(build_tool_preview(tool_name, args) or '')}"
- line = f"{body} {duration:.1f}s".replace("┊", get_skin_tool_prefix(), 1)
- return f"{line}{failure_suffix}" if is_failure else line
+ rows = _cute_bridge_rows(tool_name, args)
+ if rows is None:
+ body = render(args, result) if render else f"┊ ⚡ {tool_name[:9]:9} {_cute_trunc(build_tool_preview(tool_name, args) or '')}"
+ rows, suffixes = [body], [failure_suffix if is_failure else ""]
+ else:
+ suffixes = _bridge_row_suffixes(len(rows), result, failure_suffix if is_failure else "")
+ rows = [*rows[:-1], f"{rows[-1]} {duration:.1f}s"]
+ prefix = get_skin_tool_prefix()
+ return "\n ".join(f"{row}{suffix}".replace("┊", prefix, 1) for row, suffix in zip(rows, suffixes))
def get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index 26779b01071..b877a637a43 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -26,6 +26,7 @@ from agent.display import (
build_tool_label as _build_tool_label,
get_cute_tool_message as _get_cute_tool_message_impl,
get_tool_emoji as _get_tool_emoji,
+ tool_row_emoji as _tool_row_emoji,
redact_tool_args_for_display as _redact_tool_args_for_display,
_detect_tool_failure,
)
@@ -1556,7 +1557,7 @@ def _start_quiet_tool_spinner(agent, function_name: str, function_args: dict, *,
face = random.choice(KawaiiSpinner.get_waiting_faces())
if label is None:
display_args = _redact_tool_args_for_display(function_name, function_args) or function_args
- label = f"{_get_tool_emoji(function_name)} {_build_tool_label(function_name, display_args) or function_name}"
+ label = f"{_tool_row_emoji(function_name, display_args)} {_build_tool_label(function_name, display_args) or function_name}"
spinner = KawaiiSpinner(f"{face} {label}", spinner_type='dots', print_fn=agent._print_fn)
spinner.start()
return spinner
diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx
index 2ef1f67ec71..16f55b31dee 100644
--- a/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx
@@ -12,7 +12,7 @@ import {
type ConnectionTarget,
setConnectionRequest
} from '@/store/connection-request'
-import { $gateway, setPrimaryGateway } from '@/store/gateway'
+import { $gateway, setPrimaryGateway, setPrimaryGatewayConnectionId } from '@/store/gateway'
import { $notifications } from '@/store/notifications'
import { _resetSessionOwnerHintsForTests, setSessionOwnerHint } from '@/store/session'
@@ -85,6 +85,8 @@ function view(sessionId: string): SessionView {
}
function renderOffer(request = REQUEST) {
+ setConnectionRequest(request)
+
return render(
<I18nProvider configClient={null} initialLocale="en">
<ConnectorOffer owner={PRIMARY_OWNER} request={request} />
@@ -186,7 +188,7 @@ describe('ConnectorTool operation card', () => {
expect(openExternal).not.toHaveBeenCalled()
expect(request).toHaveBeenCalledWith(
'connectors.connect',
- { connectors: ['gmail'], reconnect: true, session_id: SESSION_ID },
+ { connectors: ['gmail'], owner: { session_id: SESSION_ID, type: 'session' }, reconnect: true },
expect.any(Number),
undefined
)
@@ -211,8 +213,9 @@ describe('ConnectorTool operation card', () => {
it('Continue settles the whole operation', async () => {
const request = vi.fn().mockResolvedValue({ status: 'ok' })
- // SAFETY: the store calls only `request`; the rest of the client is never touched in these tests.
- $gateway.set({ request } as never)
+ // SAFETY: the card calls only `request`; the rest of the client is never touched in this test.
+ setPrimaryGateway({ request } as never)
+ setPrimaryGatewayConnectionId('connection-1')
renderConnector()
@@ -221,8 +224,8 @@ describe('ConnectorTool operation card', () => {
await waitFor(() => {
expect(request).toHaveBeenCalledWith('connection.respond', {
op_id: 'operation-1',
- result: { settled_by: 'continue' },
- session_id: SESSION_ID
+ owner: { session_id: SESSION_ID, type: 'session' },
+ result: { settled_by: 'continue' }
})
})
})
diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.tsx
index 48b1c1a5b61..643833a363f 100644
--- a/apps/desktop/src/components/assistant-ui/connector-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/connector-tool.tsx
@@ -1,64 +1,40 @@
import type { ToolCallMessagePartProps } from '@assistant-ui/react'
-import type { ConnectionTargetState } from '@hermes/shared'
+import type { ConnectionTargetState, ConnectorsConnectResult } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { type RefObject, useEffect, useMemo, useRef, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
import { sessionRoute } from '@/app/routes'
-import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
import { Button } from '@/components/ui/button'
import { ConnectorCard, ConnectorRow, type ConnectorRowMark, ConnectorSummary } from '@/components/ui/connector-card'
import { useI18n } from '@/i18n'
import {
connectorAuthorizationUrl,
- connectorCalls,
connectorIconUrl,
connectorText,
connectorTitle,
- connectorToolName,
- recordOf
+ recordOf,
+ toolLabels,
+ toolLabelTitle
} from '@/lib/connector-tools'
import {
$connectionRequests,
+ type ConnectionOwner,
+ connectionOwnerFor,
type ConnectionRequest,
+ connectionRequestOpen,
type ConnectionTarget,
continueConnectionRequest,
sessionConnectionRequest
} from '@/store/connection-request'
import { requestGatewayForAgent } from '@/store/gateway'
import { notifyError } from '@/store/notifications'
-import { $activeGatewayProfile } from '@/store/profile'
-import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
-import { isSessionOwnerRoute } from '@/store/session-request-router'
-
-/** Which backend owns the session whose operation this card drives. */
-export interface ConnectorOwner {
- connectionId: null | string
- profile: string
-}
-
-/** Resolve that owner for one stored session, or null when it cannot be resolved. */
-async function connectionOwnerFor(sessionId: string, method: string): Promise<ConnectorOwner | null> {
- const ambientProfile = $activeGatewayProfile.get()
-
- try {
- const scope = await resolveSessionOwner(sessionId)
- assertSessionOwnerResolved(scope, { method, sessionId })
-
- return {
- connectionId: isSessionOwnerRoute(scope) ? scope.connectionId : null,
- profile: isSessionOwnerRoute(scope) ? scope.profile : scope || ambientProfile
- }
- } catch {
- return null
- }
-}
/** Resolve that owner. Null until it resolves and null when it cannot: a card RPC must reach the
* gateway that holds the operation, never whichever one the window happens to have in front. */
-export function useConnectionOwner(sessionId: null | string, active: boolean): ConnectorOwner | null {
- const [owner, setOwner] = useState<ConnectorOwner | null>(null)
+export function useConnectionOwner(sessionId: null | string, active: boolean): ConnectionOwner | null {
+ const [owner, setOwner] = useState<ConnectionOwner | null>(null)
useEffect(() => {
if (!sessionId || !active) {
@@ -112,7 +88,7 @@ export async function openConnectionDoneLink(
try {
await requestGatewayForAgent(owner.connectionId, owner.profile, 'connectors.operation.wake', {
op_id: op,
- session_id: request.sessionId
+ owner: { session_id: request.sessionId, type: 'session' }
})
} catch {
// The wake only shortens the wait. The operation can settle and leave the live registry between
@@ -121,26 +97,30 @@ export async function openConnectionDoneLink(
}
/** Try again for one target of the open operation: one RPC, and the fresh link when the backend
- * minted one. The backend re-mints only what is actually dead. */
+ * minted one. The backend re-mints only what is actually dead. A settled operation is dead: the
+ * RPC would open a second one that no card on this row can answer. */
export async function reissueConnectionTarget(
- owner: ConnectorOwner,
+ owner: ConnectionOwner,
request: ConnectionRequest,
name: string
): Promise<null | string> {
- const reply = await requestGatewayForAgent<ToolCallMessagePartProps['result']>(
+ if (!connectionRequestOpen(request)) {
+ return null
+ }
+
+ const reply = await requestGatewayForAgent<ConnectorsConnectResult>(
owner.connectionId,
owner.profile,
'connectors.connect',
{
connectors: [name],
- reconnect: true,
- session_id: request.sessionId
+ owner: { session_id: request.sessionId, type: 'session' },
+ reconnect: true
},
45000
)
- const rows = recordOf(reply).targets
- const minted = Array.isArray(rows) ? rows.map(recordOf).find(row => connectorText(row.name) === name) : undefined
+ const minted = reply.targets.find(target => target.name === name)
return connectorAuthorizationUrl(minted?.connect_url)
}
@@ -159,17 +139,6 @@ function requestedConnectorNames(args: ToolCallMessagePartProps['args']): string
})
}
-function matchingTargetNames(left: readonly string[], right: readonly string[]): boolean {
- if (left.length !== right.length) {
- return false
- }
-
- const leftSorted = [...left].sort()
- const rightSorted = [...right].sort()
-
- return leftSorted.every((name, index) => name === rightSorted[index])
-}
-
/** The card lives on the tool row whose id opened the operation and on no other. */
export function connectionRequestOwnsPart(props: ToolCallMessagePartProps, request: ConnectionRequest | null): boolean {
return Boolean(request && props.toolCallId === request.toolCallId)
@@ -226,8 +195,7 @@ export const CONNECTOR_CARD_PHASES = {
initiated: { mark: 'waiting', resolved: false, settled: notConnected, verb: 'open' },
not_connected: { mark: 'idle', resolved: false, settled: notConnected, verb: 'none' },
pending: { mark: 'idle', resolved: false, settled: notConnected, verb: 'open' },
- skipped: { mark: 'idle', resolved: true, settled: skipped, verb: 'none' },
- unavailable: { mark: 'idle', resolved: true, settled: notConnected, verb: 'none' }
+ skipped: { mark: 'idle', resolved: true, settled: skipped, verb: 'none' }
} satisfies Record<ConnectionTargetState, ConnectorCardPhase>
// A disabled verb (a working row, a waiting row with no link yet) refuses focus, and the keyboard
@@ -288,7 +256,7 @@ export const MARK_LABEL = {
} satisfies Record<ConnectorRowMark, (copy: ConnectorCopy) => string>
interface ConnectorOfferProps {
- owner: ConnectorOwner
+ owner: ConnectionOwner
request: ConnectionRequest
}
@@ -398,68 +366,44 @@ export function ConnectorOffer({ owner, request }: ConnectorOfferProps) {
)
}
-/** Keep execution output in the standard disclosure, with one row per app call. */
-export function ConnectorExecution(props: ToolCallMessagePartProps) {
- const view = useSessionView()
- const sessionId = useStore(view.$runtimeId)
- const $request = useMemo(() => sessionConnectionRequest(sessionId), [sessionId])
- const request = useStore($request)
- const calls = connectorCalls(props.toolName, props.args)
- const input = recordOf(props.args)
- const batch = Array.isArray(input.calls) ? input.calls : [input]
-
- // Mixed remote batches keep their complete disclosure and original result order.
- if (props.toolName === 'tool_call' && calls.length !== batch.length) {
- return <ToolFallback {...props} />
- }
+const MISSING_CALL_RESULT = { error: 'No result for this call.' }
+/** Keep execution output in the standard disclosure, with one row per inner call.
+ * The gateway labels every call the tool_search bridge runs — hosted, MCP or local —
+ * so hosted-only, MCP-only and mixed batches all render the same way. */
+export function ConnectorExecution(props: ToolCallMessagePartProps) {
+ const labels = toolLabels(props.args)
const output = recordOf(props.result)
const results = Array.isArray(output.results) ? output.results : []
- const repair = calls
- .filter((_call, index) => {
- const item = recordOf(props.toolName === 'tool_call' ? results[index] : props.result)
-
- return recordOf(item.error).connect_card_available === true
- })
- .map(call => {
- // SAFETY: connectorCalls includes only names accepted by connectorToolName.
- return connectorToolName(call.name)!.connector
- })
+ if (labels.length === 0) {
+ return <ToolFallback {...props} />
+ }
- const openRepair =
- request &&
- !request.settled &&
- matchingTargetNames(
- repair,
- request.targets.map(target => target.name)
- )
+ const input = recordOf(props.args)
+ const batch = Array.isArray(input.calls) ? input.calls : [input]
return (
<>
- {calls.map((call, index) => {
- const item =
- props.toolName === 'tool_call' ? (results[index] ?? (output.error ? output : undefined)) : props.result
-
+ {labels.map((label, index) => {
+ // A hosted batch answers one result per call; anything else answers once for the
+ // whole call, and every row shows that same outcome (a rejected batch, an error).
+ // A batch that answered short says so on the rows it left out.
+ const item = results[index] ?? (results.length > 0 ? MISSING_CALL_RESULT : props.result)
const result = recordOf(item)
- // SAFETY: connectorCalls includes only names accepted by connectorToolName.
- const identity = connectorToolName(call.name)!
return (
<ToolFallback
{...props}
- args={recordOf(call.arguments)}
+ args={recordOf(recordOf(batch[index]).arguments ?? props.args)}
isError={Boolean(result.error) || props.isError === true}
key={`${props.toolCallId}:${index}`}
- result={props.result === undefined ? undefined : (item ?? { error: 'Missing connector result' })}
+ result={item}
toolCallId={`${props.toolCallId}:${index}`}
- toolName={`${connectorTitle(identity.connector)}: ${identity.action}`}
+ toolName={toolLabelTitle(label)}
/>
)
})}
- {openRepair ? (
- <ConnectorTool {...props} args={{ action: 'status', connectors: repair }} result={undefined} />
- ) : null}
</>
)
}
diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx
index a55021f296f..67e61c295e5 100644
--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx
@@ -12,7 +12,8 @@ import {
type ConnectionTarget,
setConnectionRequest
} from '@/store/connection-request'
-import { $gateway, setPrimaryGateway } from '@/store/gateway'
+import { $gateway, setPrimaryGateway, setPrimaryGatewayConnectionId } from '@/store/gateway'
+import { setSessionOwnerHint } from '@/store/session'
const SESSION_ID = 'session-1'
@@ -116,9 +117,10 @@ describe('the MCP setup card', () => {
requiredEnv: [{ default: 'workspace', name: 'LINEAR_TEAM', prompt: 'Team', required: true, secret: false }]
}
- // SAFETY: the card calls only `request`; no other gateway client surface is exercised here.
- // respondToConnectionRequest reads $gateway, which only applyActive publishes; set it directly.
- $gateway.set({ request: rpc } as never)
+ setSessionOwnerHint(SESSION_ID, { connectionId: 'local', profile: 'default' })
+ // SAFETY: the card calls only `request`; the rest of the client is never touched in this test.
+ setPrimaryGateway({ request: rpc } as never)
+ setPrimaryGatewayConnectionId('local')
setConnectionRequest({ ...REQUEST, targets: [target] })
renderTool()
@@ -131,8 +133,8 @@ describe('the MCP setup card', () => {
await waitFor(() => expect(rpc).toHaveBeenCalledTimes(1))
expect(rpc).toHaveBeenCalledWith('connection.respond', {
op_id: 'operation-1',
- result: { targets: [{ env: { LINEAR_TEAM: 'workspace' }, name: 'linear', status: 'approved' }] },
- session_id: SESSION_ID
+ owner: { session_id: SESSION_ID, type: 'session' },
+ result: { targets: [{ env: { LINEAR_TEAM: 'workspace' }, name: 'linear', status: 'approved' }] }
})
})
diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
index 301933a18dd..3ef7b724dbd 100644
--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx
@@ -8,7 +8,6 @@ import { useSessionView } from '@/app/chat/session-view'
import {
connectionRequestOwnsPart,
CONNECTOR_CARD_PHASES,
- type ConnectorOwner,
MARK_LABEL,
reissueConnectionTarget,
useConnectionOwner,
@@ -25,6 +24,7 @@ import { Loader2 } from '@/lib/icons'
import { prettyName } from '@/lib/text'
import { cn } from '@/lib/utils'
import {
+ type ConnectionOwner,
type ConnectionRequest,
type ConnectionTarget,
type ConnectionTargetState,
@@ -72,8 +72,7 @@ const MCP_VERBS = {
initiated: 'open',
not_connected: 'none',
pending: 'approve',
- skipped: 'none',
- unavailable: 'none'
+ skipped: 'none'
} satisfies Record<ConnectionTargetState, McpVerb>
// Two states read differently per action. A pending authorize is the backend still minting the link,
@@ -213,7 +212,7 @@ export function McpSetupPending(props: ToolCallMessagePartProps) {
interface McpSetupOfferProps {
action: SetupAction
/** Null until the session's owner resolves; only Try again needs it, so the rest of the card works. */
- owner: ConnectorOwner | null
+ owner: ConnectionOwner | null
request: ConnectionRequest
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
index 80022ef408d..87ed5c9324a 100644
--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx
@@ -23,7 +23,7 @@ import { GeneratedImage } from '@/components/chat/generated-image-result'
import { SCAFFOLD_LABEL_CLASS, SCAFFOLD_META_CLASS, ScaffoldRow } from '@/components/chat/scaffold-row'
import { useOnboardingChatActive } from '@/components/onboarding-chat/assembly'
import { useI18n } from '@/i18n'
-import { connectorCalls, mcpTargets } from '@/lib/connector-tools'
+import { mcpTargets, toolLabels } from '@/lib/connector-tools'
import { generatedImageFromResult } from '@/lib/generated-images'
import { separateGluedReasoningBlocks } from '@/lib/reasoning-blocks'
import { isTodoToolName } from '@/lib/todos'
@@ -129,7 +129,7 @@ const ChainToolFallback: FC<TimelineToolCallProps> = props => {
return <ConnectorTool {...props} />
}
- if (connectorCalls(props.toolName, props.args).length > 0) {
+ if (toolLabels(props.args).length > 0) {
return <ConnectorExecution {...props} />
}
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 56b0db41859..f0a2e02be94 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -256,6 +256,7 @@ export const en: Translations = {
openaiTtsNeedsKey: 'Voice needs an OpenAI key. Add one in Settings → Keys.',
codeSkewRestartRequired:
'Hermes was updated but is still running the old version. Restart it to finish the update.',
+ rpcOutOfSync: 'The app and the backend are on different versions. Update both.',
restartHermesFailed: "Couldn't restart Hermes"
},
actions: {
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 372e28c35f1..0009eaac31c 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -297,6 +297,7 @@ export interface Translations {
openaiRejectedApiKey: string
openaiTtsNeedsKey: string
codeSkewRestartRequired: string
+ rpcOutOfSync: string
restartHermesFailed: string
}
actions: {
diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.ts
index fd5d695673c..aa21ce40e09 100644
--- a/apps/desktop/src/lib/chat-messages/hydration.ts
+++ b/apps/desktop/src/lib/chat-messages/hydration.ts
@@ -395,7 +395,9 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {
if (message.role === 'assistant' && Array.isArray(message.tool_calls)) {
parts.push(
- ...message.tool_calls.map((call, callIndex) => toolPartFromStoredCall(call, callIndex, message.timestamp))
+ ...message.tool_calls.map((call, callIndex) =>
+ toolPartFromStoredCall(call, callIndex, message.timestamp, message.tool_call_labels)
+ )
)
}
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index 9868b98a2cc..0b86cbed260 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -1,7 +1,10 @@
+import type { ToolLabel } from '@hermes/shared'
+
+import { TOOL_LABELS_ARG } from '@/lib/connector-tools'
import { firstStringField, normalize } from '@/lib/text'
import { isTodoToolName, parseTodos } from '@/lib/todos'
import type { ToolResultMetadata } from '@/lib/tool-result-metadata'
-import type { SessionMessage } from '@/types/hermes'
+import type { SessionMessage, StoredToolCallLabels } from '@/types/hermes'
import type { ChatMessage, ChatMessagePart, GatewayEventPayload } from './types'
@@ -25,6 +28,12 @@ function collectToolMatchValues(query: string, context: string, preview: string)
return [...new Set([query, context, preview].map(normalizeToolMatchValue).filter(Boolean))]
}
+/** The gateway names what a bridged `tool_call` actually runs; the row renders those words.
+ * Under a key no tool can take as an argument, so a tool's own `labels` never collides. */
+function labelArgs(labels: ToolLabel[] | undefined): { [TOOL_LABELS_ARG]: ToolLabel[] } | undefined {
+ return labels?.length ? { [TOOL_LABELS_ARG]: labels } : undefined
+}
+
function recordFromUnknown(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
}
@@ -279,6 +288,7 @@ function toolArgs(payload: GatewayEventPayload | undefined, prevArgs?: unknown):
...eventArgs,
...(payload?.context ? { context: payload.context } : {}),
...(payload?.preview ? { preview: payload.preview } : {}),
+ ...labelArgs(payload?.labels),
...carryTodos(payload, prevArgs)
}
}
@@ -762,7 +772,12 @@ function parseStoredToolResult(content: unknown): unknown {
}
}
-export function toolPartFromStoredCall(call: unknown, fallbackIndex: number, timestamp?: number): ChatMessagePart {
+export function toolPartFromStoredCall(
+ call: unknown,
+ fallbackIndex: number,
+ timestamp?: number,
+ labels?: StoredToolCallLabels
+): ChatMessagePart {
const row = recordFromUnknown(call) ?? {}
const fn = recordFromUnknown(row.function)
const id = String(row.id || row.tool_call_id || `stored-tool-${fallbackIndex}`)
@@ -771,7 +786,10 @@ export function toolPartFromStoredCall(call: unknown, fallbackIndex: number, tim
row.name || row.tool_name || fn?.name || (recordFromUnknown(row.input)?.name as string | undefined) || 'tool'
)
- const args = firstNonEmptyObject(fn?.arguments, row.arguments, row.args, row.input)
+ const args = {
+ ...firstNonEmptyObject(fn?.arguments, row.arguments, row.args, row.input),
+ ...labelArgs(labels?.[id])
+ }
return {
type: 'tool-call',
@@ -859,7 +877,8 @@ export function storedToolMessagePart(toolMessage: SessionMessage, fallbackIndex
// rebuilds the real command from args. Keep `context` alongside as the
// title-side placeholder.
const storedArgs = parseMaybeJsonObject(toolMessage.args)
- const args = { ...storedArgs, ...(context ? { context } : {}) }
+
+ const args = { ...storedArgs, ...(context ? { context } : {}), ...labelArgs(toolMessage.labels) }
return {
type: 'tool-call',
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 061b01f1551..d95bfc734ce 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -1,5 +1,5 @@
import type { ThreadMessageLike } from '@assistant-ui/react'
-import { type BillingBlock } from '@hermes/shared'
+import { type BillingBlock, type ToolLabel } from '@hermes/shared'
import type { ErrorSurface } from '@/lib/error-surface'
import type { ToolResultMetadata } from '@/lib/tool-result-metadata'
@@ -82,6 +82,7 @@ export type GatewayEventPayload = {
arguments?: unknown
context?: string
input?: unknown
+ labels?: ToolLabel[]
preview?: string
result?: unknown
summary?: string
diff --git a/apps/desktop/src/lib/connector-tools.ts b/apps/desktop/src/lib/connector-tools.ts
index 254436bf87a..d2d992ceef4 100644
--- a/apps/desktop/src/lib/connector-tools.ts
+++ b/apps/desktop/src/lib/connector-tools.ts
@@ -1,5 +1,6 @@
import { isRecord } from '@assistant-ui/core/internal'
import type { ToolCallMessagePart } from '@assistant-ui/react'
+import type { ToolLabel } from '@hermes/shared'
export interface McpTarget {
name: string
@@ -95,6 +96,48 @@ export function connectorToolName(name: string): { connector: string; action: st
return match ? { connector: match[1], action: match[2].replace(/_/g, ' ').toLowerCase() } : null
}
+const TOOL_LABEL_KINDS: readonly ToolLabel['kind'][] = ['connector', 'mcp', 'tool']
+
+/** Where the labels ride on a tool row's args. A real tool takes a `labels` argument
+ * (GitHub, Linear and Jira issue tools all do), so the key is one that cannot be one. */
+export const TOOL_LABELS_ARG = 'hermes_tool_labels'
+
+/** The gateway's own words for each inner call of a bridged `tool_call`, in call order.
+ * Rides beside `context` and `preview` on the tool row's args; empty for an ordinary tool. */
+export function toolLabels(args: ToolCallMessagePart['result']): ToolLabel[] {
+ const rows = recordOf(args)[TOOL_LABELS_ARG]
+
+ if (!Array.isArray(rows)) {
+ return []
+ }
+
+ return rows.flatMap(entry => {
+ const row = recordOf(entry)
+ const app = connectorText(row.app)
+ const text = connectorText(row.text)
+ const kind = connectorText(row.kind)
+
+ return app !== undefined && text !== undefined
+ ? [
+ {
+ action: connectorText(row.action) ?? '',
+ app,
+ emoji: connectorText(row.emoji) ?? '',
+ kind: TOOL_LABEL_KINDS.find(known => known === kind) ?? 'tool',
+ name: connectorText(row.name) ?? '',
+ preview: connectorText(row.preview) ?? '',
+ text
+ }
+ ]
+ : []
+ })
+}
+
+/** The row's own title: the phrase, then the primary argument the classic CLI also shows. */
+export function toolLabelTitle(label: ToolLabel): string {
+ return label.preview ? `${label.text} ${label.preview}` : label.text
+}
+
interface ConnectorCall {
name: string
arguments: ToolCallMessagePart['result']
diff --git a/apps/desktop/src/lib/gateway-rpc.ts b/apps/desktop/src/lib/gateway-rpc.ts
index 14c2d8a2dd6..ad4e6c20fd6 100644
--- a/apps/desktop/src/lib/gateway-rpc.ts
+++ b/apps/desktop/src/lib/gateway-rpc.ts
@@ -16,6 +16,10 @@ export function isMissingRpcMethod(error: unknown): boolean {
return /method not found|-32601|unknown method|no such method/i.test(message)
}
+export function isOutOfSyncRpcParams(error: Error | string): boolean {
+ return /out of sync \(different versions\)/i.test(error.toString())
+}
+
/** REST twin of isMissingRpcMethod: the route does not exist on this backend.
* Matches the backend catch-all ('404: {"detail":"No such API endpoint: …}'),
* FastAPI's bare 404 on headless serve — directly, or wrapped as "Error
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
index fe379580ddb..45f1e6fb769 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
@@ -53,6 +53,7 @@ export const capabilitiesViewRoutesConnections = Boolean(CapabilitiesView && Cap
* through the same toggle handlers, so they share one entry type. */
export interface CapabilityEntry {
auth?: string
+ connector?: string | null
description?: string
enabled?: boolean
fromCatalog?: boolean
diff --git a/apps/desktop/src/store/connection-request.test.ts b/apps/desktop/src/store/connection-request.test.ts
index f4b0d8adf2a..8c7ea94f843 100644
--- a/apps/desktop/src/store/connection-request.test.ts
+++ b/apps/desktop/src/store/connection-request.test.ts
@@ -15,7 +15,8 @@ import {
skipConnectionTarget,
updateConnectionRequest
} from './connection-request'
-import { $gateway } from './gateway'
+import { $gateway, setPrimaryGateway, setPrimaryGatewayConnectionId } from './gateway'
+import { _resetSessionOwnerHintsForTests, setSessionOwnerHint } from './session'
const WIRE = {
deadline_at: 1_800_000_000,
@@ -60,6 +61,7 @@ function frame(states: Record<string, Snapshot['targets'][number]['state']>, ext
return {
deadline_at: WIRE.deadline_at,
op_id: 'op-1',
+ owner: { session_id: 'a', type: 'session' },
seq: nextSeq++,
settled: false,
settled_by: null,
@@ -76,8 +78,16 @@ describe('connection-request store', () => {
afterEach(() => {
$connectionRequests.set({})
$gateway.set(null)
+ setPrimaryGateway(null)
+ _resetSessionOwnerHintsForTests({ storage: true })
})
+ function setOwnerGateway(rpc: Gateway['request']): void {
+ setSessionOwnerHint('a', { connectionId: 'local', profile: 'default' })
+ setPrimaryGateway(fakeGateway(rpc))
+ setPrimaryGatewayConnectionId('local')
+ }
+
it('normalizes the wire payload and keeps the server-owned deadline verbatim', () => {
const parsed = normalizeConnectionRequest(WIRE, 's1')
@@ -190,13 +200,13 @@ describe('connection-request store', () => {
it('respond keys on op_id, keeps the entry (the backend answers via connection.update), refuses once settled', async () => {
const rpc = vi.fn().mockResolvedValue({ status: 'ok', settled: false })
- $gateway.set(fakeGateway(rpc))
+ setOwnerGateway(rpc)
const req = request('a')
setConnectionRequest(req)
expect(await skipConnectionTarget(req, 'notion')).toBe(true)
expect(rpc.mock.calls[0][0]).toBe('connection.respond')
- expect(rpc.mock.calls[0][1]).toMatchObject({ op_id: 'op-1', session_id: 'a' })
+ expect(rpc.mock.calls[0][1]).toMatchObject({ op_id: 'op-1', owner: { session_id: 'a', type: 'session' } })
expect(rpc.mock.calls[0][1].result).toEqual({ targets: [{ name: 'notion', status: 'skipped' }] })
expect($connectionRequests.get().a).toBeDefined()
@@ -210,7 +220,7 @@ describe('connection-request store', () => {
it('typing while the card is open sends Continue, not a per-target decline', async () => {
const rpc = vi.fn().mockResolvedValue({ status: 'ok', settled: true })
- $gateway.set(fakeGateway(rpc))
+ setOwnerGateway(rpc)
setConnectionRequest(request('a'))
expect(await skipConnectionRequest('a')).toBe(true)
@@ -219,7 +229,7 @@ describe('connection-request store', () => {
it('continue is a one-field payload', async () => {
const rpc = vi.fn().mockResolvedValue({ status: 'ok', settled: true })
- $gateway.set(fakeGateway(rpc))
+ setOwnerGateway(rpc)
const req = request('a')
setConnectionRequest(req)
diff --git a/apps/desktop/src/store/connection-request.ts b/apps/desktop/src/store/connection-request.ts
index d8a5df392e6..639ac21a01b 100644
--- a/apps/desktop/src/store/connection-request.ts
+++ b/apps/desktop/src/store/connection-request.ts
@@ -1,4 +1,5 @@
import type {
+ ConnectionAnswer,
ConnectionOperationStatus,
ConnectionOperationTarget,
ConnectionRequestPayload,
@@ -11,9 +12,13 @@ import type {
} from '@hermes/shared'
import { atom, computed } from 'nanostores'
+import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
import type { SetupField } from '@/components/ui/setup-field-list'
-import { $gateway } from './gateway'
+import { $gateway, requestGatewayForAgent } from './gateway'
+import { $activeGatewayProfile } from './profile'
+import { assertSessionOwnerResolved } from './session-owner-resolution'
+import { isSessionOwnerRoute } from './session-request-router'
/** The backend sends ``prompt`` as null when the catalog entry has none; the form takes an absent one. */
const envFields = (fields: ConnectionTargetEnvField[] | null | undefined): SetupField[] =>
@@ -54,6 +59,11 @@ export interface ConnectionTarget {
/** The session's connection operation. `deadlineAt`, `opId`, `targets[].state`, `settled` and
* `settledBy` are backend-owned; the renderer holds a cache and drives it through `connection.respond`. */
+export interface ConnectionOwner {
+ connectionId: null | string
+ profile: string
+}
+
export interface ConnectionRequest {
/** The model's tool call that opened the operation. The card lives on that row and no other. */
toolCallId: string
@@ -70,17 +80,6 @@ export interface ConnectionRequest {
sessionId: string | null
}
-/** Answers the card may give for one target: the user said no, or the user consented and the backend
- * does the work. The card never reports an outcome; only the backend moves a target. */
-export type ConnectionTargetOutcome =
- { name: string; status: 'skipped' } | { env?: Record<string, string>; name: string; status: 'approved' }
-
-export interface ConnectionOutcome {
- targets?: ConnectionTargetOutcome[]
- /** `continue` ends the operation now with unresolved targets stamped `not_connected`. */
- settled_by?: 'continue'
-}
-
const keyFor = (sessionId: string | null | undefined): string => sessionId ?? ''
export const $connectionRequests = atom<Record<string, ConnectionRequest>>({})
@@ -95,19 +94,11 @@ const TARGET_STATES: readonly ConnectionTargetState[] = [
'initiated',
'not_connected',
'pending',
- 'skipped',
- 'unavailable'
+ 'skipped'
]
const ACTIONS: readonly ConnectionTargetAction[] = ['authorize', 'connect', 'enable', 'install', 'reconnect']
-
-const SETTLE_REASONS: readonly ConnectionSettleReason[] = [
- 'all_resolved',
- 'continue',
- 'deadline',
- 'interrupt',
- 'unavailable'
-]
+const SETTLE_REASONS: readonly ConnectionSettleReason[] = ['all_resolved', 'continue', 'deadline', 'interrupt']
// The wire carries these as typed literals already; the lookups defend against a backend a version ahead.
const oneOf =
@@ -300,23 +291,53 @@ export const hasConnectionRequest = (sessionId: string | null | undefined): bool
return Boolean(request && !request.settled)
}
+export async function connectionOwnerFor(sessionId: string, method: string): Promise<ConnectionOwner | null> {
+ const ambientProfile = $activeGatewayProfile.get()
+
+ try {
+ const scope = await resolveSessionOwner(sessionId)
+ assertSessionOwnerResolved(scope, { method, sessionId })
+
+ return {
+ connectionId: isSessionOwnerRoute(scope) ? scope.connectionId : null,
+ profile: isSessionOwnerRoute(scope) ? scope.profile : scope || ambientProfile
+ }
+ } catch {
+ return null
+ }
+}
+
+export const connectionRequestOpen = (
+ request: ConnectionRequest
+): request is ConnectionRequest & { sessionId: string } => {
+ const current = $connectionRequests.get()[keyFor(request.sessionId)]
+
+ return Boolean(request.sessionId && current && current.opId === request.opId && !current.settled)
+}
+
/** Drive the operation. The entry stays in the store: the backend answers with `connection.update`
* and the card re-renders from that; only settlement removes it. */
export async function respondToConnectionRequest(
request: ConnectionRequest,
- outcome: ConnectionOutcome
+ outcome: ConnectionAnswer
): Promise<boolean> {
- const current = $connectionRequests.get()[keyFor(request.sessionId)]
-
- if (!current || current.opId !== request.opId || current.settled) {
+ if (!connectionRequestOpen(request)) {
return false
}
- await $gateway.get()?.request('connection.respond', {
+ const params = {
op_id: request.opId,
- result: outcome,
- session_id: request.sessionId
- })
+ owner: { session_id: request.sessionId, type: 'session' as const },
+ result: outcome
+ }
+
+ const owner = await connectionOwnerFor(request.sessionId, 'connection.respond')
+
+ if (owner) {
+ await requestGatewayForAgent(owner.connectionId, owner.profile, 'connection.respond', params)
+ } else {
+ await $gateway.get()?.request('connection.respond', params)
+ }
return true
}
diff --git a/apps/desktop/src/store/connector-catalog.ts b/apps/desktop/src/store/connector-catalog.ts
index b9e32926029..00d69385688 100644
--- a/apps/desktop/src/store/connector-catalog.ts
+++ b/apps/desktop/src/store/connector-catalog.ts
@@ -18,8 +18,11 @@
import { useEffect, useState } from 'react'
import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
+import { translateNow } from '@/i18n'
import type { ConnectorRow } from '@/lib/connector-tools'
+import { isMissingRpcMethod, isOutOfSyncRpcParams } from '@/lib/gateway-rpc'
import { requestGatewayForAgent } from '@/store/gateway'
+import { notifyError } from '@/store/notifications'
import { $activeGatewayProfile } from '@/store/profile'
import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
import { isSessionOwnerRoute } from '@/store/session-request-router'
@@ -54,7 +57,7 @@ export function useConnectorCatalog(storedId: null | string, runtimeId: null | s
connectionId,
profile,
'connectors.list',
- { session_id: runtimeId },
+ { owner: { session_id: runtimeId, type: 'session' } },
15000
)
})
@@ -63,9 +66,13 @@ export function useConnectorCatalog(storedId: null | string, runtimeId: null | s
setCatalog(response.available ? { rows: response.connectors, status: 'ready' } : { status: 'unavailable' })
}
})
- .catch(() => {
+ .catch(error => {
if (!cancelled) {
setCatalog({ status: 'unavailable' })
+
+ if (isMissingRpcMethod(error) || isOutOfSyncRpcParams(error)) {
+ notifyError(error, translateNow('connectors.unavailable'), { id: 'connectors-rpc-out-of-sync' })
+ }
}
})
diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.ts
index 57d2fda740a..00fd7c22243 100644
--- a/apps/desktop/src/store/notifications.ts
+++ b/apps/desktop/src/store/notifications.ts
@@ -1,6 +1,7 @@
import { atom } from 'nanostores'
import { translateNow } from '@/i18n'
+import { isOutOfSyncRpcParams } from '@/lib/gateway-rpc'
import { isLocalBackendSlotWaitTimeout, requestPoolLimitsSettings } from '@/store/pool-limits'
import { requestBackendRestart, requestRoute } from '@/store/recovery-requests'
@@ -100,6 +101,10 @@ const MAINTENANCE_ROUTE = '/command-center?section=maintenance'
/** One-click recoveries reused by several rules. */
export const RECOVERY_ACTIONS = {
+ openUpdates: (): NotificationAction => ({
+ label: translateNow('notifications.updateHermes'),
+ onClick: () => void import('@/store/updates').then(({ openUpdatesWindow }) => openUpdatesWindow())
+ }),
restartHermes: (): NotificationAction => ({
label: translateNow('notifications.actions.restartHermes'),
onClick: requestBackendRestart
@@ -178,6 +183,11 @@ const ERROR_SUMMARIES: ErrorSummaryRule[] = [
test: msg => /microphone permission/i.test(msg),
summarize: () => translateNow('notifications.errors.microphonePermission')
},
+ {
+ test: msg => isOutOfSyncRpcParams(msg),
+ summarize: () => translateNow('notifications.errors.rpcOutOfSync'),
+ action: () => RECOVERY_ACTIONS.openUpdates()
+ },
{
test: msg => /Restart required:/i.test(msg),
summarize: () => translateNow('notifications.errors.codeSkewRestartRequired'),
@@ -247,7 +257,11 @@ export function notify(input: NotificationInput): string {
return id
}
-export function notifyError(error: unknown, fallback: string, options: { action?: NotificationAction } = {}): string {
+export function notifyError(
+ error: unknown,
+ fallback: string,
+ options: { action?: NotificationAction; id?: string } = {}
+): string {
const readable = readableError(error, fallback)
const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)
@@ -258,6 +272,8 @@ export function notifyError(error: unknown, fallback: string, options: { action?
onClick: requestPoolLimitsSettings
}
: (options.action ?? readable.action),
+ // A caller that can fire again for the same cause names its toast, so the repeat replaces it.
+ id: options.id,
kind: 'error',
title: fallback,
message: poolSlotTimeout ? translateNow('desktop.poolSlotTimeoutBody') : readable.message,
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index 06fedccfe7d..d170b9e5c84 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -105,7 +105,7 @@ function isUpdateToastSnoozed(): boolean {
// v7: requires JSON-RPC server->client requests for every blocking prompt
// (approval/clarify/sudo/secret/vault/MCP setup); a v6 backend's
// `<kind>.request` notifications would never render a card.
-export const REQUIRED_BACKEND_CONTRACT = 7
+export const REQUIRED_BACKEND_CONTRACT = 8
const SKEW_TOAST_ID = 'backend-contract-skew'
// The contract check runs on every session.resume (applyRuntimeInfo), so
// without a snooze the warning re-popped on every thread the user opened, even
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index cf58230dc43..6ff7f883bb0 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1,4 +1,6 @@
-import type { ConnectionRequestPayload } from '@hermes/shared'
+import type { ConnectionRequestPayload, ToolLabel } from '@hermes/shared'
+
+export type StoredToolCallLabels = Record<string, ToolLabel[]>
export interface ConfigFieldSchema {
category?: string
@@ -615,6 +617,8 @@ export interface SessionMessage {
*/
args?: unknown
codex_reasoning_items?: unknown
+ labels?: ToolLabel[]
+ tool_call_labels?: StoredToolCallLabels
/** Responses-API assistant message items; text parts here are the
* user-visible reply when `content` persisted empty (#68321). */
codex_message_items?: unknown
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index ea6bb234d1f..43c80c323e9 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -458,78 +458,6 @@ export interface ProjectFacts {
verifyCommands: string[]
contextFiles: string[]
}
-export interface ConnectionOperationParams {
- profile?: string | null
- session_id: string
- op_id: string
-}
-/** ``methods_connectors._operation_view``: the operation's full snapshot. */
-export interface ConnectionOperationStatus {
- op_id: string
- seq: number
- deadline_at: number
- settled: boolean
- settled_at?: number | null
- settled_by?: ConnectionSettleReason | null
- targets: ConnectionOperationTarget[]
-}
-/** ``tools/connectors/contract.py::SettleReason``. */
-export type ConnectionSettleReason = 'all_resolved' | 'continue' | 'deadline' | 'interrupt' | 'unavailable'
-/** ``Target.snapshot``: the link minted up front rides here, never in the model result. ``extra`` keys a leg records (``tools``, ``hint``) are typed here as they appear. */
-export interface ConnectionOperationTarget {
- name: string
- kind: ConnectionTargetKind
- action: ConnectionTargetAction
- state: ConnectionTargetState
- detail?: string | null
- instructions?: string | null
- discovery_error?: string | null
- connect_url?: string | null
- connection_id?: string | null
- attempt?: string | null
- required_env?: ConnectionTargetEnvField[] | null
- tools?: string[] | null
- hint?: string | null
-}
-export type ConnectionTargetKind = 'connector' | 'mcp'
-export type ConnectionTargetAction = 'authorize' | 'connect' | 'enable' | 'install' | 'reconnect'
-/** ``tools/connectors/contract.py::TargetState``. */
-export type ConnectionTargetState = 'pending' | 'initiated' | 'connected' | 'skipped' | 'failed' | 'expired' | 'unavailable' | 'not_connected'
-/** One credential an MCP install still needs; the card renders a field per entry and sends the values back with the approval. */
-export interface ConnectionTargetEnvField {
- name: string
- required: boolean
- secret: boolean
- default: string
- prompt?: string | null
-}
-export interface ConnectionWakeResult {
- status: string
-}
-export interface ConnectionRespondParams {
- profile?: string | null
- session_id: string
- op_id: string
- result: ConnectionAnswer
-}
-/** The card's answer: per-target outcomes and an optional Continue (``settled_by: "continue"``). Settlement is derived from target states afterwards. */
-export interface ConnectionAnswer {
- targets?: ConnectionAnswerTarget[]
- settled_by?: ConnectionSettleReason | null
-}
-/** One row's answer from the card. ``env`` carries the credential values an install asked for through ``required_env``. */
-export interface ConnectionAnswerTarget {
- name: string
- status: ConnectionAnswerStatus
- detail?: string | null
- env?: Record<string, string> | null
-}
-/** What the card says about one row: ``tools/connectors/mcp.py::apply_answer``. */
-export type ConnectionAnswerStatus = 'approved' | 'skipped'
-export interface ConnectionRespondResult {
- status: string
- settled: boolean
-}
/** ``key`` selects one getter from ``_CONFIG_GETTERS``; ``cwd`` feeds the ``project`` getter, ``session_id`` lets ``reasoning`` / ``fast`` answer with the session's live pin. */
export interface ConfigGetParams {
profile?: string | null
@@ -768,42 +696,6 @@ export interface ModelPricing {
was_input?: string | null
was_output?: string | null
}
-export interface ConnectorsListParams {
- profile?: string | null
- session_id: string
-}
-export interface ConnectorsListResult {
- available: boolean
- connectors: ConnectorRow[]
-}
-/** One ``manage_connections`` status entry after ``connector_ui_payload`` redaction; the connector service owns the closed key set, so unknown metadata passes through. */
-export interface ConnectorRow {
- connector?: string
- connected?: boolean | null
- enabled?: boolean | null
- connectionStatus?: string | null
- name?: string | null
- description?: string | null
- [key: string]: unknown
-}
-export interface ConnectorsConnectParams {
- profile?: string | null
- session_id: string
- connectors: string[]
- reconnect?: boolean
-}
-/** The operation the connect opened (or re-minted on): ``tools/connectors/managed.py`` ``_off_desktop_result`` / ``methods_connectors._reissue``. ``status``/``note`` ride along from the tool result when the call ran through ``manage_connections``. */
-export interface ConnectorsConnectResult {
- op_id: string
- seq: number
- deadline_at: number
- settled: boolean
- settled_at?: number | null
- settled_by?: ConnectionSettleReason | null
- targets: ConnectionOperationTarget[]
- status?: string | null
- note?: string | null
-}
export interface ImageGenerateParams {
prompt?: string | null
aspect_ratio?: string | null
@@ -958,6 +850,264 @@ export interface VerificationEvidenceRow {
output_summary?: string | null
[key: string]: unknown
}
+export interface ConnectionOperationParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ op_id: string
+}
+export interface SessionOwner {
+ type: 'session'
+ session_id: string
+}
+export interface AccountOwner {
+ type: 'account'
+}
+/** ``methods_connectors._operation_view``: the operation's full snapshot. */
+export interface ConnectionOperationStatus {
+ op_id: string
+ seq: number
+ deadline_at: number
+ settled: boolean
+ settled_at?: number | null
+ settled_by?: ConnectionSettleReason | null
+ targets: ConnectionOperationTarget[]
+}
+/** ``tools/connectors/contract.py::SettleReason``. */
+export type ConnectionSettleReason = 'all_resolved' | 'continue' | 'deadline' | 'interrupt'
+/** ``Target.snapshot``: the link minted up front rides here, never in the model result. ``extra`` keys a leg records (``tools``, ``hint``) are typed here as they appear. */
+export interface ConnectionOperationTarget {
+ name: string
+ kind: ConnectionTargetKind
+ action: ConnectionTargetAction
+ state: ConnectionTargetState
+ detail?: string | null
+ instructions?: string | null
+ discovery_error?: string | null
+ connect_url?: string | null
+ connection_id?: string | null
+ attempt?: string | null
+ required_env?: ConnectionTargetEnvField[] | null
+ tools?: string[] | null
+ hint?: string | null
+}
+export type ConnectionTargetKind = 'connector' | 'mcp'
+export type ConnectionTargetAction = 'authorize' | 'connect' | 'enable' | 'install' | 'reconnect'
+/** ``tools/connectors/contract.py::TargetState``. */
+export type ConnectionTargetState = 'pending' | 'initiated' | 'connected' | 'skipped' | 'failed' | 'expired' | 'not_connected'
+/** One credential an MCP install still needs; the card renders a field per entry and sends the values back with the approval. */
+export interface ConnectionTargetEnvField {
+ name: string
+ required: boolean
+ secret: boolean
+ default: string
+ prompt?: string | null
+}
+export interface ConnectionWakeResult {
+ status: 'ok'
+}
+export interface ConnectionRespondParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ op_id: string
+ result: ConnectionAnswer
+}
+/** The card's answer: per-target outcomes and an optional Continue (``settled_by: "continue"``). Settlement is derived from target states afterwards. */
+export interface ConnectionAnswer {
+ targets?: ConnectionAnswerTarget[]
+ settled_by?: ConnectionSettleReason | null
+}
+/** One row's answer from the card. ``env`` carries the credential values an install asked for through ``required_env``. */
+export interface ConnectionAnswerTarget {
+ name: string
+ status: ConnectionAnswerStatus
+ detail?: string | null
+ env?: Record<string, string> | null
+}
+/** What the card says about one row: ``tools/connectors/mcp.py::apply_answer``. */
+export type ConnectionAnswerStatus = 'approved' | 'skipped'
+export interface ConnectionRespondResult {
+ status: 'ok'
+ settled: boolean
+}
+export interface ConnectorsListParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+}
+export interface ConnectorsListResult {
+ available: boolean
+ connectors: ConnectorRow[]
+}
+export interface ConnectorRow {
+ connector: string
+ enabled: boolean
+ connected: boolean
+ connection_status: 'pending' | 'active' | 'failed' | 'expired' | 'revoked' | 'inactive' | null
+ status_reason: string | null
+ gateway_disabled_tools: string[]
+}
+export interface ConnectorsConnectParams {
+ profile?: string | null
+ owner: SessionOwner | AccountOwner
+ connectors: string[]
+ reconnect?: boolean
+}
+/** ``methods_connectors._reissue`` / ``managed._off_desktop_result``: the operation the connect opened; ``status``/``note`` ride along from the tool result. */
+export interface ConnectorsConnectResult {
+ op_id: string
+ seq: number
+ deadline_at: number
+ settled: boolean
+ settled_at?: number | null
+ settled_by?: ConnectionSettleReason | null
+ targets: ConnectionOperationTarget[]
+ status?: 'initiated' | 'settled' | null
+ note?: string | null
+}
+export interface ConnectorToolsParams {
+ profile?: string | null
+ slug: string
+ refresh?: boolean
+}
+export interface ConnectorToolsResult {
+ connector: string
+ toolkit_version: string
+ etag: string
+ fetched_at: number
+ source: ConnectorToolsSource
+ stale: boolean
+ tools: ConnectorToolRow[]
+}
+export type ConnectorToolsSource = 'cache' | 'network' | 'revalidated'
+export interface ConnectorToolRow {
+ slug: string
+ name: string
+ description: string
+ facet: ConnectorToolFacet
+ hints: string[]
+ categories: string[]
+ no_auth: boolean
+ deprecated: boolean
+}
+export type ConnectorToolFacet = 'read' | 'write' | 'destructive' | 'unclassified'
+export interface ConnectorsCatalogResult {
+ connectors: ConnectorCatalogRow[]
+}
+export interface ConnectorCatalogRow {
+ slug: string
+ name: string
+ description: string
+ category: string
+ logo_url?: string | null
+}
+export interface ConnectorAccountsParams {
+ profile?: string | null
+ connector?: string | null
+}
+export interface ConnectorAccountsResult {
+ accounts: ConnectorAccountRow[]
+}
+export interface ConnectorAccountRow {
+ connection_id: string
+ connector: string
+ status: ConnectorAccountStatus
+ status_reason?: string | null
+ label: string
+ alias?: string | null
+ active: boolean
+ created_at: string
+ updated_at: string
+}
+export type ConnectorAccountStatus = 'pending' | 'active' | 'failed' | 'expired' | 'revoked' | 'inactive'
+export interface ConnectorAccountsRemoveParams {
+ profile?: string | null
+ connection_id: string
+}
+export interface ConnectorAccountsRemoveResult {
+ connection_id: string
+ connector: string
+ status: 'removed'
+}
+export interface ConnectorPolicyGetResult {
+ layers: ConnectorPolicyLayer[]
+ effective: ConnectorPolicyEffectiveUnrestricted | ConnectorPolicyEffectiveDenyAll | ConnectorPolicyEffectiveAllow | ConnectorPolicyEffectiveDeny
+}
+export interface ConnectorPolicyLayer {
+ kind: ConnectorPolicyLayerKind
+ revision: string
+ body: ConnectorPolicyUnrestrictedBody | ConnectorPolicyDenyAllBody | ConnectorPolicyAllowBody | ConnectorPolicyDenyBody
+}
+export type ConnectorPolicyLayerKind = 'org' | 'role' | 'member'
+export interface ConnectorPolicyUnrestrictedBody {
+ mode: 'unrestricted'
+}
+export interface ConnectorPolicyDenyAllBody {
+ mode: 'deny-all'
+}
+export interface ConnectorPolicyAllowBody {
+ mode: 'allow'
+ connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+}
+export interface ConnectorPolicyTags {
+ enable?: string[] | null
+ disable?: string[] | null
+}
+export interface ConnectorPolicyDenyBody {
+ mode: 'deny'
+ disabled_connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+}
+export interface ConnectorPolicyEffectiveUnrestricted {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'unrestricted'
+}
+export interface ConnectorPolicyEffectiveDenyAll {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'deny-all'
+}
+export interface ConnectorPolicyEffectiveAllow {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'allow'
+ connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+}
+export interface ConnectorPolicyEffectiveDeny {
+ version: 1
+ revision: string
+ issued_at_ms: number
+ mode: 'deny'
+ disabled_connectors: string[]
+ tools: Record<string, string[]>
+ tags?: ConnectorPolicyTags | null
+}
+export interface ConnectorPolicySetParams {
+ profile?: string | null
+ change: ToolsChange | ConnectorChange
+ expected_revision: string
+}
+export interface ToolsChange {
+ type: 'tools'
+ connector: string
+ disabled_tools: string[]
+}
+export interface ConnectorChange {
+ type: 'connector'
+ connector: string
+ enabled: boolean
+}
+export interface ConnectorPolicySetResult {
+ revision: string
+ effective: ConnectorPolicyEffectiveUnrestricted | ConnectorPolicyEffectiveDenyAll | ConnectorPolicyEffectiveAllow | ConnectorPolicyEffectiveDeny
+}
export interface GroupsCapabilitiesParams {
profile?: string | null
}
@@ -2510,9 +2660,22 @@ export interface TranscriptMessage {
name?: string | null
context?: string | null
args?: Record<string, unknown> | null
+ labels?: ToolLabel[] | null
reasoning?: string | null
[key: string]: unknown
}
+/** ``tools.tool_labels.ToolLabel`` — what one call executed through the tool_search bridge is, in words. Clients render ``text`` (or ``app``/``action`` in their own columns) and never parse the tool name themselves. */
+export interface ToolLabel {
+ kind: ToolLabelKind
+ app: string
+ action: string
+ emoji: string
+ text: string
+ name: string
+ preview?: string
+}
+/** Which surface one inner call of a bridged ``tool_call`` runs on. */
+export type ToolLabelKind = 'connector' | 'mcp' | 'tool'
/** ``session_id`` is the STORED id (or an exact title); the reply's ``session_id`` is the runtime id. */
export interface SessionResumeParams {
session_id: string
@@ -3848,6 +4011,7 @@ export interface ConnectionUpdatePayload {
settled_at?: number | null
settled_by?: ConnectionSettleReason | null
targets: ConnectionOperationTarget[]
+ owner: SessionOwner | AccountOwner
target?: string | null
from?: ConnectionTargetState | null
to?: ConnectionTargetState | null
@@ -3978,6 +4142,7 @@ export interface ToolStartPayload {
args?: Record<string, unknown> | null
args_text?: string | null
preview?: string | null
+ labels?: ToolLabel[] | null
}
/** ``tool_progress._on_tool_complete``; ``todos``/``revision`` merged in for the todo tools. */
export interface ToolCompletePayload {
@@ -3991,6 +4156,7 @@ export interface ToolCompletePayload {
inline_diff?: string | null
todos?: unknown[] | null
revision?: number | null
+ labels?: ToolLabel[] | null
}
/** ``agent_callbacks`` tool_gen_callback. */
export interface ToolGeneratingPayload {
@@ -4218,6 +4384,7 @@ export interface RequestCancelPayload {
method: string
reason: string
}
+export type ConnectorErrorReason = 'INVALID_PARAMS' | 'NOT_OWNER' | 'UNSUPPORTED_RUNTIME' | 'CONNECTOR_REQUEST_FAILED' | 'INVALID_CONNECTOR_RESPONSE' | 'UNKNOWN_TARGET' | 'LINK_STILL_VALID' | 'REISSUE_REFUSED' | 'UNKNOWN_OPERATION' | 'INVALID_ANSWER' | 'NEEDS_NOUS_AUTH' | 'CONNECTOR_NOT_FOUND' | 'TOOLS_UNAVAILABLE' | 'CONNECTORS_UNAVAILABLE' | 'CATALOG_UNAVAILABLE' | 'ACCOUNTS_UNAVAILABLE' | 'CONNECTION_NOT_FOUND' | 'POLICY_UNAVAILABLE' | 'POLICY_CONFLICT' | 'FORBIDDEN_SCOPE' | 'ORG_REQUIRED' | 'ORG_ACCESS_DENIED' | 'INVALID_POLICY'
// ── Client→server methods ──
export interface RpcMethods {
@@ -4283,14 +4450,26 @@ export interface RpcMethods {
'config.show': { params: ConfigShowParams; result: ConfigShowResult }
/** Per-target outcomes from the card, and an optional Continue. */
'connection.respond': { params: ConnectionRespondParams; result: ConnectionRespondResult }
- /** Start (or re-initiate) authorization for named connectors on the session's connection operation. */
+ /** The scoped member's hosted connector accounts, optionally filtered by connector slug. */
+ 'connectors.accounts': { params: ConnectorAccountsParams; result: ConnectorAccountsResult }
+ /** Remove one hosted connector account owned by the scoped member. */
+ 'connectors.accounts.remove': { params: ConnectorAccountsRemoveParams; result: ConnectorAccountsRemoveResult }
+ /** The hosted connector catalog available to the scoped member. */
+ 'connectors.catalog': { params: ProfileParams; result: ConnectorsCatalogResult }
+ /** Start or re-initiate authorization for named connectors on a session or account operation. */
'connectors.connect': { params: ConnectorsConnectParams; result: ConnectorsConnectResult }
- /** Connector catalog + connection state for one owned session (``available=False`` when the toolset is off). */
+ /** Connector catalog + connection state for one session or profile account owner. */
'connectors.list': { params: ConnectorsListParams; result: ConnectorsListResult }
- /** The current snapshot of one open operation on an owned session. */
+ /** The current snapshot of one open session or account operation. */
'connectors.operation.status': { params: ConnectionOperationParams; result: ConnectionOperationStatus }
/** The browser leg came back (hermes://connections/done): read the accounts now, not at the next tick. */
'connectors.operation.wake': { params: ConnectionOperationParams; result: ConnectionWakeResult }
+ /** Policy layers for the scoped member, from organization to member scope. */
+ 'connectors.policy.get': { params: ProfileParams; result: ConnectorPolicyGetResult }
+ /** Apply one scoped member connector or tool-list policy change. */
+ 'connectors.policy.set': { params: ConnectorPolicySetParams; result: ConnectorPolicySetResult }
+ /** The scoped profile's cached or current tool list for one connector. */
+ 'connectors.tools': { params: ConnectorToolsParams; result: ConnectorToolsResult }
/** List/add/remove/pause/resume cron jobs in the (optionally profile-scoped) cron store. */
'cron.manage': { params: CronManageParams; result: CronManageResult }
/** Block/unblock NEW spawns globally (active children keep running); returns the new state. */
@@ -4693,10 +4872,16 @@ export const RPC_METHODS = [
'config.set',
'config.show',
'connection.respond',
+ 'connectors.accounts',
+ 'connectors.accounts.remove',
+ 'connectors.catalog',
'connectors.connect',
'connectors.list',
'connectors.operation.status',
'connectors.operation.wake',
+ 'connectors.policy.get',
+ 'connectors.policy.set',
+ 'connectors.tools',
'cron.manage',
'delegation.pause',
'delegation.status',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 224b30bb25a..3348fb02100 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -564,9 +564,63 @@
}
}
},
+ {
+ "name": "connectors.accounts",
+ "summary": "The scoped member's hosted connector accounts, optionally filtered by connector slug.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorAccountsParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorAccountsResult"
+ }
+ }
+ },
+ {
+ "name": "connectors.accounts.remove",
+ "summary": "Remove one hosted connector account owned by the scoped member.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorAccountsRemoveParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorAccountsRemoveResult"
+ }
+ }
+ },
+ {
+ "name": "connectors.catalog",
+ "summary": "The hosted connector catalog available to the scoped member.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ProfileParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorsCatalogResult"
+ }
+ }
+ },
{
"name": "connectors.connect",
- "summary": "Start (or re-initiate) authorization for named connectors on the session's connection operation.",
+ "summary": "Start or re-initiate authorization for named connectors on a session or account operation.",
"params": [
{
"name": "params",
@@ -584,7 +638,7 @@
},
{
"name": "connectors.list",
- "summary": "Connector catalog + connection state for one owned session (``available=False`` when the toolset is off).",
+ "summary": "Connector catalog + connection state for one session or profile account owner.",
"params": [
{
"name": "params",
@@ -602,7 +656,7 @@
},
{
"name": "connectors.operation.status",
- "summary": "The current snapshot of one open operation on an owned session.",
+ "summary": "The current snapshot of one open session or account operation.",
"params": [
{
"name": "params",
@@ -636,6 +690,60 @@
}
}
},
+ {
+ "name": "connectors.policy.get",
+ "summary": "Policy layers for the scoped member, from organization to member scope.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ProfileParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorPolicyGetResult"
+ }
+ }
+ },
+ {
+ "name": "connectors.policy.set",
+ "summary": "Apply one scoped member connector or tool-list policy change.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorPolicySetParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorPolicySetResult"
+ }
+ }
+ },
+ {
+ "name": "connectors.tools",
+ "summary": "The scoped profile's cached or current tool list for one connector.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorToolsParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConnectorToolsResult"
+ }
+ }
+ },
{
"name": "cron.manage",
"summary": "List/add/remove/pause/resume cron jobs in the (optionally profile-scoped) cron store.",
@@ -3951,6 +4059,21 @@
],
"components": {
"schemas": {
+ "AccountOwner": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "account",
+ "title": "Type",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "title": "AccountOwner",
+ "type": "object"
+ },
"ActiveIdResult": {
"additionalProperties": false,
"properties": {
@@ -8428,9 +8551,23 @@
"default": null,
"title": "Profile"
},
- "session_id": {
- "title": "Session Id",
- "type": "string"
+ "owner": {
+ "discriminator": {
+ "mapping": {
+ "account": "#/components/schemas/AccountOwner",
+ "session": "#/components/schemas/SessionOwner"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SessionOwner"
+ },
+ {
+ "$ref": "#/components/schemas/AccountOwner"
+ }
+ ],
+ "title": "Owner"
},
"op_id": {
"title": "Op Id",
@@ -8438,7 +8575,7 @@
}
},
"required": [
- "session_id",
+ "owner",
"op_id"
],
"title": "ConnectionOperationParams",
@@ -8711,9 +8848,23 @@
"default": null,
"title": "Profile"
},
- "session_id": {
- "title": "Session Id",
- "type": "string"
+ "owner": {
+ "discriminator": {
+ "mapping": {
+ "account": "#/components/schemas/AccountOwner",
+ "session": "#/components/schemas/SessionOwner"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SessionOwner"
+ },
+ {
+ "$ref": "#/components/schemas/AccountOwner"
+ }
+ ],
+ "title": "Owner"
},
"op_id": {
"title": "Op Id",
@@ -8724,7 +8875,7 @@
}
},
"required": [
- "session_id",
+ "owner",
"op_id",
"result"
],
@@ -8735,6 +8886,7 @@
"additionalProperties": false,
"properties": {
"status": {
+ "const": "ok",
"title": "Status",
"type": "string"
},
@@ -8756,8 +8908,7 @@
"all_resolved",
"continue",
"deadline",
- "interrupt",
- "unavailable"
+ "interrupt"
],
"title": "ConnectionSettleReason",
"type": "string"
@@ -8832,7 +8983,6 @@
"skipped",
"failed",
"expired",
- "unavailable",
"not_connected"
],
"title": "ConnectionTargetState",
@@ -8888,9 +9038,1223 @@
"title": "Targets",
"type": "array"
},
- "target": {
+ "owner": {
+ "discriminator": {
+ "mapping": {
+ "account": "#/components/schemas/AccountOwner",
+ "session": "#/components/schemas/SessionOwner"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SessionOwner"
+ },
+ {
+ "$ref": "#/components/schemas/AccountOwner"
+ }
+ ],
+ "title": "Owner"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Target"
+ },
+ "from": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectionTargetState"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "to": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectionTargetState"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "actor": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectionActor"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "detail": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Detail"
+ }
+ },
+ "required": [
+ "op_id",
+ "seq",
+ "deadline_at",
+ "settled",
+ "targets",
+ "owner"
+ ],
+ "title": "ConnectionUpdatePayload",
+ "type": "object"
+ },
+ "ConnectionWakeResult": {
+ "additionalProperties": false,
+ "properties": {
+ "status": {
+ "const": "ok",
+ "title": "Status",
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "title": "ConnectionWakeResult",
+ "type": "object"
+ },
+ "ConnectorAccountRow": {
+ "additionalProperties": false,
+ "properties": {
+ "connection_id": {
+ "title": "Connection Id",
+ "type": "string"
+ },
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "status": {
+ "$ref": "#/components/schemas/ConnectorAccountStatus"
+ },
+ "status_reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Status Reason"
+ },
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "alias": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Alias"
+ },
+ "active": {
+ "title": "Active",
+ "type": "boolean"
+ },
+ "created_at": {
+ "title": "Created At",
+ "type": "string"
+ },
+ "updated_at": {
+ "title": "Updated At",
+ "type": "string"
+ }
+ },
+ "required": [
+ "connection_id",
+ "connector",
+ "status",
+ "label",
+ "active",
+ "created_at",
+ "updated_at"
+ ],
+ "title": "ConnectorAccountRow",
+ "type": "object"
+ },
+ "ConnectorAccountStatus": {
+ "enum": [
+ "pending",
+ "active",
+ "failed",
+ "expired",
+ "revoked",
+ "inactive"
+ ],
+ "title": "ConnectorAccountStatus",
+ "type": "string"
+ },
+ "ConnectorAccountsParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "connector": {
+ "anyOf": [
+ {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Connector"
+ }
+ },
+ "title": "ConnectorAccountsParams",
+ "type": "object"
+ },
+ "ConnectorAccountsRemoveParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "connection_id": {
+ "minLength": 1,
+ "title": "Connection Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "connection_id"
+ ],
+ "title": "ConnectorAccountsRemoveParams",
+ "type": "object"
+ },
+ "ConnectorAccountsRemoveResult": {
+ "additionalProperties": false,
+ "properties": {
+ "connection_id": {
+ "title": "Connection Id",
+ "type": "string"
+ },
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "status": {
+ "const": "removed",
+ "title": "Status",
+ "type": "string"
+ }
+ },
+ "required": [
+ "connection_id",
+ "connector",
+ "status"
+ ],
+ "title": "ConnectorAccountsRemoveResult",
+ "type": "object"
+ },
+ "ConnectorAccountsResult": {
+ "additionalProperties": false,
+ "properties": {
+ "accounts": {
+ "items": {
+ "$ref": "#/components/schemas/ConnectorAccountRow"
+ },
+ "title": "Accounts",
+ "type": "array"
+ }
+ },
+ "required": [
+ "accounts"
+ ],
+ "title": "ConnectorAccountsResult",
+ "type": "object"
+ },
+ "ConnectorCatalogRow": {
+ "additionalProperties": false,
+ "properties": {
+ "slug": {
+ "title": "Slug",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "category": {
+ "title": "Category",
+ "type": "string"
+ },
+ "logo_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Logo Url"
+ }
+ },
+ "required": [
+ "slug",
+ "name",
+ "description",
+ "category"
+ ],
+ "title": "ConnectorCatalogRow",
+ "type": "object"
+ },
+ "ConnectorChange": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "connector",
+ "title": "Type",
+ "type": "string"
+ },
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "type",
+ "connector",
+ "enabled"
+ ],
+ "title": "ConnectorChange",
+ "type": "object"
+ },
+ "ConnectorPolicyAllowBody": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "const": "allow",
+ "title": "Mode",
+ "type": "string"
+ },
+ "connectors": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Connectors",
+ "type": "array"
+ },
+ "tools": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": "Tools",
+ "type": "object"
+ },
+ "tags": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyTags"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "mode",
+ "connectors",
+ "tools"
+ ],
+ "title": "ConnectorPolicyAllowBody",
+ "type": "object"
+ },
+ "ConnectorPolicyDenyAllBody": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "const": "deny-all",
+ "title": "Mode",
+ "type": "string"
+ }
+ },
+ "required": [
+ "mode"
+ ],
+ "title": "ConnectorPolicyDenyAllBody",
+ "type": "object"
+ },
+ "ConnectorPolicyDenyBody": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "const": "deny",
+ "title": "Mode",
+ "type": "string"
+ },
+ "disabled_connectors": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Disabled Connectors",
+ "type": "array"
+ },
+ "tools": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": "Tools",
+ "type": "object"
+ },
+ "tags": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyTags"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "mode",
+ "disabled_connectors",
+ "tools"
+ ],
+ "title": "ConnectorPolicyDenyBody",
+ "type": "object"
+ },
+ "ConnectorPolicyEffectiveAllow": {
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1,
+ "title": "Version",
+ "type": "integer"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "issued_at_ms": {
+ "title": "Issued At Ms",
+ "type": "integer"
+ },
+ "mode": {
+ "const": "allow",
+ "title": "Mode",
+ "type": "string"
+ },
+ "connectors": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Connectors",
+ "type": "array"
+ },
+ "tools": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": "Tools",
+ "type": "object"
+ },
+ "tags": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyTags"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "version",
+ "revision",
+ "issued_at_ms",
+ "mode",
+ "connectors",
+ "tools"
+ ],
+ "title": "ConnectorPolicyEffectiveAllow",
+ "type": "object"
+ },
+ "ConnectorPolicyEffectiveDeny": {
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1,
+ "title": "Version",
+ "type": "integer"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "issued_at_ms": {
+ "title": "Issued At Ms",
+ "type": "integer"
+ },
+ "mode": {
+ "const": "deny",
+ "title": "Mode",
+ "type": "string"
+ },
+ "disabled_connectors": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Disabled Connectors",
+ "type": "array"
+ },
+ "tools": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": "Tools",
+ "type": "object"
+ },
+ "tags": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyTags"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "version",
+ "revision",
+ "issued_at_ms",
+ "mode",
+ "disabled_connectors",
+ "tools"
+ ],
+ "title": "ConnectorPolicyEffectiveDeny",
+ "type": "object"
+ },
+ "ConnectorPolicyEffectiveDenyAll": {
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1,
+ "title": "Version",
+ "type": "integer"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "issued_at_ms": {
+ "title": "Issued At Ms",
+ "type": "integer"
+ },
+ "mode": {
+ "const": "deny-all",
+ "title": "Mode",
+ "type": "string"
+ }
+ },
+ "required": [
+ "version",
+ "revision",
+ "issued_at_ms",
+ "mode"
+ ],
+ "title": "ConnectorPolicyEffectiveDenyAll",
+ "type": "object"
+ },
+ "ConnectorPolicyEffectiveUnrestricted": {
+ "additionalProperties": false,
+ "properties": {
+ "version": {
+ "const": 1,
+ "title": "Version",
+ "type": "integer"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "issued_at_ms": {
+ "title": "Issued At Ms",
+ "type": "integer"
+ },
+ "mode": {
+ "const": "unrestricted",
+ "title": "Mode",
+ "type": "string"
+ }
+ },
+ "required": [
+ "version",
+ "revision",
+ "issued_at_ms",
+ "mode"
+ ],
+ "title": "ConnectorPolicyEffectiveUnrestricted",
+ "type": "object"
+ },
+ "ConnectorPolicyGetResult": {
+ "additionalProperties": false,
+ "properties": {
+ "layers": {
+ "items": {
+ "$ref": "#/components/schemas/ConnectorPolicyLayer"
+ },
+ "title": "Layers",
+ "type": "array"
+ },
+ "effective": {
+ "discriminator": {
+ "mapping": {
+ "allow": "#/components/schemas/ConnectorPolicyEffectiveAllow",
+ "deny": "#/components/schemas/ConnectorPolicyEffectiveDeny",
+ "deny-all": "#/components/schemas/ConnectorPolicyEffectiveDenyAll",
+ "unrestricted": "#/components/schemas/ConnectorPolicyEffectiveUnrestricted"
+ },
+ "propertyName": "mode"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveUnrestricted"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveDenyAll"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveAllow"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveDeny"
+ }
+ ],
+ "title": "Effective"
+ }
+ },
+ "required": [
+ "layers",
+ "effective"
+ ],
+ "title": "ConnectorPolicyGetResult",
+ "type": "object"
+ },
+ "ConnectorPolicyLayer": {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "$ref": "#/components/schemas/ConnectorPolicyLayerKind"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "body": {
+ "discriminator": {
+ "mapping": {
+ "allow": "#/components/schemas/ConnectorPolicyAllowBody",
+ "deny": "#/components/schemas/ConnectorPolicyDenyBody",
+ "deny-all": "#/components/schemas/ConnectorPolicyDenyAllBody",
+ "unrestricted": "#/components/schemas/ConnectorPolicyUnrestrictedBody"
+ },
+ "propertyName": "mode"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyUnrestrictedBody"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyDenyAllBody"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyAllowBody"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyDenyBody"
+ }
+ ],
+ "title": "Body"
+ }
+ },
+ "required": [
+ "kind",
+ "revision",
+ "body"
+ ],
+ "title": "ConnectorPolicyLayer",
+ "type": "object"
+ },
+ "ConnectorPolicyLayerKind": {
+ "enum": [
+ "org",
+ "role",
+ "member"
+ ],
+ "title": "ConnectorPolicyLayerKind",
+ "type": "string"
+ },
+ "ConnectorPolicySetParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "change": {
+ "discriminator": {
+ "mapping": {
+ "connector": "#/components/schemas/ConnectorChange",
+ "tools": "#/components/schemas/ToolsChange"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ToolsChange"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorChange"
+ }
+ ],
+ "title": "Change"
+ },
+ "expected_revision": {
+ "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$",
+ "title": "Expected Revision",
+ "type": "string"
+ }
+ },
+ "required": [
+ "change",
+ "expected_revision"
+ ],
+ "title": "ConnectorPolicySetParams",
+ "type": "object"
+ },
+ "ConnectorPolicySetResult": {
+ "additionalProperties": false,
+ "properties": {
+ "revision": {
+ "title": "Revision",
+ "type": "string"
+ },
+ "effective": {
+ "discriminator": {
+ "mapping": {
+ "allow": "#/components/schemas/ConnectorPolicyEffectiveAllow",
+ "deny": "#/components/schemas/ConnectorPolicyEffectiveDeny",
+ "deny-all": "#/components/schemas/ConnectorPolicyEffectiveDenyAll",
+ "unrestricted": "#/components/schemas/ConnectorPolicyEffectiveUnrestricted"
+ },
+ "propertyName": "mode"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveUnrestricted"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveDenyAll"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveAllow"
+ },
+ {
+ "$ref": "#/components/schemas/ConnectorPolicyEffectiveDeny"
+ }
+ ],
+ "title": "Effective"
+ }
+ },
+ "required": [
+ "revision",
+ "effective"
+ ],
+ "title": "ConnectorPolicySetResult",
+ "type": "object"
+ },
+ "ConnectorPolicyTags": {
+ "additionalProperties": false,
+ "properties": {
+ "enable": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Enable"
+ },
+ "disable": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Disable"
+ }
+ },
+ "title": "ConnectorPolicyTags",
+ "type": "object"
+ },
+ "ConnectorPolicyUnrestrictedBody": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "const": "unrestricted",
+ "title": "Mode",
+ "type": "string"
+ }
+ },
+ "required": [
+ "mode"
+ ],
+ "title": "ConnectorPolicyUnrestrictedBody",
+ "type": "object"
+ },
+ "ConnectorRow": {
+ "additionalProperties": false,
+ "properties": {
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "connected": {
+ "title": "Connected",
+ "type": "boolean"
+ },
+ "connection_status": {
+ "anyOf": [
+ {
+ "enum": [
+ "pending",
+ "active",
+ "failed",
+ "expired",
+ "revoked",
+ "inactive"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Connection Status"
+ },
+ "status_reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Status Reason"
+ },
+ "gateway_disabled_tools": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Gateway Disabled Tools",
+ "type": "array"
+ }
+ },
+ "required": [
+ "connector",
+ "enabled",
+ "connected",
+ "connection_status",
+ "status_reason",
+ "gateway_disabled_tools"
+ ],
+ "title": "ConnectorRow",
+ "type": "object"
+ },
+ "ConnectorToolFacet": {
+ "enum": [
+ "read",
+ "write",
+ "destructive",
+ "unclassified"
+ ],
+ "title": "ConnectorToolFacet",
+ "type": "string"
+ },
+ "ConnectorToolRow": {
+ "additionalProperties": false,
+ "properties": {
+ "slug": {
+ "title": "Slug",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "facet": {
+ "$ref": "#/components/schemas/ConnectorToolFacet"
+ },
+ "hints": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Hints",
+ "type": "array"
+ },
+ "categories": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Categories",
+ "type": "array"
+ },
+ "no_auth": {
+ "title": "No Auth",
+ "type": "boolean"
+ },
+ "deprecated": {
+ "title": "Deprecated",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug",
+ "name",
+ "description",
+ "facet",
+ "hints",
+ "categories",
+ "no_auth",
+ "deprecated"
+ ],
+ "title": "ConnectorToolRow",
+ "type": "object"
+ },
+ "ConnectorToolsParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "slug": {
+ "title": "Slug",
+ "type": "string"
+ },
+ "refresh": {
+ "default": false,
+ "title": "Refresh",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "slug"
+ ],
+ "title": "ConnectorToolsParams",
+ "type": "object"
+ },
+ "ConnectorToolsResult": {
+ "additionalProperties": false,
+ "properties": {
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "toolkit_version": {
+ "title": "Toolkit Version",
+ "type": "string"
+ },
+ "etag": {
+ "title": "Etag",
+ "type": "string"
+ },
+ "fetched_at": {
+ "title": "Fetched At",
+ "type": "number"
+ },
+ "source": {
+ "$ref": "#/components/schemas/ConnectorToolsSource"
+ },
+ "stale": {
+ "title": "Stale",
+ "type": "boolean"
+ },
+ "tools": {
+ "items": {
+ "$ref": "#/components/schemas/ConnectorToolRow"
+ },
+ "title": "Tools",
+ "type": "array"
+ }
+ },
+ "required": [
+ "connector",
+ "toolkit_version",
+ "etag",
+ "fetched_at",
+ "source",
+ "stale",
+ "tools"
+ ],
+ "title": "ConnectorToolsResult",
+ "type": "object"
+ },
+ "ConnectorToolsSource": {
+ "enum": [
+ "cache",
+ "network",
+ "revalidated"
+ ],
+ "title": "ConnectorToolsSource",
+ "type": "string"
+ },
+ "ConnectorsCatalogResult": {
+ "additionalProperties": false,
+ "properties": {
+ "connectors": {
+ "items": {
+ "$ref": "#/components/schemas/ConnectorCatalogRow"
+ },
+ "title": "Connectors",
+ "type": "array"
+ }
+ },
+ "required": [
+ "connectors"
+ ],
+ "title": "ConnectorsCatalogResult",
+ "type": "object"
+ },
+ "ConnectorsConnectParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "owner": {
+ "discriminator": {
+ "mapping": {
+ "account": "#/components/schemas/AccountOwner",
+ "session": "#/components/schemas/SessionOwner"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SessionOwner"
+ },
+ {
+ "$ref": "#/components/schemas/AccountOwner"
+ }
+ ],
+ "title": "Owner"
+ },
+ "connectors": {
+ "items": {
+ "pattern": "^[a-z0-9][a-z0-9_-]*$",
+ "type": "string"
+ },
+ "minItems": 1,
+ "title": "Connectors",
+ "type": "array"
+ },
+ "reconnect": {
+ "default": false,
+ "title": "Reconnect",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "owner",
+ "connectors"
+ ],
+ "title": "ConnectorsConnectParams",
+ "type": "object"
+ },
+ "ConnectorsConnectResult": {
+ "additionalProperties": false,
+ "description": "``methods_connectors._reissue`` / ``managed._off_desktop_result``: the operation the connect opened; ``status``/``note`` ride along from the tool result.",
+ "properties": {
+ "op_id": {
+ "title": "Op Id",
+ "type": "string"
+ },
+ "seq": {
+ "title": "Seq",
+ "type": "integer"
+ },
+ "deadline_at": {
+ "title": "Deadline At",
+ "type": "number"
+ },
+ "settled": {
+ "title": "Settled",
+ "type": "boolean"
+ },
+ "settled_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Settled At"
+ },
+ "settled_by": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ConnectionSettleReason"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "targets": {
+ "items": {
+ "$ref": "#/components/schemas/ConnectionOperationTarget"
+ },
+ "title": "Targets",
+ "type": "array"
+ },
+ "status": {
"anyOf": [
{
+ "enum": [
+ "initiated",
+ "settled"
+ ],
"type": "string"
},
{
@@ -8898,42 +10262,9 @@
}
],
"default": null,
- "title": "Target"
- },
- "from": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ConnectionTargetState"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "to": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ConnectionTargetState"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "actor": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ConnectionActor"
- },
- {
- "type": "null"
- }
- ],
- "default": null
+ "title": "Status"
},
- "detail": {
+ "note": {
"anyOf": [
{
"type": "string"
@@ -8943,7 +10274,7 @@
}
],
"default": null,
- "title": "Detail"
+ "title": "Note"
}
},
"required": [
@@ -8953,97 +10284,10 @@
"settled",
"targets"
],
- "title": "ConnectionUpdatePayload",
- "type": "object"
- },
- "ConnectionWakeResult": {
- "additionalProperties": false,
- "properties": {
- "status": {
- "title": "Status",
- "type": "string"
- }
- },
- "required": [
- "status"
- ],
- "title": "ConnectionWakeResult",
- "type": "object"
- },
- "ConnectorRow": {
- "additionalProperties": true,
- "description": "One ``manage_connections`` status entry after ``connector_ui_payload`` redaction; the\nconnector service owns the closed key set, so unknown metadata passes through.",
- "properties": {
- "connector": {
- "default": "",
- "title": "Connector",
- "type": "string"
- },
- "connected": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Connected"
- },
- "enabled": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Enabled"
- },
- "connectionStatus": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Connectionstatus"
- },
- "name": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Name"
- },
- "description": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Description"
- }
- },
- "title": "ConnectorRow",
+ "title": "ConnectorsConnectResult",
"type": "object"
},
- "ConnectorsConnectParams": {
+ "ConnectorsListParams": {
"additionalProperties": false,
"properties": {
"profile": {
@@ -9058,137 +10302,27 @@
"default": null,
"title": "Profile"
},
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "connectors": {
- "items": {
- "type": "string"
- },
- "title": "Connectors",
- "type": "array"
- },
- "reconnect": {
- "default": false,
- "title": "Reconnect",
- "type": "boolean"
- }
- },
- "required": [
- "session_id",
- "connectors"
- ],
- "title": "ConnectorsConnectParams",
- "type": "object"
- },
- "ConnectorsConnectResult": {
- "additionalProperties": false,
- "description": "The operation the connect opened (or re-minted on): ``tools/connectors/managed.py``\n``_off_desktop_result`` / ``methods_connectors._reissue``. ``status``/``note`` ride along from\nthe tool result when the call ran through ``manage_connections``.",
- "properties": {
- "op_id": {
- "title": "Op Id",
- "type": "string"
- },
- "seq": {
- "title": "Seq",
- "type": "integer"
- },
- "deadline_at": {
- "title": "Deadline At",
- "type": "number"
- },
- "settled": {
- "title": "Settled",
- "type": "boolean"
- },
- "settled_at": {
- "anyOf": [
- {
- "type": "number"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Settled At"
- },
- "settled_by": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ConnectionSettleReason"
+ "owner": {
+ "discriminator": {
+ "mapping": {
+ "account": "#/components/schemas/AccountOwner",
+ "session": "#/components/schemas/SessionOwner"
},
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "targets": {
- "items": {
- "$ref": "#/components/schemas/ConnectionOperationTarget"
+ "propertyName": "type"
},
- "title": "Targets",
- "type": "array"
- },
- "status": {
- "anyOf": [
+ "oneOf": [
{
- "type": "string"
+ "$ref": "#/components/schemas/SessionOwner"
},
{
- "type": "null"
+ "$ref": "#/components/schemas/AccountOwner"
}
],
- "default": null,
- "title": "Status"
- },
- "note": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Note"
+ "title": "Owner"
}
},
"required": [
- "op_id",
- "seq",
- "deadline_at",
- "settled",
- "targets"
- ],
- "title": "ConnectorsConnectResult",
- "type": "object"
- },
- "ConnectorsListParams": {
- "additionalProperties": false,
- "properties": {
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- },
- "session_id": {
- "title": "Session Id",
- "type": "string"
- }
- },
- "required": [
- "session_id"
+ "owner"
],
"title": "ConnectorsListParams",
"type": "object"
@@ -26646,6 +27780,27 @@
"title": "SessionMostRecentResult",
"type": "object"
},
+ "SessionOwner": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "session",
+ "title": "Type",
+ "type": "string"
+ },
+ "session_id": {
+ "minLength": 1,
+ "title": "Session Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "session_id"
+ ],
+ "title": "SessionOwner",
+ "type": "object"
+ },
"SessionParams": {
"additionalProperties": false,
"description": "Any method addressed at one live session.",
@@ -30854,6 +32009,21 @@
],
"default": null,
"title": "Revision"
+ },
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
}
},
"required": [
@@ -30878,6 +32048,60 @@
"title": "ToolGeneratingPayload",
"type": "object"
},
+ "ToolLabel": {
+ "additionalProperties": false,
+ "description": "``tools.tool_labels.ToolLabel`` \u2014 what one call executed through the tool_search bridge is,\nin words. Clients render ``text`` (or ``app``/``action`` in their own columns) and never parse\nthe tool name themselves.",
+ "properties": {
+ "kind": {
+ "$ref": "#/components/schemas/ToolLabelKind"
+ },
+ "app": {
+ "title": "App",
+ "type": "string"
+ },
+ "action": {
+ "title": "Action",
+ "type": "string"
+ },
+ "emoji": {
+ "title": "Emoji",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "preview": {
+ "default": "",
+ "title": "Preview",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "app",
+ "action",
+ "emoji",
+ "text",
+ "name"
+ ],
+ "title": "ToolLabel",
+ "type": "object"
+ },
+ "ToolLabelKind": {
+ "description": "Which surface one inner call of a bridged ``tool_call`` runs on.",
+ "enum": [
+ "connector",
+ "mcp",
+ "tool"
+ ],
+ "title": "ToolLabelKind",
+ "type": "string"
+ },
"ToolOutputRiskPayload": {
"additionalProperties": false,
"description": "``tool_progress._progress_output_risk``.",
@@ -31017,6 +32241,21 @@
],
"default": null,
"title": "Preview"
+ },
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
}
},
"required": [
@@ -31034,6 +32273,35 @@
"title": "ToolsAction",
"type": "string"
},
+ "ToolsChange": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "tools",
+ "title": "Type",
+ "type": "string"
+ },
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "disabled_tools": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 2000,
+ "title": "Disabled Tools",
+ "type": "array"
+ }
+ },
+ "required": [
+ "type",
+ "connector",
+ "disabled_tools"
+ ],
+ "title": "ToolsChange",
+ "type": "object"
+ },
"ToolsConfigureParams": {
"additionalProperties": false,
"description": "``names`` are toolset keys or ``server:tool`` MCP targets; with ``session_id`` the live session's\nprofile is authoritative and its agent is rebuilt.",
@@ -31520,6 +32788,21 @@
"default": null,
"title": "Args"
},
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
+ },
"reasoning": {
"anyOf": [
{
@@ -33884,6 +35167,34 @@
},
"title": "_SessionScoped",
"type": "object"
+ },
+ "ConnectorErrorReason": {
+ "type": "string",
+ "enum": [
+ "INVALID_PARAMS",
+ "NOT_OWNER",
+ "UNSUPPORTED_RUNTIME",
+ "CONNECTOR_REQUEST_FAILED",
+ "INVALID_CONNECTOR_RESPONSE",
+ "UNKNOWN_TARGET",
+ "LINK_STILL_VALID",
+ "REISSUE_REFUSED",
+ "UNKNOWN_OPERATION",
+ "INVALID_ANSWER",
+ "NEEDS_NOUS_AUTH",
+ "CONNECTOR_NOT_FOUND",
+ "TOOLS_UNAVAILABLE",
+ "CONNECTORS_UNAVAILABLE",
+ "CATALOG_UNAVAILABLE",
+ "ACCOUNTS_UNAVAILABLE",
+ "CONNECTION_NOT_FOUND",
+ "POLICY_UNAVAILABLE",
+ "POLICY_CONFLICT",
+ "FORBIDDEN_SCOPE",
+ "ORG_REQUIRED",
+ "ORG_ACCESS_DENIED",
+ "INVALID_POLICY"
+ ]
}
}
},
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index 68ff0ff2546..e165a56a45f 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -1981,6 +1981,7 @@ class CLICommandsMixin:
**{k: runtime.get(k) for k in ("api_key", "base_url", "provider", "api_mode",
"max_tokens")}, enabled_toolsets=self.enabled_toolsets,
quiet_mode=True, verbose_logging=False, session_id=task_id, platform="cli",
+ side_agent=True,
session_db=self._session_db, reasoning_config=self.reasoning_config,
service_tier=self.service_tier,
request_overrides=turn_route.get("request_overrides"),
diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.py
index 0d69b8d5f15..de69c992517 100644
--- a/hermes_cli/cli_modal_mixin.py
+++ b/hermes_cli/cli_modal_mixin.py
@@ -746,7 +746,6 @@ class CLIModalMixin:
_apply()
def _connection_callback(self, payload):
- """Collect the first setup decision, then return while operation updates repaint the panel."""
if not isinstance(payload, dict):
return None
self._capture_modal_input_snapshot()
@@ -757,12 +756,9 @@ class CLIModalMixin:
return None
state["owns_hook"] = installed
state["tool_thread_id"] = threading.current_thread().ident
- if state["phase"] == "waiting":
- return None
- response_queue = queue.Queue()
- state["response_queue"] = response_queue
- self._ring_bell(prompt=True, context="connection setup")
- return response_queue.get()
+ if state["phase"] != "waiting":
+ self._ring_bell(prompt=True, context="connection setup")
+ return None
def _connection_answer(self, *, approve: bool) -> None:
state = self._connection_state
@@ -784,10 +780,6 @@ class CLIModalMixin:
# waiting phase first so it cannot overwrite that.
state["phase"] = "waiting"
apply_answer(operation, json.dumps({"targets": [answer]}))
- response_queue = state.get("response_queue")
- if response_queue is not None:
- response_queue.put(answer["status"])
- state.pop("response_queue", None)
self._paint_now()
def _connection_retry(self) -> None:
@@ -799,6 +791,15 @@ class CLIModalMixin:
self._connection_close()
return
target = state["target"]
+ if target.get("kind") == "connector" and target.get("state") in {"failed", "expired"}:
+ from tools.connectors.run import reissue
+
+ state["phase"] = "waiting"
+ if reissue(operation, [str(target.get("name") or "")]) is not None:
+ target["detail"] = "This connection cannot be started again. Cancel and ask the agent again."
+ state["phase"] = "failed"
+ self._paint_now()
+ return
if target.get("state") in {"pending", "failed", "expired"}:
# Connect on a failed row is the same attempt with the values now in the draft.
self._connection_answer(approve=True)
diff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.py
index 611fb309605..f29ffd992cd 100644
--- a/hermes_cli/cli_stream_mixin.py
+++ b/hermes_cli/cli_stream_mixin.py
@@ -655,8 +655,9 @@ class CLIStreamMixin:
if tool_name in announced:
return
announced.add(tool_name)
- from agent.display import get_tool_emoji
- _cprint(f" ┊ {get_tool_emoji(tool_name, default='⚡')} preparing {tool_name}…")
+ from agent.display import bridge_generating_phrase, get_tool_emoji
+ what = bridge_generating_phrase(tool_name) or tool_name
+ _cprint(f" ┊ {get_tool_emoji(tool_name, default='⚡')} preparing {what}…")
def _on_tool_progress(self, event_type: str, function_name: str = None, preview: str = None, function_args: dict = None, **kwargs):
"""Tool lifecycle events (tool.started / tool.completed / reasoning.* / moa.*).
@@ -751,12 +752,12 @@ class CLIStreamMixin:
if event_type != "tool.started":
return
if function_name and not function_name.startswith("_"):
- from agent.display import get_tool_emoji, get_tool_preview_max_len
+ from agent.display import get_tool_preview_max_len, tool_row_emoji
label = preview or function_name
_pl = get_tool_preview_max_len()
if _pl > 0 and len(label) > _pl:
label = label[:_pl - 3] + "..."
- self._spinner_text = f"{get_tool_emoji(function_name)} {label}"
+ self._spinner_text = f"{tool_row_emoji(function_name, function_args)} {label}"
self._tool_start_time = time.monotonic()
# Store args for stacked scrollback line on completion
self._pending_tool_info.setdefault(function_name, []).append(
diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.py
index 04adfb464c4..b62ebfc2236 100644
--- a/hermes_cli/nous_account.py
+++ b/hermes_cli/nous_account.py
@@ -584,6 +584,12 @@ def _dict_or_empty(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
+def resolve_nous_portal_base_url() -> str:
+ from hermes_cli.auth import _nous_portal_base_url, get_provider_auth_state
+
+ return _nous_portal_base_url(get_provider_auth_state("nous") or {})
+
+
def _portal_base_url(state: dict[str, Any]) -> Optional[str]:
value = state.get("portal_base_url")
return value.strip().rstrip("/") if _nonblank(value) else None
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 0eba929e578..c5ce453a691 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -510,13 +510,40 @@ async def get_session_latest_descendant(session_id: str, profile: Optional[str]
"changed": bool(path and latest != path[0])}
+def _stored_tool_call_labels(message: dict) -> dict:
+ from agent.display import tool_labels_for_call
+ from tools.tool_labels import BRIDGE_TOOL_NAMES
+
+ out = {}
+ for call in message.get("tool_calls") or ():
+ if not isinstance(call, dict):
+ continue
+ fn = call.get("function") if isinstance(call.get("function"), dict) else {}
+ call_id, name = str(call.get("id") or ""), str(fn.get("name") or "")
+ if not call_id or name not in BRIDGE_TOOL_NAMES:
+ continue
+ try:
+ args = json.loads(fn.get("arguments") or "{}")
+ except (TypeError, ValueError):
+ args = {}
+ labels = [label.as_payload() for label in tool_labels_for_call(name, args if isinstance(args, dict) else {})]
+ if labels:
+ out[call_id] = labels
+ return out
+
+
+def _with_tool_call_labels(message: dict) -> dict:
+ labels = _stored_tool_call_labels(message)
+ return {**message, "tool_call_labels": labels} if labels else message
+
+
def _project_for_display(messages: list) -> list:
- """Replace compaction summaries with their display-only projection."""
from agent.compaction_display import project_compaction_message_for_display
from agent.context_compressor import is_compaction_summary_message
projected_messages = []
for message in messages:
+ message = _with_tool_call_labels(message)
if not is_compaction_summary_message(message):
projected_messages.append(message)
continue
diff --git a/run_agent.py b/run_agent.py
index 28f7626e170..1e6fb74ee6e 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -121,6 +121,7 @@ from model_tools import get_toolset_for_tool
from tools.terminal_tool_lifecycle import cleanup_vm, get_active_env
from tools.interrupt import set_interrupt as _set_interrupt
from tools.browser_tool_lifecycle import cleanup_browser
+from tools.connectors.turn import agent_connection_surface, scoped_connection_surface
from agent.memory_provider import is_trivial_prompt
from agent.client_lifecycle import ClientLifecycleMixin
@@ -288,6 +289,7 @@ class AIAgent(
checkpoint_max_total_size_mb: int = 500, checkpoint_max_file_size_mb: int = 10,
pass_session_id: bool = False, requested_provider: str = None,
capabilities: Dict[str, bool] | None = None, cwd: str | None = None,
+ side_agent: bool = False,
):
"""Forwarder — see ``agent.agent_init.init_agent`` (same keyword parameters, minus ``tool_delay``)."""
init_kwargs = {k: v for k, v in locals().items() if k not in ("self", "tool_delay")}
@@ -1319,19 +1321,20 @@ class AIAgent(
args = (assistant_message, messages, effective_task_id, api_call_count)
self._executing_tools = True # allow _vprint during tool execution even with stream consumers
try:
- if len(tool_calls) <= 1:
- self._execute_tool_calls_sequential(*args)
- else:
- from agent.tool_dispatch_helpers import _plan_tool_batch_segments
- active_env = get_active_env(effective_task_id)
- exec_cwd = Path(active_env.cwd) if active_env is not None and active_env.cwd else None
- segments = _plan_tool_batch_segments(tool_calls, execution_cwd=exec_cwd)
- if len(segments) == 1:
- run = self._execute_tool_calls_concurrent if segments[0][0] == "parallel" else self._execute_tool_calls_sequential
- run(*args)
+ with scoped_connection_surface(agent_connection_surface(self)):
+ if len(tool_calls) <= 1:
+ self._execute_tool_calls_sequential(*args)
else:
- from agent.tool_executor import execute_tool_calls_segmented
- execute_tool_calls_segmented(self, *args, segments=segments)
+ from agent.tool_dispatch_helpers import _plan_tool_batch_segments
+ active_env = get_active_env(effective_task_id)
+ exec_cwd = Path(active_env.cwd) if active_env is not None and active_env.cwd else None
+ segments = _plan_tool_batch_segments(tool_calls, execution_cwd=exec_cwd)
+ if len(segments) == 1:
+ run = self._execute_tool_calls_concurrent if segments[0][0] == "parallel" else self._execute_tool_calls_sequential
+ run(*args)
+ else:
+ from agent.tool_executor import execute_tool_calls_segmented
+ execute_tool_calls_segmented(self, *args, segments=segments)
finally:
self._executing_tools = False
# getattr: test stubs built without _set_defaults drive this method too
diff --git a/scripts/gen_gateway_contracts.py b/scripts/gen_gateway_contracts.py
index 476660cb663..0e40a50cee0 100644
--- a/scripts/gen_gateway_contracts.py
+++ b/scripts/gen_gateway_contracts.py
@@ -16,7 +16,7 @@ import subprocess
import sys
from collections import OrderedDict
from pathlib import Path
-from typing import Any
+from typing import Any, get_args, get_type_hints
from pydantic import TypeAdapter
from pydantic.json_schema import GenerateJsonSchema
@@ -26,10 +26,28 @@ if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from tui_gateway import contracts # noqa: E402,F401 (imports every topic module → fills the tables)
+from tui_gateway.contracts.connectors import ( # noqa: E402
+ ConnectorAccountStatus,
+ ConnectorErrorReason,
+ ConnectorToolFacet,
+ ConnectorToolsSource,
+)
+from tui_gateway.contracts.connectors_operation import ConnectionSettleReason, ConnectionTargetState # noqa: E402
from tui_gateway.contracts.registry import EVENTS, METHODS, SERVER_REQUESTS # noqa: E402
+from tools.connectors.contract import SettleReason, TargetState # noqa: E402
+from tools.connectors.gateway.wire import ConnectionStatus # noqa: E402
+from tools.connectors.portal.tools_cache import ToolsRead # noqa: E402
+from tools.connectors.portal.wire import ConnectorTool # noqa: E402
TS_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.generated.ts"
OPENRPC_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.openrpc.json"
+_ENUM_PAIRS = (
+ ("ConnectionTargetState", ConnectionTargetState, "TargetState", TargetState),
+ ("ConnectionSettleReason", ConnectionSettleReason, "SettleReason", SettleReason),
+ ("ConnectorAccountStatus", ConnectorAccountStatus, "ConnectionStatus", ConnectionStatus),
+ ("ConnectorToolFacet", ConnectorToolFacet, "ConnectorTool.facet", ConnectorTool.model_fields["facet"].annotation),
+ ("ConnectorToolsSource", ConnectorToolsSource, "ToolsRead.source", get_type_hints(ToolsRead)["source"]),
+)
HEADER = (
"// GENERATED by scripts/gen_gateway_contracts.py from tui_gateway/contracts — DO NOT EDIT.\n"
@@ -169,7 +187,28 @@ def _pascal(name: str) -> str:
return "".join(p[:1].upper() + p[1:] for p in re.split(r"[._]", name))
+def _enum_values(enum) -> set[str]:
+ values = getattr(enum, "__members__", None)
+ if values is not None:
+ return {member.value for member in values.values()}
+ if isinstance(enum, str):
+ return {enum}
+ return {value for member in get_args(enum) for value in _enum_values(member)}
+
+
+def _check_enum_parity() -> None:
+ for contract_name, contract_enum, domain_name, domain_enum in _ENUM_PAIRS:
+ contract_values = _enum_values(contract_enum)
+ domain_values = _enum_values(domain_enum)
+ if contract_values != domain_values:
+ raise ValueError(
+ f"enum parity failed: {contract_name} vs {domain_name}: "
+ f"{sorted(contract_values ^ domain_values)}"
+ )
+
+
def render_ts() -> str:
+ _check_enum_parity()
models: list[type] = []
for m in METHODS.values():
models += [m.params, m.result]
@@ -191,6 +230,11 @@ def render_ts() -> str:
out = [HEADER, "/* eslint-disable */\n", "// ── Types ──\n"]
out.extend(r.emitted.values())
+ out.append(
+ "export type ConnectorErrorReason = "
+ + r.type_of({"enum": [member.value for member in ConnectorErrorReason]})
+ + "\n"
+ )
out.append("\n// ── Client→server methods ──\n")
out.append("export interface RpcMethods {\n")
@@ -239,6 +283,7 @@ def _openrpc_schema(model: type) -> dict:
def render_openrpc() -> str:
+ _check_enum_parity()
components: dict[str, dict] = {}
all_models: list[type] = []
for m in METHODS.values():
@@ -258,6 +303,10 @@ def render_openrpc() -> str:
ref_template="#/components/schemas/{model}",
)
components = top.get("$defs", {})
+ components["ConnectorErrorReason"] = {
+ "type": "string",
+ "enum": [member.value for member in ConnectorErrorReason],
+ }
def ref(model: type) -> dict:
return {"$ref": f"#/components/schemas/{model.__name__}"}
diff --git a/tests/hermes_cli/test_cli_clarify_batch.py b/tests/hermes_cli/test_cli_clarify_batch.py
index 7658c0f911a..2e17d75b43d 100644
--- a/tests/hermes_cli/test_cli_clarify_batch.py
+++ b/tests/hermes_cli/test_cli_clarify_batch.py
@@ -237,8 +237,6 @@ class TestClarifyBatchPanel:
thread.join(timeout=2)
assert result["value"] == "a"
- # The connection modal uses the same agent-thread queue handoff. Connect sends the
- # approved target and env directly to the backend, while rendering masks secrets.
cli._connection_state = None
cli._capture_modal_input_snapshot = MagicMock()
cli._restore_modal_input_snapshot = MagicMock()
@@ -265,15 +263,14 @@ class TestClarifyBatchPanel:
target=lambda: connection_result.setdefault("value", cli._connection_callback(payload)), daemon=True
)
connection_thread.start()
- deadline = time.time() + 2
- while cli._connection_state is None and time.time() < deadline:
- time.sleep(0.01)
+ connection_thread.join(timeout=2)
+ assert not connection_thread.is_alive()
+ assert connection_result["value"] is None
state = cli._connection_state
state["drafts"]["asana"]["CLIENT_SECRET"] = "never-render-this"
assert "never-render-this" not in "\n".join(cli._connection_render_lines())
assert "Client secret*: Set" in cli._connection_render_lines()
cli._connection_answer(approve=True)
- connection_thread.join(timeout=2)
sent = json.loads(apply_answer.call_args.args[1])
assert sent == {"targets": [{
@@ -281,7 +278,6 @@ class TestClarifyBatchPanel:
"status": "approved",
"env": {"CLIENT_ID": "default-id", "CLIENT_SECRET": "never-render-this"},
}]}
- assert connection_result["value"] == "approved"
cli._connection_close()
diff --git a/tests/tools/test_connector_bridge_wiring.py b/tests/tools/test_connector_bridge_wiring.py
index de7237889ad..49f1771497d 100644
--- a/tests/tools/test_connector_bridge_wiring.py
+++ b/tests/tools/test_connector_bridge_wiring.py
@@ -11,7 +11,8 @@ import logging
import pytest
from agent.tool_dispatch_helpers import _peel_bridge_call
-from tools.connectors.gateway.bridge import connector_describe
+from tools.connectors.gateway.bridge import ConnectorLeg, connector_describe
+from tools.connectors.gateway.errors import GatewayAuthError
from tools.tool_search import (
CONNECTOR_BATCH_SENTINEL,
ToolSearchConfig,
@@ -161,7 +162,7 @@ def test_normalize_rejects_malformed_batches(bad, expected_fragment):
def _fake_connector_search(queries):
assert queries == [{"use_case": "send an email"}]
- return {
+ return ConnectorLeg(payload={
"results": [
{"index": 1, "use_case": "send an email", "tools": ["GMAIL_SEND_EMAIL", "ORPHAN_TOOL"]},
],
@@ -176,7 +177,7 @@ def _fake_connector_search(queries):
# connector it cannot compose a callable name and must be dropped.
},
"connections": [{"connector": "gmail", "connected": False, "description": ""}],
- }
+ })
def _registered_local_defs():
@@ -209,12 +210,12 @@ def test_connector_intent_is_not_starved_by_local_tools_sharing_one_word():
out = json.loads(dispatch_tool_search(
{"queries": ["send gmail email"], "limit": 5},
current_tool_defs=defs,
- connector_search=lambda q: {
+ connector_search=lambda q: ConnectorLeg(payload={
"results": [{"use_case": "send gmail email", "tools": ["GMAIL_SEND_EMAIL"]}],
"schemas": {"GMAIL_SEND_EMAIL": {
"connector": "gmail", "tool": "GMAIL_SEND_EMAIL",
"description": "Send an email via gmail", "input_schema": {}}},
- }))
+ })))
assert out["results"][0]["matches"] == ["connectors__gmail__SEND_EMAIL"]
finally:
for n in names:
@@ -231,12 +232,12 @@ def test_both_sources_answer_within_one_limit():
out = json.loads(dispatch_tool_search(
{"queries": ["tracker create issue"], "limit": 2},
current_tool_defs=defs,
- connector_search=lambda q: {
+ connector_search=lambda q: ConnectorLeg(payload={
"results": [{"use_case": "tracker create issue", "tools": ["TRACKER_CREATE_ISSUE"]}],
"schemas": {"TRACKER_CREATE_ISSUE": {
"connector": "tracker", "tool": "TRACKER_CREATE_ISSUE",
"description": "Create a tracker issue", "input_schema": {}}},
- }))
+ })))
matches = out["results"][0]["matches"]
assert len(matches) == 2
assert set(matches) == {"mcp__tracker__create_issue", "connectors__tracker__CREATE_ISSUE"}
@@ -250,7 +251,7 @@ def test_search_composes_lowercase_connector_from_vendor_cased_schema():
# custom toolkits; the composed name must carry the lowercase catalog
# form or the gateway's own policy gates refuse the call.
def cased_search(queries):
- return {
+ return ConnectorLeg(payload={
"results": [{"index": 1, "tools": ["CUSTOM_X_READ"]}],
"schemas": {
"CUSTOM_X_READ": {
@@ -260,7 +261,7 @@ def test_search_composes_lowercase_connector_from_vendor_cased_schema():
"input_schema": {},
}
},
- }
+ })
out = json.loads(
dispatch_tool_search(
@@ -298,7 +299,7 @@ def test_search_keeps_only_the_twin_a_colliding_name_reaches(order, caplog):
describe the literal under a name that runs the prefixed tool, whichever the
gateway listed first, and must say so in the log rather than alias silently."""
def twins(queries):
- return {
+ return ConnectorLeg(payload={
"results": [{"index": 1, "tools": list(order)}],
"schemas": {
"GMAIL_FETCH_PROFILE": {"connector": "gmail", "tool": "GMAIL_FETCH_PROFILE",
@@ -306,7 +307,7 @@ def test_search_keeps_only_the_twin_a_colliding_name_reaches(order, caplog):
"FETCH_PROFILE": {"connector": "gmail", "tool": "FETCH_PROFILE",
"description": "literal twin", "input_schema": {}},
},
- }
+ })
with caplog.at_level(logging.WARNING, logger="tools.connectors.search"):
out = json.loads(dispatch_tool_search(
@@ -324,13 +325,13 @@ def test_search_keeps_only_the_twin_a_colliding_name_reaches(order, caplog):
def test_search_limit_caps_the_group_across_both_legs_and_counts_total():
def many_hits(queries):
slugs = [f"CUSTOM_X_TOOL_{i}" for i in range(9)]
- return {
+ return ConnectorLeg(payload={
"results": [{"index": 1, "tools": slugs}],
"schemas": {
s: {"connector": "custom_x", "tool": s, "description": "widget", "input_schema": {}}
for s in slugs
},
- }
+ })
out = json.loads(
dispatch_tool_search(
@@ -349,12 +350,12 @@ def test_search_limit_caps_the_group_across_both_legs_and_counts_total():
def test_search_drops_remote_group_with_mismatched_use_case_echo():
def misaligned(queries):
- return {
+ return ConnectorLeg(payload={
"results": [{"index": 1, "use_case": "SOMETHING ELSE", "tools": ["CUSTOM_X_READ"]}],
"schemas": {
"CUSTOM_X_READ": {"connector": "custom_x", "tool": "CUSTOM_X_READ", "description": "d", "input_schema": {}}
},
- }
+ })
out = json.loads(
dispatch_tool_search(
@@ -366,21 +367,24 @@ def test_search_drops_remote_group_with_mismatched_use_case_echo():
assert not any(m.startswith("connectors__") for m in out["results"][0]["matches"])
-def test_search_identical_to_local_only_when_remote_leg_fails():
+def test_search_keeps_local_results_and_names_the_hosted_failure():
def exploding_search(queries):
raise RuntimeError("gateway exploded")
- local_only = dispatch_tool_search(
+ local_only = json.loads(dispatch_tool_search(
{"queries": ["send an email"]},
current_tool_defs=_local_defs(),
- connector_search=lambda queries: {},
- )
- with_failure = dispatch_tool_search(
+ connector_search=lambda queries: ConnectorLeg(),
+ ))
+ with_failure = json.loads(dispatch_tool_search(
{"queries": ["send an email"]},
current_tool_defs=_local_defs(),
connector_search=exploding_search,
- )
- assert local_only == with_failure # byte-identical: D32
+ ))
+ assert "connectors" not in local_only
+ connectors = with_failure.pop("connectors")
+ assert local_only == with_failure
+ assert connectors["status"] == "unavailable" and connectors["reason"] == "unreachable"
def test_search_never_sends_the_gateway_more_use_cases_than_it_accepts():
@@ -392,7 +396,7 @@ def test_search_never_sends_the_gateway_more_use_cases_than_it_accepts():
def recording_search(use_cases):
sent.append(use_cases)
- return {}
+ return ConnectorLeg()
seven = [f"query {i}" for i in range(7)]
parsed = json.loads(dispatch_tool_search(
@@ -419,7 +423,8 @@ def test_describe_merges_remote_schema_and_leaves_misses_in_not_found():
def fake_describe(names):
assert set(names) == {composed, stale}
- return {"tools": {composed: {"description": "Send an email", "parameters": {"type": "object"}}}}
+ return ConnectorLeg(payload={
+ "tools": {composed: {"description": "Send an email", "parameters": {"type": "object"}}}})
out = json.loads(
dispatch_tool_describe(
@@ -433,17 +438,32 @@ def test_describe_merges_remote_schema_and_leaves_misses_in_not_found():
assert "errors" not in out # a connector miss is stale/unknown, not an error
-def test_describe_connector_names_fall_to_not_found_when_dark():
+def test_describe_connector_names_fall_to_not_found_when_dark_and_to_connectors_when_the_leg_fails():
composed = "connectors__gmail__SEND_EMAIL"
out = json.loads(
dispatch_tool_describe(
{"names": [composed]},
current_tool_defs=_local_defs(),
- connector_describe=lambda names: {},
+ connector_describe=lambda names: ConnectorLeg(),
)
)
assert out["not_found"] == [composed]
+ def exploding_describe(names):
+ raise RuntimeError("gateway exploded")
+
+ failed = json.loads(
+ dispatch_tool_describe(
+ {"names": [composed]},
+ current_tool_defs=_local_defs(),
+ connector_describe=exploding_describe,
+ )
+ )
+ assert "not_found" not in failed and "hint" not in failed
+ assert failed["connectors"]["status"] == "unavailable"
+ assert failed["connectors"]["reason"] == "unreachable"
+ assert failed["connectors"]["names"] == [composed]
+
# ---------------------------------------------------------------------------
# planner admission: only PURE connector batches are parallel-safe
@@ -658,7 +678,7 @@ def test_connector_describe_maps_slugs_back_to_composed_names():
availability=lambda: True,
client_factory=lambda: FakeClient(),
)
- assert out["tools"]["connectors__gmail__SEND_EMAIL"]["parameters"] == {"type": "object"}
+ assert out.payload["tools"]["connectors__gmail__SEND_EMAIL"]["parameters"] == {"type": "object"}
def test_connector_describe_colliding_candidate_slugs_resolve_per_name():
@@ -687,7 +707,7 @@ def test_connector_describe_colliding_candidate_slugs_resolve_per_name():
availability=lambda: True,
client_factory=lambda: FakeClient(),
)
- assert set(out["tools"]) == {
+ assert set(out.payload["tools"]) == {
"connectors__first__SECOND_X",
"connectors__second__X",
}
@@ -723,15 +743,23 @@ def test_connector_describe_prefers_each_names_prefixed_candidate():
availability=lambda: True,
client_factory=lambda: FakeClient(),
)
- assert out["tools"]["connectors__gmail__X"]["description"] == "prefixed"
+ assert out.payload["tools"]["connectors__gmail__X"]["description"] == "prefixed"
-def test_connector_describe_is_empty_on_unavailable_and_exploding_client():
- assert connector_describe(["connectors__g__T"], availability=lambda: False) == {}
+def test_connector_describe_is_empty_on_unavailable_and_names_the_failure_reason():
+ off = connector_describe(["connectors__g__T"], availability=lambda: False)
+ assert off == ConnectorLeg()
def boom():
raise RuntimeError("boom")
assert connector_describe(
["connectors__g__T"], availability=lambda: True, client_factory=boom
- ) == {}
+ ) == ConnectorLeg(failure="unreachable")
+
+ def rejected():
+ raise GatewayAuthError("token rejected", code="UNAUTHORIZED", status=401)
+
+ assert connector_describe(
+ ["connectors__g__T"], availability=lambda: True, client_factory=rejected
+ ) == ConnectorLeg(failure="sign_in_expired")
diff --git a/tests/tools/test_connector_dispatch_policy.py b/tests/tools/test_connector_dispatch_policy.py
index cf105fb69f1..ecbcedf811d 100644
--- a/tests/tools/test_connector_dispatch_policy.py
+++ b/tests/tools/test_connector_dispatch_policy.py
@@ -117,7 +117,7 @@ def test_disabled_connections_cannot_be_called_through_a_stale_schema(monkeypatc
from tools.registry import registry
monkeypatch.setattr(config, "connectors_available", lambda: False)
- monkeypatch.setattr(managed, "_default_client",
+ monkeypatch.setattr(managed, "managed_client",
lambda: (_ for _ in ()).throw(AssertionError("disabled connector attempted I/O")))
result = json.loads(registry.dispatch("manage_connections", {"action": "connect", "connectors": ["gmail"]}))
assert "not available" in result["error"]
diff --git a/tests/tools/test_connector_session_scope.py b/tests/tools/test_connector_session_scope.py
index b8a264c2719..7a69886e6e5 100644
--- a/tests/tools/test_connector_session_scope.py
+++ b/tests/tools/test_connector_session_scope.py
@@ -46,7 +46,7 @@ def test_connector_scope_controls_schema_discovery_and_execution(monkeypatch, en
return []
monkeypatch.setattr(bridge, "_default_client_factory", Client)
- monkeypatch.setattr(managed, "_default_client", Client)
+ monkeypatch.setattr(managed, "managed_client", Client)
scope = {"enabled_toolsets": enabled, "disabled_toolsets": disabled}
defs = model_tools.get_tool_definitions(**scope, quiet_mode=True, skip_tool_search_assembly=True)
assert ("manage_connections" in {td["function"]["name"] for td in defs}) is allowed
diff --git a/tests/tools/test_connectors_gateway_client.py b/tests/tools/test_connectors_gateway_client.py
index 5df0142ea0e..5cd43431cf2 100644
--- a/tests/tools/test_connectors_gateway_client.py
+++ b/tests/tools/test_connectors_gateway_client.py
@@ -10,7 +10,7 @@ from dataclasses import replace as dataclass_replace
import pytest
-from tools.connectors.gateway.bridge import connector_search_hits
+from tools.connectors.gateway.bridge import ConnectorLeg, connector_search_hits
from tools.connectors.gateway.client import ConnectorClient
from tools.connectors.gateway.errors import (
GatewayAuthError,
@@ -237,10 +237,10 @@ def test_connection_required_stays_inside_the_200_envelope():
# ---------------------------------------------------------------------------
-def test_search_hits_empty_on_unavailable_dark_gateway_and_exploding_client():
+def test_search_hits_empty_on_unavailable_dark_gateway_and_names_a_real_failure():
assert connector_search_hits(
[{"use_case": "send mail"}], availability=lambda: False
- ) == {}
+ ) == ConnectorLeg()
def dark_factory():
raise GatewayUnavailable("dark", code="NOT_FOUND", status=404)
@@ -251,7 +251,7 @@ def test_search_hits_empty_on_unavailable_dark_gateway_and_exploding_client():
availability=lambda: True,
client_factory=dark_factory,
)
- == {}
+ == ConnectorLeg()
)
def boom_factory():
@@ -263,7 +263,31 @@ def test_search_hits_empty_on_unavailable_dark_gateway_and_exploding_client():
availability=lambda: True,
client_factory=boom_factory,
)
- == {}
+ == ConnectorLeg(failure="unreachable")
+ )
+
+ def rejected_factory():
+ raise GatewayAuthError("token rejected", code="UNAUTHORIZED", status=401)
+
+ assert (
+ connector_search_hits(
+ [{"use_case": "send mail"}],
+ availability=lambda: True,
+ client_factory=rejected_factory,
+ )
+ == ConnectorLeg(failure="sign_in_expired")
+ )
+
+ def forbidden_factory():
+ raise GatewayAuthError("no entitlement", code="FORBIDDEN", status=403)
+
+ assert (
+ connector_search_hits(
+ [{"use_case": "send mail"}],
+ availability=lambda: True,
+ client_factory=forbidden_factory,
+ )
+ == ConnectorLeg()
)
@@ -273,12 +297,13 @@ def test_search_hits_pass_through_on_success():
assert queries == [{"use_case": "send mail"}]
return {"results": [{"index": 1, "use_case": "send mail"}]}
- hits = connector_search_hits(
+ leg = connector_search_hits(
[{"use_case": "send mail"}],
availability=lambda: True,
client_factory=lambda: FakeClient(),
)
- assert hits["results"][0]["use_case"] == "send mail"
+ assert leg.failure is None
+ assert leg.payload["results"][0]["use_case"] == "send mail"
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_connectors_gateway_wire.py b/tests/tools/test_connectors_gateway_wire.py
index 9382310226a..34569906c99 100644
--- a/tests/tools/test_connectors_gateway_wire.py
+++ b/tests/tools/test_connectors_gateway_wire.py
@@ -6,6 +6,7 @@ from pydantic import ValidationError
from tools.connectors.gateway import wire
from tools.connectors.gateway.merge import partition_calls, splice_remote_results
+from tools.connectors.turn import CARD, LINK, SIDE, scoped_connection_surface
def test_connections_result_carries_status_reason_under_either_spelling():
@@ -39,16 +40,24 @@ def _connection_required_entry():
return entry["error"]
-def test_connection_required_on_desktop_names_the_card_and_drops_the_url(monkeypatch):
- monkeypatch.setattr("tools.connectors.gateway.merge.session_platform", lambda: "desktop")
- error = _connection_required_entry()
+def test_connection_required_with_a_card_or_in_a_side_agent_carries_no_link():
+ with scoped_connection_surface(CARD):
+ error = _connection_required_entry()
assert error["connector"] == "gmail"
assert error["connect_card_available"] is True
assert "connect_url" not in error
+ assert "manage_connections" in error["hint"]
+ with scoped_connection_surface(SIDE):
+ side = _connection_required_entry()
+ assert "connect_url" not in side
+ assert "connect_card_available" not in side
+ assert "Only the main agent" in side["hint"]
-def test_connection_required_off_desktop_keeps_the_url(monkeypatch):
- monkeypatch.setattr("tools.connectors.gateway.merge.session_platform", lambda: "tui")
- error = _connection_required_entry()
+
+def test_connection_required_without_a_card_keeps_the_url():
+ with scoped_connection_surface(LINK):
+ error = _connection_required_entry()
assert error["connect_url"] == "https://example.test/connect/abc"
+ assert error["hint"] == "then retry"
assert "connect_card_available" not in error
diff --git a/tests/tools/test_connectors_managed.py b/tests/tools/test_connectors_managed.py
index db8f536e657..9ff5c19d92b 100644
--- a/tests/tools/test_connectors_managed.py
+++ b/tests/tools/test_connectors_managed.py
@@ -37,11 +37,12 @@ class GatewayFake:
repair check only; the watcher reads accounts."""
def __init__(self, connected=(), flips=None, rows=None, mint_status="initiated", status_reason=None,
- mint_connection_id=True):
+ mint_connection_id=True, mint_overrides=None):
self.connected = set(connected)
self.flips = dict(flips or {})
self.rows = dict(rows or {})
self.mint_status = mint_status
+ self.mint_overrides = dict(mint_overrides or {})
self.status_reason = status_reason
self.mint_connection_id = mint_connection_id
self.lists = 0
@@ -57,10 +58,11 @@ class GatewayFake:
self.mints.append({"connectors": tuple(connectors), "reinitiate": reinitiate, "return_to": return_to, "op": op})
results = []
for slug in connectors:
- row = {"connector": slug, "status": self.mint_status, "reinitiated": reinitiate}
- if self.mint_status == "initiated":
+ status = self.mint_overrides.get(slug, self.mint_status)
+ row = {"connector": slug, "status": status, "reinitiated": reinitiate}
+ if status == "initiated":
row["connect_url"] = f"https://connect.example/{slug}/{len(self.mints)}"
- if self.mint_connection_id and self.mint_status in ("initiated", "active"):
+ if self.mint_connection_id and status in ("initiated", "active"):
connection_id = f"ca_{slug}_{len(self.mints)}"
self.slug_of[connection_id] = slug
row["connection_id"] = connection_id
@@ -206,13 +208,45 @@ def test_respond_from_the_card_skips_a_target_and_wakes_the_loop():
assert out["settled_by"] == "all_resolved"
-def test_mint_failure_detail_survives_the_generic_list_copy():
+def test_mint_failure_detail_survives_and_only_an_unlisted_catalog_name_is_misrouted():
gw = GatewayFake(mint_status="failed", status_reason="vendor: bad scope")
- with patch("tools.connectors.operation.OPERATION_DEADLINE_SECONDS", 0.05):
- out = _run({"action": "connect", "connectors": ["gmail"]}, gw, callback=_desktop_callback(), tick=0.01)
- target = out["targets"][0]
- assert target["state"] == "not_connected" # failed is unresolved; deadline stamped it
- assert target["detail"] == "vendor: bad scope"
+ with patch("tools.connectors.operation.OPERATION_DEADLINE_SECONDS", 0.05), \
+ patch("tools.connectors.managed.catalog_names", return_value={"notion"}), \
+ patch("tools.connectors.managed.hosted_names", return_value={"gmail", "notion"}):
+ out = _run({"action": "connect", "connectors": ["gmail", "notion"]}, gw,
+ callback=_desktop_callback(), tick=0.01)
+ by = {t["name"]: t for t in out["targets"]}
+ assert by["gmail"]["state"] == "not_connected"
+ assert by["gmail"]["detail"] == "vendor: bad scope"
+ assert by["notion"]["detail"] == "vendor: bad scope"
+
+ gw = GatewayFake(flips={"gmail": 1}, mint_overrides={"notion": "failed"})
+ card = _desktop_callback()
+ with patch("tools.connectors.operation.OPERATION_DEADLINE_SECONDS", 0.2), \
+ patch("tools.connectors.managed.catalog_names", return_value={"notion"}), \
+ patch("tools.connectors.managed.hosted_names", return_value={"gmail"}):
+ out = _run({"action": "connect", "connectors": ["gmail", "notion"]}, gw, callback=card, tick=0.01)
+ by = {t["name"]: t for t in out["targets"]}
+ assert len(gw.mints) == 1 and card.seen
+ assert by["gmail"]["state"] == "connected"
+ assert by["notion"]["detail"].startswith("notion is a local MCP server")
+
+ gw = GatewayFake(mint_status="failed")
+ card = _desktop_callback()
+ with patch("tools.connectors.operation.OPERATION_DEADLINE_SECONDS", 30.0), \
+ patch("tools.connectors.managed.catalog_names", return_value={"notion"}), \
+ patch("tools.connectors.managed.hosted_names", return_value=set()):
+ out = _run({"action": "connect", "connectors": ["notion"]}, gw, callback=card, tick=0.01)
+ assert card.seen == [] and out["settled_by"] == "all_resolved"
+ assert out["targets"][0]["detail"].startswith("notion is a local MCP server")
+
+ gw = GatewayFake(mint_status="failed", status_reason="gateway hiccup")
+ with patch("tools.connectors.operation.OPERATION_DEADLINE_SECONDS", 0.05), \
+ patch("tools.connectors.managed.catalog_names", return_value={"notion"}), \
+ patch("tools.connectors.managed.hosted_names", return_value=None):
+ out = _run({"action": "connect", "connectors": ["notion"]}, gw,
+ callback=_desktop_callback(), tick=0.01)
+ assert out["targets"][0]["detail"] == "gateway hiccup"
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_refresh_agent_mcp_tools.py b/tests/tools/test_refresh_agent_mcp_tools.py
index 37a2d1ba843..37e64ef7103 100644
--- a/tests/tools/test_refresh_agent_mcp_tools.py
+++ b/tests/tools/test_refresh_agent_mcp_tools.py
@@ -47,6 +47,16 @@ def test_refresh_adds_late_landing_tools(monkeypatch):
assert "mcp_granola_get_account_info" in agent.valid_tool_names
assert len(agent.tools) == 3
+ side = _agent(["read_file", "terminal"])
+ side.side_agent = True
+ monkeypatch.setattr(model_tools, "get_tool_definitions",
+ lambda **kw: new_defs + [_tool("manage_connections")])
+
+ _mcp_agent.refresh_agent_mcp_tools(side)
+
+ assert "manage_connections" not in side.valid_tool_names
+ assert "manage_connections" not in [t["function"]["name"] for t in side.tools]
+
def test_refresh_preserves_memory_provider_and_context_engine_tools(monkeypatch):
"""B1 regression: a rebuild must NOT drop post-build-injected tools.
diff --git a/tests/tui_gateway/test_connector_operation_e2e.py b/tests/tui_gateway/test_connector_operation_e2e.py
index 49d1e217645..2b63435ef22 100644
--- a/tests/tui_gateway/test_connector_operation_e2e.py
+++ b/tests/tui_gateway/test_connector_operation_e2e.py
@@ -148,17 +148,27 @@ def owned_session(monkeypatch, tmp_path):
def _rpc(client, method, **params):
+ with client._frames_lock:
+ before = len(client.frames)
response = server.dispatch(
{
"jsonrpc": "2.0",
"id": 7,
"method": method,
- "params": {"session_id": SID, **params},
+ "params": {"owner": {"type": "session", "session_id": SID}, **params},
},
client.transport,
)
- assert response is not None
- return response
+ if response is not None:
+ return response
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ with client._frames_lock:
+ replies = [frame for frame in client.frames[before:] if frame.get("id") == 7]
+ if replies:
+ return replies[-1]
+ time.sleep(0.01)
+ raise AssertionError("no reply")
def test_desktop_connect_settles_through_callback_response(owned_session, monkeypatch):
diff --git a/tests/tui_gateway/test_connector_operation_rpc.py b/tests/tui_gateway/test_connector_operation_rpc.py
index fc7723e7dec..32f79c7a8f4 100644
--- a/tests/tui_gateway/test_connector_operation_rpc.py
+++ b/tests/tui_gateway/test_connector_operation_rpc.py
@@ -71,8 +71,18 @@ def owned(monkeypatch):
def _rpc(client, method, **params):
- return server.dispatch({"jsonrpc": "2.0", "id": 7, "method": method, "params": {"session_id": SID, **params}},
- client.transport)
+ before = len(client.frames)
+ response = server.dispatch({"jsonrpc": "2.0", "id": 7, "method": method,
+ "params": {"owner": {"type": "session", "session_id": SID}, **params}}, client.transport)
+ if response is not None:
+ return response
+ deadline = time.time() + 2
+ while time.time() < deadline:
+ replies = [frame for frame in list(client.frames)[before:] if frame.get("id") == 7]
+ if replies:
+ return replies[-1]
+ time.sleep(0.01)
+ raise AssertionError("no reply")
def _connect_rpc(client, **params):
diff --git a/tools/connectors/account.py b/tools/connectors/account.py
new file mode 100644
index 00000000000..bbeb0644192
--- /dev/null
+++ b/tools/connectors/account.py
@@ -0,0 +1,82 @@
+from __future__ import annotations
+
+import contextvars
+import threading
+import uuid
+from dataclasses import dataclass, field
+
+from tools.connectors import live
+from tools.connectors import managed
+from tools.connectors.operation import ConnectionOperation, Target
+from tools.connectors.run import drive_operation
+
+
+_PREPARE_WAIT_SECONDS = 31.0
+_start_lock = threading.Lock()
+
+
+@dataclass
+class AccountOperationStart:
+ operation: ConnectionOperation
+ started: bool
+ done: threading.Event = field(default_factory=threading.Event)
+ failed: bool = False
+
+
+def _matching_open_operation(names: list[str], *, profile_home: str | None) -> ConnectionOperation | None:
+ matches = [live.find_target(name, profile_home=profile_home) for name in names]
+ first = next((operation for operation in matches if operation is not None), None)
+ if first is None:
+ return None
+ if any(operation is not first for operation in matches):
+ raise ValueError("requested connectors do not share one open operation")
+ return first
+
+
+def find_or_start_operation(
+ names: list[str],
+ *,
+ action: str,
+ profile_home: str | None,
+) -> AccountOperationStart:
+ with _start_lock:
+ if operation := _matching_open_operation(names, profile_home=profile_home):
+ return AccountOperationStart(operation=operation, started=False)
+ operation = ConnectionOperation(
+ [Target(name, "connector", action) for name in names],
+ session_key=f"account:{uuid.uuid4().hex}",
+ )
+ started = AccountOperationStart(operation=operation, started=True)
+ context = contextvars.copy_context()
+ thread = threading.Thread(
+ target=lambda: context.run(_run, started, action),
+ daemon=True,
+ name="connector-account-operation",
+ )
+ try:
+ live.open(operation)
+ thread.start()
+ except Exception:
+ live.close(operation)
+ raise
+ return started
+
+
+def _run(start: AccountOperationStart, action: str) -> None:
+ try:
+ drive_operation(
+ start.operation,
+ managed.managed_kind(managed.managed_client(), action, force=False),
+ connection_callback=lambda _payload: start.done.set(),
+ tick_seconds=managed.WATCH_TICK_SECONDS,
+ with_urls_in_result=False,
+ )
+ except Exception:
+ live.close(start.operation)
+ start.failed = True
+ finally:
+ start.done.set()
+
+
+def wait_for_prepare(start: AccountOperationStart) -> bool:
+ return start.done.wait(_PREPARE_WAIT_SECONDS)
diff --git a/tools/connectors/gateway/bridge.py b/tools/connectors/gateway/bridge.py
index 61d283e5345..459929e74b0 100644
--- a/tools/connectors/gateway/bridge.py
+++ b/tools/connectors/gateway/bridge.py
@@ -1,22 +1,45 @@
-"""Core boundary for connector search, descriptions, and remote execution.
-
-Search and description failures degrade to no remote results; exceptions cannot escape this bridge because core dispatch bypasses registry error wrapping.
-"""
-
from __future__ import annotations
import logging
-from dataclasses import replace as dataclass_replace
+from dataclasses import dataclass, field, replace as dataclass_replace
from typing import Any, Callable, Optional, Sequence
from tools.connectors.gateway.config import connectors_available
-from tools.connectors.gateway.errors import GatewayUnavailable, ToolGatewayError
+from tools.connectors.gateway.errors import GatewayAuthError, GatewayUnavailable, ToolGatewayError
from tools.connectors.gateway.merge import fill_remote_failure, splice_remote_results
from tools.connectors.gateway.names import parse_connector_name, vendor_slug_candidates
logger = logging.getLogger(__name__)
-__all__ = ["connector_describe", "connector_search_hits", "run_remote"]
+SIGN_IN_EXPIRED = "sign_in_expired"
+UNREACHABLE = "unreachable"
+
+__all__ = [
+ "SIGN_IN_EXPIRED",
+ "UNREACHABLE",
+ "ConnectorLeg",
+ "connector_describe",
+ "connector_search_hits",
+ "run_remote",
+]
+
+
+@dataclass(frozen=True)
+class ConnectorLeg:
+
+ payload: dict[str, Any] = field(default_factory=dict)
+ failure: Optional[str] = None
+
+
+_TOKEN_REJECTED_CODES = frozenset({"UNAUTHORIZED", "INVALID_TOKEN", "TOKEN_EXPIRED"})
+
+
+def _leg_failure(exc: Exception) -> Optional[str]:
+ if isinstance(exc, GatewayAuthError):
+ if exc.status == 401 or str(exc.code).upper() in _TOKEN_REJECTED_CODES:
+ return SIGN_IN_EXPIRED
+ return None
+ return UNREACHABLE
def _default_client_factory():
@@ -30,20 +53,19 @@ def connector_search_hits(
*,
availability: Optional[Callable[[], bool]] = None,
client_factory: Optional[Callable[[], Any]] = None,
-) -> dict[str, Any]:
- """Return no hits on failure so local search behavior is unchanged."""
+) -> ConnectorLeg:
try:
available = (availability or connectors_available)()
if not available or not queries:
- return {}
+ return ConnectorLeg()
client = (client_factory or _default_client_factory)()
- return client.search(list(queries)) or {}
+ return ConnectorLeg(payload=client.search(list(queries)) or {})
except GatewayUnavailable:
logger.debug("Connector search skipped: gateway dark")
- return {}
+ return ConnectorLeg()
except Exception as exc:
- logger.debug("Connector search failed silently (D32): %s", exc)
- return {}
+ logger.debug("Connector search failed (D32): %s", exc)
+ return ConnectorLeg(failure=_leg_failure(exc))
def connector_describe(
@@ -51,12 +73,11 @@ def connector_describe(
*,
availability: Optional[Callable[[], bool]] = None,
client_factory: Optional[Callable[[], Any]] = None,
-) -> dict[str, Any]:
- """Return no schemas on failure so local descriptions are unchanged."""
+) -> ConnectorLeg:
try:
available = (availability or connectors_available)()
if not available:
- return {}
+ return ConnectorLeg()
# Resolve each name independently: candidates can overlap across composed names.
wanted: dict[str, tuple[str, ...]] = {}
request_slugs: list[str] = []
@@ -70,7 +91,7 @@ def connector_describe(
if slug not in request_slugs:
request_slugs.append(slug)
if not wanted:
- return {}
+ return ConnectorLeg()
client = (client_factory or _default_client_factory)()
response = client.schemas(request_slugs) or {}
schemas = response.get("schemas") if isinstance(response.get("schemas"), dict) else {}
@@ -87,13 +108,13 @@ def connector_describe(
"description": str(schema.get("description") or ""),
"parameters": schema.get("input_schema") or {},
}
- return {"tools": tools}
+ return ConnectorLeg(payload={"tools": tools})
except GatewayUnavailable:
logger.debug("Connector describe skipped: gateway dark")
- return {}
+ return ConnectorLeg()
except Exception as exc:
- logger.debug("Connector describe failed silently (D32): %s", exc)
- return {}
+ logger.debug("Connector describe failed (D32): %s", exc)
+ return ConnectorLeg(failure=_leg_failure(exc))
def run_remote(
diff --git a/tools/connectors/gateway/client.py b/tools/connectors/gateway/client.py
index 85de9b732cd..8657e902892 100644
--- a/tools/connectors/gateway/client.py
+++ b/tools/connectors/gateway/client.py
@@ -131,18 +131,6 @@ class ConnectorClient:
return items
raise ToolGatewayError("connector list pagination incomplete", code="INVALID_RESPONSE")
- def list_accounts(
- self, *, connector: Optional[str] = None, status: Optional[Sequence[str]] = None
- ) -> list[dict[str, Any]]:
- query = []
- if connector:
- query.append(f"connector={connector}")
- if status:
- query.append(f"status={','.join(status)}")
- path = wire.CONNECTOR_ACCOUNTS_PATH + (f"?{'&'.join(query)}" if query else "")
- page = self._parse(wire.ConnectorAccountsResponse, self._request("GET", path, None), "connector accounts")
- return [row.model_dump(by_alias=True) for row in page.accounts]
-
def account_status(
self, connection_id: str, *, timeout: float = DEFAULT_TIMEOUT_SECONDS
) -> Optional[dict[str, Any]]:
diff --git a/tools/connectors/gateway/config.py b/tools/connectors/gateway/config.py
index 68507308976..5a936e95cc2 100644
--- a/tools/connectors/gateway/config.py
+++ b/tools/connectors/gateway/config.py
@@ -119,12 +119,6 @@ def operation_session_key(session_id: Optional[str]) -> str:
def session_platform() -> str:
- """The session's surface (``desktop``, ``tui``, ``cli``, a messaging platform, or '').
-
- Decides whether a card exists for this session. Never infer that from a callback being
- attached: the GUI bridge attaches callbacks to every backend session, terminal TUI included.
- Messaging adapters bind the surface as the session platform; the desktop and TUI gateway bind
- it as the session source (``tui_gateway.server._set_session_context``), so both are read."""
from gateway.session_context import get_session_env
platform = get_session_env("HERMES_SESSION_PLATFORM", "") or get_session_env("HERMES_SESSION_SOURCE", "")
diff --git a/tools/connectors/gateway/errors.py b/tools/connectors/gateway/errors.py
index 1109732aed6..4b194dd9b7e 100644
--- a/tools/connectors/gateway/errors.py
+++ b/tools/connectors/gateway/errors.py
@@ -7,10 +7,13 @@ from __future__ import annotations
from typing import Any, Mapping, Optional
+from tools.connectors.turn import CARD, LINK, SIDE
+
__all__ = [
"GatewayAuthError",
"GatewayUnavailable",
"IdempotencyConflict",
+ "SIDE_AGENT_HINT",
"ToolGatewayError",
"parse_gateway_error",
"render_connection_required",
@@ -103,16 +106,25 @@ def parse_gateway_error(status: int, body: Any, headers: Optional[Mapping[str, A
return ToolGatewayError(message, retryable=status >= 500, **kwargs)
+SIDE_AGENT_HINT = (
+ "This app is not connected. Only the main agent can connect it, so report that back "
+ "instead of trying to connect it here."
+)
+
+CARD_HINT = (
+ "This app is not connected. Call manage_connections to open a connection card for it; "
+ "there is no link to show the user."
+)
+
+
def render_connection_required(
*,
connector: Optional[str] = None,
message: Optional[str] = None,
connect_url: Optional[str] = None,
hint: Optional[str] = None,
- card: bool = False,
+ surface: str = LINK,
) -> dict[str, Any]:
- """Single shared CONNECTION_REQUIRED shape. With a card the link stays on the panel and the
- model is told a connect card is available; without one the model relays the link."""
payload: dict[str, Any] = {
"code": "CONNECTION_REQUIRED",
"message": message
@@ -124,9 +136,14 @@ def render_connection_required(
}
if connector:
payload["connector"] = connector
- if card:
+ if surface == SIDE:
+ payload["hint"] = SIDE_AGENT_HINT
+ return payload
+ if surface == CARD:
payload["connect_card_available"] = True
- elif connect_url:
+ payload["hint"] = CARD_HINT
+ return payload
+ if connect_url:
payload["connect_url"] = connect_url
if hint:
payload["hint"] = hint
diff --git a/tools/connectors/gateway/merge.py b/tools/connectors/gateway/merge.py
index a0ec82a54d2..b7c96f22c82 100644
--- a/tools/connectors/gateway/merge.py
+++ b/tools/connectors/gateway/merge.py
@@ -8,9 +8,9 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Mapping, Optional, Sequence
-from tools.connectors.gateway.config import session_platform
from tools.connectors.gateway.errors import render_connection_required
from tools.connectors.gateway.names import parse_connector_name
+from tools.connectors.turn import connection_surface
__all__ = [
"Partition",
@@ -94,7 +94,7 @@ def render_remote_entry(planned: PlannedCall, remote: Mapping[str, Any]) -> dict
message=message,
connect_url=_opt_str(error.get("connect_url")),
hint=_opt_str(error.get("hint")),
- card=session_platform() == "desktop",
+ surface=connection_surface(),
)
else:
payload = {"code": code, "message": message}
diff --git a/tools/connectors/gateway/wire.py b/tools/connectors/gateway/wire.py
index 0a201dfcde3..73168b9bab1 100644
--- a/tools/connectors/gateway/wire.py
+++ b/tools/connectors/gateway/wire.py
@@ -163,12 +163,12 @@ class ConnectorListItem(_Wire):
connected: bool = False
connection_status: Optional[ConnectionStatus] = Field(default=None, alias="connectionStatus")
status_reason: Optional[str] = Field(default=None, alias="statusReason")
- disabled_tools: list[str] = Field(default_factory=list, alias="disabledTools")
+ gateway_disabled_tools: list[str] = Field(default_factory=list, alias="disabledTools")
class ConnectorListResponse(_Wire):
items: list[ConnectorListItem]
- next_cursor: Optional[str] = Field(alias="nextCursor")
+ next_cursor: Optional[str] = Field(default=None, alias="nextCursor")
class ConnectorAccount(_Wire):
@@ -188,6 +188,12 @@ class ConnectorAccountsResponse(_Wire):
accounts: list[ConnectorAccount]
+class RemovedConnectorAccount(_Wire):
+ connection_id: str = Field(alias="connectionId")
+ connector: str
+ status: Literal["removed"]
+
+
class ConnectorConnectionsSummary(_Wire):
total: int = 0
active: int = 0
diff --git a/tools/connectors/live.py b/tools/connectors/live.py
index 2b95a603dac..ccb9220ec5b 100644
--- a/tools/connectors/live.py
+++ b/tools/connectors/live.py
@@ -24,10 +24,14 @@ _open: Dict[Tuple[str, str], ConnectionOperation] = {}
_lock = threading.Lock()
-def _key(session_key: str, profile_home: Optional[str]) -> Tuple[str, str]:
+def _profile_key(profile_home: Optional[str]) -> str:
"""A session record names its profile home only for a non-default profile; the tool thread sees
the same home through its turn override, and the default profile through the process home."""
- return hermes_home_key(profile_home or get_process_hermes_home()), session_key
+ return hermes_home_key(profile_home or get_process_hermes_home())
+
+
+def _key(session_key: str, profile_home: Optional[str]) -> Tuple[str, str]:
+ return _profile_key(profile_home), session_key
def open(operation: ConnectionOperation) -> None: # noqa: A001 - the verb is the API
@@ -52,6 +56,21 @@ def get(session_key: str, op_id: str, *, profile_home: Optional[str] = None) ->
return operation if operation is not None and operation.op_id == op_id else None
+def get_by_op_id(op_id: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
+ profile_key = _profile_key(profile_home)
+ with _lock:
+ return next((operation for (key, _), operation in _open.items()
+ if key == profile_key and operation.op_id == op_id and not operation.settled), None)
+
+
+def find_target(name: str, *, profile_home: Optional[str] = None) -> Optional[ConnectionOperation]:
+ profile_key = _profile_key(profile_home)
+ with _lock:
+ return next((operation for (key, _), operation in _open.items()
+ if key == profile_key and not operation.settled
+ and (target := operation.target(name)) is not None and target.kind == "connector"), None)
+
+
def close(operation: ConnectionOperation) -> None:
key = (operation.profile_key, operation.session_key)
with _lock:
diff --git a/tools/connectors/managed.py b/tools/connectors/managed.py
index 6a55953bfb7..b9797a795fc 100644
--- a/tools/connectors/managed.py
+++ b/tools/connectors/managed.py
@@ -1,12 +1,3 @@
-"""Managed connectors (Nous tool gateway) on the connection operation.
-
-``connect`` mints a link for every target up front and stores it on the target; ``reconnect``
-reads status first and reinitiates only what is not connected (``force`` always reinitiates).
-On a desktop session the call blocks until the operation settles and the result carries no URL;
-the card owns the links. Off the desktop the result carries the URLs and returns at once, until
-PR3 delivers them as their own message. The watcher hook reads one route per pending target:
-that target's own account row, at 1 Hz."""
-
from __future__ import annotations
import json
@@ -14,11 +5,12 @@ import logging
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
-from tools.connectors.contract import Actor, TargetState, allowed
+from tools.connectors.contract import Actor, SettleReason, TargetState, allowed
from tools.connectors.gateway.config import operation_session_key
from tools.connectors.gateway.errors import RateLimited
-from tools.connectors.operation import ConnectionOperation, IllegalTransition, Target
+from tools.connectors.operation import ConnectionOperation, DetachedOperation, IllegalTransition, Target
from tools.connectors.run import Kind, run_operation
+from tools.connectors.targets import catalog_names, hosted_names, misrouted_to_hosted_error
from tools.registry import tool_error
logger = logging.getLogger(__name__)
@@ -45,16 +37,21 @@ _ACCOUNT_OUTCOME: Dict[str, Tuple[TargetState, Actor]] = {
NOTE = (
"Settled once. connected → use the app now; skipped → the user chose Not now, do not connect it "
- "or route around it; not_connected → ask the user what to do, never re-mint on your own."
+ "or route around it; not_connected → ask the user what to do, never re-mint on your own. "
+ "A later request from the USER for that same app is not a re-ask — run it."
)
-def _default_client():
+def managed_client():
from tools.connectors.gateway.client import ConnectorClient
return ConnectorClient()
+def managed_kind(client: Any, action: str, force: bool) -> Kind:
+ return Kind(prepare=_prepare(client, action, force), observe=lambda operation: _observe(client, operation), note=NOTE)
+
+
def _status_by_slug(client: Any) -> Dict[str, Dict[str, Any]]:
"""The toolkit list, by slug. Only the reconnect repair check reads it: it answers "is this app
already connected" before any account exists for the watcher to read."""
@@ -76,8 +73,8 @@ def mint(client: Any, operation: ConnectionOperation, names: List[str], *, reini
if target is None:
continue
status = str(entry.get("status") or "")
- detail = str(entry.get("status_reason") or entry.get("statusReason") or "")
- connection_id = entry.get("connection_id") or entry.get("connectionId")
+ detail = str(entry.get("status_reason") or "")
+ connection_id = entry.get("connection_id")
if status == "active":
operation.transition(name, TargetState.initiated, actor)
operation.transition(name, TargetState.connected, Actor.backend_watcher, connection_id=connection_id)
@@ -87,7 +84,7 @@ def mint(client: Any, operation: ConnectionOperation, names: List[str], *, reini
"only the card or the deadline can end the row", name)
operation.transition(
name, TargetState.initiated, actor,
- connect_url=entry.get("connect_url"), connection_id=connection_id, attempt=entry.get("attempt"),
+ connect_url=entry.get("connect_url"), connection_id=connection_id,
detail=detail,
)
elif target.state == TargetState.failed:
@@ -171,15 +168,37 @@ def _observe(client: Any, operation: ConnectionOperation) -> None:
_apply_read(operation, target, str(row.get("status") or "").lower(), str(row.get("statusReason") or ""))
+def _mark_misrouted(operation: ConnectionOperation) -> None:
+ unminted = [t for t in operation.targets
+ if t.state == TargetState.failed and not t.connection_id]
+ if not unminted:
+ return
+ catalog = catalog_names()
+ candidates = [t for t in unminted if t.name in catalog]
+ if not candidates:
+ return
+ hosted = hosted_names()
+ if hosted is None:
+ return
+ misrouted = [t for t in candidates if t.name not in hosted]
+ for target in misrouted:
+ operation.refresh(target.name, connect_url=None, actor=Actor.backend_watcher,
+ detail=misrouted_to_hosted_error(target.name))
+ if misrouted and len(misrouted) == len(operation.targets):
+ operation.settle(SettleReason.all_resolved)
+
+
def _prepare(client: Any, action: str, force: bool) -> Callable[[ConnectionOperation], None]:
def prepare(operation: ConnectionOperation) -> None:
names = [t.name for t in operation.targets]
if action == "connect":
mint(client, operation, names, reinitiate=False, actor=Actor.backend_watcher)
+ _mark_misrouted(operation)
return
if force:
# The re-mint names a new account; the watcher reads that one, never the old row.
mint(client, operation, names, reinitiate=True, actor=Actor.backend_watcher)
+ _mark_misrouted(operation)
return
status = _status_by_slug(client)
repair = []
@@ -190,12 +209,13 @@ def _prepare(client: Any, action: str, force: bool) -> Callable[[ConnectionOpera
else:
repair.append(name)
mint(client, operation, repair, reinitiate=True, actor=Actor.backend_watcher)
+ _mark_misrouted(operation)
return prepare
-def _off_desktop_result(client: Any, action: str, names: List[str], force: bool, session_id: str) -> str:
- operation = ConnectionOperation([Target(n, "connector", action) for n in names], session_key=session_id)
+def _no_card_result(client: Any, action: str, names: List[str], force: bool, session_id: str) -> str:
+ operation = DetachedOperation([Target(n, "connector", action) for n in names], session_key=session_id)
_prepare(client, action, force)(operation)
payload = operation.result(with_urls=True)
payload["status"] = "initiated" if any(t.state == TargetState.initiated for t in operation.targets) else "settled"
@@ -220,7 +240,7 @@ def run_managed_action(
if connectors_available is not None and not connectors_available():
return tool_error("Connectors are not available in this session.")
try:
- client = (client_factory or _default_client)()
+ client = (client_factory or managed_client)()
if action == "status":
items = client.list_connectors()
if connectors:
@@ -237,10 +257,10 @@ def run_managed_action(
force = bool(args.get("force", False))
session_key = operation_session_key(session_id)
if connection_callback is None:
- return _off_desktop_result(client, action, connectors, force, session_key)
+ return _no_card_result(client, action, connectors, force, session_key)
return run_operation(
[Target(n, "connector", action) for n in connectors],
- Kind(prepare=_prepare(client, action, force), observe=lambda op: _observe(client, op), note=NOTE),
+ managed_kind(client, action, force),
session_key=session_key, tool_call_id=tool_call_id, tick_seconds=WATCH_TICK_SECONDS,
connection_callback=connection_callback, with_urls_in_result=False,
)
diff --git a/tools/connectors/mcp.py b/tools/connectors/mcp.py
index 9276310dc61..0fca8aca392 100644
--- a/tools/connectors/mcp.py
+++ b/tools/connectors/mcp.py
@@ -1,12 +1,3 @@
-"""MCP targets of ``manage_connections``: the backend installs, enables and authorizes; the card is
-a projection of the operation and may only say approved, skipped or continue.
-
-An MCP target runs the same ``run.py`` lifecycle a managed connector runs. ``prepare`` starts an
-OAuth flow, or records the credentials an install still needs; the card's approval starts the
-install or the enable; ``observe`` reads the outcome on every tick. A session that attaches no
-connection callback runs every action at once and receives the authorization URL in the result.
-"""
-
from __future__ import annotations
import contextlib
@@ -20,8 +11,9 @@ from typing import Any, Callable, Dict, List, Optional
from tools.connectors.contract import Actor, SettleReason, TargetState
from tools.connectors.gateway.config import operation_session_key
-from tools.connectors.operation import ConnectionOperation, IllegalTransition, Target
+from tools.connectors.operation import ConnectionOperation, DetachedOperation, IllegalTransition, Target
from tools.connectors.run import Kind, run_operation
+from tools.connectors.targets import hosted_names, misrouted_to_mcp_error
from tools.registry import tool_error
logger = logging.getLogger(__name__)
@@ -31,20 +23,22 @@ logger = logging.getLogger(__name__)
PREPARE_WAIT_SECONDS = 30.0
NOTE = (
- "Settled once; do not re-ask for any target the user skipped or that timed out. Connected "
+ "Settled once; do not re-ask on your own for any target the user skipped or that timed out, but "
+ "a later request from the USER for that same app is not a re-ask — run it. Connected "
"targets' tools are available now through tool_describe/tool_call and are named under "
"tools_listing. A target with discovery_error is authorized but its tools are unavailable; "
"retry discovery with manage_connections using that target's authorize or install action "
"without asking for consent again."
)
-OFF_DESKTOP_NOTE = (
- "No connection callback is attached in this session. Show any connect_url to the user so they "
+NO_CARD_NOTE = (
+ "No connection card is drawn for this turn. Show any connect_url to the user so they "
"open it in a browser, then ask them to say when they are done. Connected targets' tools are "
"available now through tool_describe/tool_call and are named under tools_listing. A target with "
"discovery_error is authorized but its tools are unavailable; retry discovery with "
"manage_connections using that target's authorize or install action without asking for consent "
- "again. Do not re-ask for skipped or timed-out targets."
+ "again. Do not re-ask on your own for skipped or timed-out targets, but a later request from "
+ "the USER for that same app is not a re-ask — run it."
)
@@ -70,6 +64,12 @@ def validate_mcp_names(action: str, names: List[str]) -> Optional[str]:
unknown = [n for n in names if n not in allowed]
if not unknown:
return None
+ foreign = [n for n in unknown if n not in catalog and n not in configured]
+ if foreign:
+ hosted = hosted_names() or set()
+ misrouted = [n for n in foreign if n in hosted]
+ if misrouted:
+ return " ".join(misrouted_to_mcp_error(action, name) for name in misrouted)
if action == "install":
return (
f"unknown MCP server(s) for install: {', '.join(unknown)}. Install works for "
@@ -674,7 +674,7 @@ _PREPARE = {"authorize": _start_oauth, "install": _declare_env, "enable": _nothi
_APPROVE = {"authorize": _nothing, "install": _start_install, "enable": _do_enable}
_RETRY = {"authorize": _start_oauth, "install": _start_install, "enable": _do_enable}
_OBSERVE = {"authorize": _observe_oauth, "install": _observe_install, "enable": _observe_worker}
-_OFF_DESKTOP = {"authorize": _start_oauth, "install": _install_now, "enable": _do_enable}
+_NO_CARD = {"authorize": _start_oauth, "install": _install_now, "enable": _do_enable}
# ---------------------------------------------------------------------------
@@ -763,21 +763,13 @@ def retry(operation: ConnectionOperation, names: List[str]) -> Optional[str]:
# ---------------------------------------------------------------------------
-class _DetachedOperation(ConnectionOperation):
- """The operation behind an off-desktop call. It is never registered in ``live`` and no card
- renders it, so it publishes no ``connection.update``: a frame would reach a session whose
- renderer knows nothing about the operation."""
-
- on_change = None
-
-
-def _off_desktop_result(runner: _Runner, names: List[str], action: str, session_key: str) -> str:
- operation = _DetachedOperation([Target(n, "mcp", action) for n in names], session_key=session_key)
+def _no_card_result(runner: _Runner, names: List[str], action: str, session_key: str) -> str:
+ operation = DetachedOperation([Target(n, "mcp", action) for n in names], session_key=session_key)
for target in operation.targets:
- runner.run(_OFF_DESKTOP, operation, target)
+ runner.run(_NO_CARD, operation, target)
payload = operation.result(with_urls=True)
payload["status"] = "initiated" if any(t.state == TargetState.initiated for t in operation.targets) else "settled"
- payload["note"] = OFF_DESKTOP_NOTE
+ payload["note"] = NO_CARD_NOTE
return json.dumps(payload, ensure_ascii=False)
@@ -798,7 +790,7 @@ def run_mcp_operation(
# Every interactive surface that renders the card attaches this callback. Registry dispatch and
# messaging sessions attach none, so they receive the link instead of opening an unanswerable op.
if connection_callback is None:
- return _off_desktop_result(runner, names, action, session_key)
+ return _no_card_result(runner, names, action, session_key)
try:
return run_operation(
[Target(n, "mcp", action) for n in names],
diff --git a/tools/connectors/operation.py b/tools/connectors/operation.py
index b2a20e741fc..f908da5d367 100644
--- a/tools/connectors/operation.py
+++ b/tools/connectors/operation.py
@@ -209,14 +209,15 @@ class ConnectionOperation:
return dict(self._settled_snapshot, targets=targets)
return self._snapshot_locked(with_urls=with_urls)
- def result(self, *, with_urls: bool = True) -> Dict[str, Any]:
- """The settled model result, or the live snapshot before settlement.
+ def snapshot(self, *, with_urls: bool = True) -> Dict[str, Any]:
+ with self._lock:
+ return self._result_locked(with_urls=with_urls)
- Deferred MCP listings are model-only result data. Change frames and request payloads use
- the internal snapshots, so renderers never receive the catalog block.
- """
+ def result(self, *, with_urls: bool = True) -> Dict[str, Any]:
with self._lock:
result = self._result_locked(with_urls=with_urls)
+ for target in result["targets"]:
+ target.pop("connection_id", None)
if result.get("settled_at") is None:
return result
from tools.registry import registry
@@ -252,3 +253,8 @@ class ConnectionOperation:
if self.tool_call_id:
payload["tool_call_id"] = self.tool_call_id
return payload
+
+
+class DetachedOperation(ConnectionOperation):
+
+ on_change = None
diff --git a/tools/connectors/portal/__init__.py b/tools/connectors/portal/__init__.py
new file mode 100644
index 00000000000..2ae28399f5f
--- /dev/null
+++ b/tools/connectors/portal/__init__.py
@@ -0,0 +1 @@
+pass
diff --git a/tools/connectors/portal/client.py b/tools/connectors/portal/client.py
new file mode 100644
index 00000000000..6bed3662b32
--- /dev/null
+++ b/tools/connectors/portal/client.py
@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Any, Callable, Mapping, Protocol
+from urllib.parse import quote
+
+import requests
+from pydantic import ValidationError
+
+from hermes_cli.nous_account import resolve_nous_portal_base_url
+from tools.connectors.gateway.errors import (
+ GatewayAuthError,
+ GatewayUnavailable,
+ ToolGatewayError,
+ parse_gateway_error,
+)
+from tools.connectors.gateway.wire import ConnectorAccountsResponse, RemovedConnectorAccount
+from tools.connectors.portal.errors import InvalidConnectorSlug, PortalConnectorUnavailable, PortalToolsUnavailable
+from tools.connectors.portal.wire import (
+ ConnectorCatalogResponse,
+ ConnectorPolicyResponse,
+ ConnectorPolicyWriteResponse,
+ ConnectorToolsListing,
+)
+from tools.managed_gateway_auth import read_nous_access_token
+
+
+DEFAULT_TIMEOUT_SECONDS = 30.0
+_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
+
+
+class Transport(Protocol):
+ def request(
+ self,
+ method: str,
+ url: str,
+ *,
+ headers: dict[str, str] | None = None,
+ json: dict[str, Any] | None = None,
+ timeout: float | None = None,
+ ) -> Any: ...
+
+
+@dataclass(frozen=True)
+class NotModified:
+ pass
+
+
+def validate_slug(slug: str) -> None:
+ if not _SLUG_RE.fullmatch(slug):
+ raise InvalidConnectorSlug("connector must be a slug")
+
+
+def _default_transport() -> Transport:
+ return requests
+
+
+def _default_endpoint_resolver() -> str:
+ return resolve_nous_portal_base_url()
+
+
+def _default_header_provider(_url: str) -> dict[str, str]:
+ token = read_nous_access_token()
+ return {"Authorization": f"Bearer {token}"} if isinstance(token, str) and token.strip() else {}
+
+
+class PortalConnectorClient:
+
+ def __init__(
+ self,
+ *,
+ transport: Transport | None = None,
+ endpoint_resolver: Callable[[], str] | None = None,
+ header_provider: Callable[[str], dict[str, str]] | None = None,
+ ) -> None:
+ self._transport = transport or _default_transport()
+ self._endpoint_resolver = endpoint_resolver or _default_endpoint_resolver
+ self._header_provider = header_provider or _default_header_provider
+
+ def origin(self) -> str:
+ return self._endpoint_resolver().rstrip("/")
+
+ def require_authentication(self) -> None:
+ self._authorized_headers(self.origin())
+
+ def authorization_token(self) -> str | None:
+ authorization = self._authorized_headers(self.origin()).get("Authorization")
+ if not isinstance(authorization, str):
+ return None
+ scheme, _, token = authorization.partition(" ")
+ return token.strip() if scheme.lower() == "bearer" and token.strip() else None
+
+ def _authorized_headers(self, url: str, extra: dict[str, str] | None = None) -> dict[str, str]:
+ headers = {"Accept": "application/json", **(extra or {}), **self._header_provider(url)}
+ if not isinstance(headers.get("Authorization"), str) or not headers["Authorization"].strip():
+ raise GatewayAuthError("portal authorization required", code="NO_TOKEN", status=401)
+ return headers
+
+ def tools(self, slug: str, *, if_none_match: str | None = None) -> ConnectorToolsListing | NotModified:
+ validate_slug(slug)
+ headers = {"If-None-Match": if_none_match} if if_none_match else None
+ try:
+ response, status = self._request("GET", f"/api/v1/connectors/{slug}/tools", headers=headers)
+ except ToolGatewayError as exc:
+ missing_route = isinstance(exc, GatewayUnavailable) and exc.code != "connector_not_found"
+ if type(exc) is not ToolGatewayError and not missing_route:
+ raise
+ raise PortalToolsUnavailable(
+ "portal tools unavailable",
+ code=exc.code,
+ status=exc.status,
+ request_id=exc.request_id,
+ retryable=exc.retryable,
+ ) from exc
+ if status == 304:
+ return NotModified()
+ listing = self._parse(ConnectorToolsListing, response, status, PortalToolsUnavailable, "portal tools unavailable")
+ etag = getattr(response, "headers", {}).get("etag")
+ return listing.model_copy(update={"etag": etag}) if isinstance(etag, str) and etag else listing
+
+ def catalog(self) -> ConnectorCatalogResponse:
+ response, status = self._request("GET", "/api/v1/connectors/catalog")
+ return self._parse(ConnectorCatalogResponse, response, status, PortalConnectorUnavailable, "portal catalog unavailable")
+
+ def list_accounts(self) -> list[dict[str, Any]]:
+ response, status = self._request("GET", "/api/v1/connectors/accounts")
+ inventory = self._parse(ConnectorAccountsResponse, response, status, PortalConnectorUnavailable, "portal accounts unavailable")
+ return [account.model_dump(by_alias=True) for account in inventory.accounts]
+
+ def delete_account(self, connection_id: str) -> dict[str, Any]:
+ path = f"/api/v1/connectors/accounts/{quote(connection_id, safe='')}"
+ response, status = self._request("DELETE", path)
+ removed = self._parse(RemovedConnectorAccount, response, status, PortalConnectorUnavailable, "portal accounts unavailable")
+ return removed.model_dump(by_alias=True)
+
+ def policy(self) -> ConnectorPolicyResponse:
+ response, status = self._request("GET", "/api/v1/connectors/policy")
+ return self._parse(ConnectorPolicyResponse, response, status, PortalConnectorUnavailable, "portal policy unavailable")
+
+ def set_policy(self, body: dict[str, Any]) -> ConnectorPolicyWriteResponse:
+ response, status = self._request("PUT", "/api/v1/connectors/policy", body)
+ return self._parse(ConnectorPolicyWriteResponse, response, status, PortalConnectorUnavailable, "portal policy unavailable")
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ body: dict[str, Any] | None = None,
+ *,
+ headers: dict[str, str] | None = None,
+ ) -> tuple[Any, int]:
+ url = f"{self.origin()}{path}"
+ headers = self._authorized_headers(url, headers)
+ try:
+ response = self._transport.request(method, url, headers=headers, json=body, timeout=DEFAULT_TIMEOUT_SECONDS)
+ except Exception as exc:
+ raise PortalConnectorUnavailable("portal connector metadata unavailable", code="TRANSPORT_ERROR", retryable=True) from exc
+ status = int(getattr(response, "status_code", 0))
+ if not 200 <= status < 300 and status != 304:
+ error = parse_gateway_error(status, _safe_json(response), getattr(response, "headers", None))
+ raise error
+ return response, status
+
+ @staticmethod
+ def _parse(model, response: Any, status: int, error_type, message: str):
+ try:
+ payload = response.json()
+ if not isinstance(payload, Mapping):
+ raise ValueError("response must be an object")
+ return model.model_validate(payload)
+ except (AttributeError, TypeError, ValueError, ValidationError) as exc:
+ raise error_type(message, code="INVALID_RESPONSE", status=status) from exc
+
+
+def _safe_json(response: Any) -> Any:
+ try:
+ return response.json()
+ except Exception:
+ return None
diff --git a/tools/connectors/portal/errors.py b/tools/connectors/portal/errors.py
new file mode 100644
index 00000000000..66795299b38
--- /dev/null
+++ b/tools/connectors/portal/errors.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from tools.connectors.gateway.errors import ToolGatewayError
+
+
+class InvalidConnectorSlug(ValueError):
+ pass
+
+
+class PortalConnectorUnavailable(ToolGatewayError):
+ pass
+
+
+class PortalToolsUnavailable(PortalConnectorUnavailable):
+ pass
diff --git a/tools/connectors/portal/policy.py b/tools/connectors/portal/policy.py
new file mode 100644
index 00000000000..50f6ac1da98
--- /dev/null
+++ b/tools/connectors/portal/policy.py
@@ -0,0 +1,57 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Callable
+
+from tools.connectors.portal.client import validate_slug
+from tools.connectors.portal.errors import InvalidConnectorSlug
+from tools.connectors.portal.wire import PolicyBody, UnrestrictedPolicyBody
+
+if TYPE_CHECKING:
+ from tui_gateway.contracts.connectors import ConnectorChange, ToolsChange
+
+
+class InvalidMemberPolicy(ValueError):
+ pass
+
+
+_LAYERS: dict[str, tuple[bool, Callable[[Any], list[str]]]] = {
+ "unrestricted": (False, lambda _body: []),
+ "deny-all": (True, lambda _body: []),
+ "allow": (True, lambda body: list(body.connectors)),
+ "deny": (False, lambda body: list(body.disabled_connectors)),
+}
+
+
+def _layer(member_body: PolicyBody | None) -> tuple[str, list[str], bool]:
+ body = member_body or UnrestrictedPolicyBody(mode="unrestricted")
+ allow, values_of = _LAYERS[body.mode]
+ return "connectors" if allow else "disabledConnectors", values_of(body), allow
+
+
+def _slug(connector: str) -> str:
+ try:
+ validate_slug(connector)
+ except InvalidConnectorSlug as exc:
+ raise InvalidMemberPolicy("connector must be a slug") from exc
+ return connector
+
+
+def _validated_tools(tools: list[str]) -> list[str]:
+ if any(not tool or len(tool) > 256 for tool in tools):
+ raise InvalidMemberPolicy("disabled_tools must contain non-empty tool slugs up to 256 characters")
+ return tools
+
+
+def compose_connector_write(member_body: PolicyBody | None, change: ConnectorChange) -> dict[str, Any]:
+ connector = _slug(change.connector)
+ key, values, allow = _layer(member_body)
+ retained = [item for item in values if item != connector]
+ return {"scope": "member", key: [*retained, connector] if change.enabled == allow else retained}
+
+
+def compose_tools_write(member_body: PolicyBody | None, change: ToolsChange) -> dict[str, Any]:
+ connector = _slug(change.connector)
+ key, values, allow = _layer(member_body)
+ if (connector in values) != allow:
+ raise InvalidMemberPolicy("connector is off in the member policy")
+ return {"scope": "member", key: values, "tools": {connector: _validated_tools(change.disabled_tools)}}
diff --git a/tools/connectors/portal/tools_cache.py b/tools/connectors/portal/tools_cache.py
new file mode 100644
index 00000000000..28575fc7189
--- /dev/null
+++ b/tools/connectors/portal/tools_cache.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+import base64
+import binascii
+import hashlib
+import json
+import time
+from typing import Callable, Literal, Protocol
+
+from pydantic import ValidationError
+
+from hermes_constants import get_hermes_home
+from tools.connectors.gateway.errors import GatewayAuthError, GatewayUnavailable, ToolGatewayError
+from tools.connectors.portal.client import NotModified, validate_slug
+from tools.connectors.portal.errors import PortalToolsUnavailable
+from tools.connectors.portal.wire import ConnectorTool, ConnectorToolsListing
+from utils import atomic_json_write, read_json_or_empty
+
+
+class ToolsClient(Protocol):
+ def origin(self) -> str: ...
+
+ def authorization_token(self) -> str | None: ...
+
+ def tools(self, slug: str, *, if_none_match: str | None = None) -> ConnectorToolsListing | NotModified: ...
+
+
+TTL_SECONDS = 24 * 60 * 60
+
+
+@dataclass(frozen=True)
+class ToolsRead:
+ connector: str
+ toolkit_version: str
+ etag: str
+ fetched_at: float
+ source: Literal["cache", "network", "revalidated"]
+ stale: bool
+ tools: list[ConnectorTool]
+
+
+def _member_key(token: str | None) -> str | None:
+ if not isinstance(token, str):
+ return None
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ try:
+ payload = parts[1] + "=" * (-len(parts[1]) % 4)
+ claims = json.loads(base64.urlsafe_b64decode(payload))
+ except (binascii.Error, ValueError, UnicodeDecodeError, json.JSONDecodeError):
+ return None
+ subject = claims.get("sub") if isinstance(claims, dict) else None
+ if not isinstance(subject, str) or not subject:
+ return None
+ return hashlib.sha256(subject.encode("utf-8")).hexdigest()[:16]
+
+
+def _cache_path(origin: str, member_key: str, slug: str):
+ origin_key = hashlib.sha256(origin.encode("utf-8")).hexdigest()[:16]
+ return get_hermes_home() / "cache" / "connectors" / origin_key / member_key / f"{slug}.json"
+
+
+def _cached(path) -> ToolsRead | None:
+ raw = read_json_or_empty(path)
+ try:
+ tools = [ConnectorTool.model_validate(tool) for tool in raw["tools"]]
+ return ToolsRead(
+ connector=str(raw["connector"]),
+ toolkit_version=str(raw["toolkit_version"]),
+ etag=str(raw["etag"]),
+ fetched_at=float(raw["fetched_at"]),
+ source="cache",
+ stale=False,
+ tools=tools,
+ )
+ except (KeyError, TypeError, ValueError, ValidationError):
+ return None
+
+
+def _store(path, entry: ToolsRead) -> ToolsRead:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ atomic_json_write(
+ path,
+ {
+ "etag": entry.etag,
+ "toolkit_version": entry.toolkit_version,
+ "connector": entry.connector,
+ "tools": [tool.model_dump(by_alias=True) for tool in entry.tools],
+ "fetched_at": entry.fetched_at,
+ },
+ )
+ return entry
+
+
+def read_tools(
+ slug: str,
+ *,
+ client: ToolsClient,
+ refresh: bool = False,
+ now: Callable[[], float] = time.time,
+) -> ToolsRead:
+ validate_slug(slug)
+ member_key = _member_key(client.authorization_token())
+ if member_key is None:
+ listing = client.tools(slug)
+ if isinstance(listing, NotModified):
+ raise PortalToolsUnavailable("portal tools unavailable", code="INVALID_RESPONSE")
+ return ToolsRead(
+ connector=listing.connector,
+ toolkit_version=listing.toolkit_version,
+ etag=listing.etag,
+ fetched_at=now(),
+ source="network",
+ stale=False,
+ tools=listing.tools,
+ )
+ path = _cache_path(client.origin(), member_key, slug)
+ cached = _cached(path)
+ fetched_at = now()
+ age = fetched_at - cached.fetched_at if cached is not None else None
+ if cached is not None and not refresh and age is not None and 0 <= age < TTL_SECONDS:
+ return cached
+ try:
+ listing = client.tools(slug, if_none_match=cached.etag if cached is not None else None)
+ except GatewayUnavailable:
+ path.unlink(missing_ok=True)
+ raise
+ except GatewayAuthError:
+ raise
+ except (PortalToolsUnavailable, ToolGatewayError):
+ if cached is None:
+ raise
+ return replace(cached, stale=True)
+ if isinstance(listing, NotModified):
+ if cached is None:
+ raise PortalToolsUnavailable("portal tools unavailable", code="INVALID_RESPONSE")
+ return _store(path, replace(cached, fetched_at=fetched_at, source="revalidated"))
+ return _store(path, ToolsRead(
+ connector=listing.connector,
+ toolkit_version=listing.toolkit_version,
+ etag=listing.etag,
+ fetched_at=fetched_at,
+ source="network",
+ stale=False,
+ tools=listing.tools,
+ ))
diff --git a/tools/connectors/portal/wire.py b/tools/connectors/portal/wire.py
new file mode 100644
index 00000000000..075312b82c6
--- /dev/null
+++ b/tools/connectors/portal/wire.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+
+class _PortalWire(BaseModel):
+ model_config = ConfigDict(extra="ignore", populate_by_name=True, strict=True)
+
+
+class ConnectorTool(_PortalWire):
+ slug: str
+ name: str
+ description: str
+ facet: Literal["read", "write", "destructive", "unclassified"]
+ hints: list[str]
+ categories: list[str]
+ no_auth: bool = Field(alias="noAuth")
+ deprecated: bool
+
+ @field_validator("facet", mode="before")
+ @classmethod
+ def _unknown_facet_is_unclassified(cls, value: object) -> object:
+ if not isinstance(value, str):
+ return value
+ return value if value in {"read", "write", "destructive", "unclassified"} else "unclassified"
+
+ @field_validator("categories")
+ @classmethod
+ def _normalize_categories(cls, value: list[str]) -> list[str]:
+ return [category.lower() for category in value]
+
+
+class ConnectorToolsListing(_PortalWire):
+ connector: str
+ toolkit_version: str = Field(alias="toolkitVersion")
+ etag: str
+ tools: list[ConnectorTool]
+
+
+class ConnectorCatalogRow(_PortalWire):
+ slug: str
+ name: str
+ description: str
+ category: str
+ logo_url: str | None = Field(default=None, alias="logoUrl")
+
+
+class ConnectorCatalogResponse(_PortalWire):
+ connectors: list[ConnectorCatalogRow]
+
+
+class PolicyTags(_PortalWire):
+ enable: list[str] | None = None
+ disable: list[str] | None = None
+
+
+class UnrestrictedPolicyBody(_PortalWire):
+ mode: Literal["unrestricted"]
+
+
+class DenyAllPolicyBody(_PortalWire):
+ mode: Literal["deny-all"]
+
+
+class PolicyToolRule(_PortalWire):
+ disable: list[str] = Field(default_factory=list)
+
+
+class AllowPolicyBody(_PortalWire):
+ mode: Literal["allow"]
+ connectors: list[str]
+ tools: dict[str, PolicyToolRule] = Field(default_factory=dict)
+ tags: PolicyTags | None = None
+
+
+class DenyPolicyBody(_PortalWire):
+ mode: Literal["deny"]
+ disabled_connectors: list[str] = Field(alias="disabledConnectors")
+ tools: dict[str, PolicyToolRule] = Field(default_factory=dict)
+ tags: PolicyTags | None = None
+
+
+PolicyBody = UnrestrictedPolicyBody | DenyAllPolicyBody | AllowPolicyBody | DenyPolicyBody
+
+
+class ConnectorPolicyEffectiveBase(_PortalWire):
+ version: Literal[1]
+ revision: str
+ issued_at_ms: int = Field(alias="issuedAtMs")
+
+
+class ConnectorPolicyEffectiveUnrestricted(ConnectorPolicyEffectiveBase):
+ mode: Literal["unrestricted"]
+
+
+class ConnectorPolicyEffectiveDenyAll(ConnectorPolicyEffectiveBase):
+ mode: Literal["deny-all"]
+
+
+class ConnectorPolicyEffectiveAllow(ConnectorPolicyEffectiveBase):
+ mode: Literal["allow"]
+ connectors: list[str]
+ tools: dict[str, PolicyToolRule] = Field(default_factory=dict)
+ tags: PolicyTags | None = None
+
+
+class ConnectorPolicyEffectiveDeny(ConnectorPolicyEffectiveBase):
+ mode: Literal["deny"]
+ disabled_connectors: list[str] = Field(alias="disabledConnectors")
+ tools: dict[str, PolicyToolRule] = Field(default_factory=dict)
+ tags: PolicyTags | None = None
+
+
+ConnectorPolicyEffective = (
+ ConnectorPolicyEffectiveUnrestricted
+ | ConnectorPolicyEffectiveDenyAll
+ | ConnectorPolicyEffectiveAllow
+ | ConnectorPolicyEffectiveDeny
+)
+
+
+class ConnectorPolicyLayer(_PortalWire):
+ kind: Literal["org", "role", "member"]
+ id: str | None = None
+ body: PolicyBody = Field(discriminator="mode")
+ revision: str
+
+
+class ConnectorPolicyResponse(_PortalWire):
+ layers: list[ConnectorPolicyLayer]
+ effective: ConnectorPolicyEffective = Field(discriminator="mode")
+
+
+class ConnectorPolicyWriteResponse(_PortalWire):
+ revision: str
+ effective: ConnectorPolicyEffective = Field(discriminator="mode")
diff --git a/tools/connectors/run.py b/tools/connectors/run.py
index e2de7a4a7e0..cce49af2d18 100644
--- a/tools/connectors/run.py
+++ b/tools/connectors/run.py
@@ -11,12 +11,19 @@ from __future__ import annotations
import json
import time
from dataclasses import dataclass
-from typing import Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional, Sequence
from tools.connectors import live
from tools.connectors.contract import SettleReason
from tools.connectors.operation import ConnectionOperation, Target
+UNKNOWN_TARGET = "unknown_target"
+MIXED_KINDS = "mixed_kinds"
+LINK_STILL_VALID = "link_still_valid"
+SETTLED = "settled"
+NOT_ALLOWED = "not_allowed"
+REFUSED = "refused"
+
WATCH_INTERVAL_SECONDS = 5.0
# The interrupt flag has no wake hook, so the tick sleep is sliced and the flag read each slice.
_WAKE_SLICE_SECONDS = 0.25
@@ -34,6 +41,31 @@ class Kind:
note: str
+def reissue(operation: ConnectionOperation, names: Sequence[str]) -> Optional[str]:
+ from tools.connectors.contract import Actor, TargetState, allowed
+
+ targets = [operation.target(name) for name in names]
+ if any(target is None for target in targets):
+ return UNKNOWN_TARGET
+ if len({target.kind for target in targets}) != 1:
+ return MIXED_KINDS
+ stale = [target.name for target in targets if target.state in (TargetState.failed, TargetState.expired)]
+ if len(stale) != len(targets):
+ return LINK_STILL_VALID
+ if operation.settled:
+ return SETTLED
+ if any(allowed(target.kind, target.state, TargetState.initiated) is None for target in targets):
+ return NOT_ALLOWED
+ if targets[0].kind == "connector":
+ from tools.connectors.managed import managed_client, mint
+
+ mint(managed_client(), operation, stale, reinitiate=True, actor=Actor.user)
+ return None
+ from tools.connectors.mcp import retry
+
+ return REFUSED if retry(operation, stale) else None
+
+
def run_operation(
targets: List[Target],
kind: Kind,
@@ -55,8 +87,26 @@ def run_operation(
f"a connection operation is already open in this session ({exc.existing.op_id}); it settles "
"when the user finishes with the card, on Continue, or at its deadline. Do not start another."
)
+ return drive_operation(
+ operation,
+ kind,
+ connection_callback=connection_callback,
+ tick_seconds=tick_seconds,
+ with_urls_in_result=with_urls_in_result,
+ )
+
+
+def drive_operation(
+ operation: ConnectionOperation,
+ kind: Kind,
+ *,
+ connection_callback: Optional[Callback],
+ tick_seconds: Optional[float] = None,
+ with_urls_in_result: bool,
+) -> str:
try:
kind.prepare(operation)
+ operation.settle_if_all_resolved()
if connection_callback is not None and not operation.settled:
connection_callback(operation.request_payload())
_watch(operation, kind, tick_seconds)
diff --git a/tools/connectors/search.py b/tools/connectors/search.py
index d934a7e021a..38d5d455820 100644
--- a/tools/connectors/search.py
+++ b/tools/connectors/search.py
@@ -1,13 +1,9 @@
-"""Remote connector adapter for tool search and descriptions.
-
-Failures return no connector results so local search behavior is unchanged.
-"""
-
from __future__ import annotations
import logging
-from typing import Any, Dict, Iterable, List, Optional
+from typing import Any, Dict, Iterable, List, Optional, Tuple
+from tools.connectors.gateway.bridge import SIGN_IN_EXPIRED, UNREACHABLE
from tools.connectors.gateway.names import format_connector_name, is_connector_name, vendor_slug_candidates
from tools.tool_search_catalog import CatalogEntry, _fn, _tokenize
@@ -18,6 +14,18 @@ def connections_in_scope(tool_defs: Iterable[Dict[str, Any]]) -> bool:
return any(_fn(td).get("name") == "manage_connections" for td in tool_defs)
+def connectors_unavailable(failure: str, *, verb: str,
+ names: Optional[List[str]] = None) -> Dict[str, Any]:
+ hint = (f"Hosted connector tools could not be {verb} right now. "
+ "Do not conclude the app is missing.")
+ if failure == SIGN_IN_EXPIRED:
+ hint += " The user must sign in to Nous again."
+ field: Dict[str, Any] = {"status": "unavailable", "reason": failure, "hint": hint}
+ if names:
+ field["names"] = names
+ return field
+
+
def _connector_entry(name: str, connector: str, slug: str, schema: Dict[str, Any]) -> CatalogEntry:
description = str(schema.get("description") or "")
input_schema = schema.get("input_schema")
@@ -32,17 +40,19 @@ def _connector_entry(name: str, connector: str, slug: str, schema: Dict[str, Any
def connector_entries_by_group(
queries: List[str],
connector_search: Optional[Any] = None,
-) -> List[List[CatalogEntry]]:
- """Correlate remote response groups by position, never their wire index."""
+) -> Tuple[List[List[CatalogEntry]], Optional[str]]:
per_query: List[List[CatalogEntry]] = [[] for _ in queries]
try:
if connector_search is None:
from tools.connectors.gateway.bridge import connector_search_hits as connector_search
- hits = connector_search([{"use_case": q} for q in queries]) or {}
+ leg = connector_search([{"use_case": q} for q in queries])
+ if leg.failure:
+ return per_query, leg.failure
+ hits = leg.payload or {}
schemas = hits.get("schemas")
groups = hits.get("results")
if not isinstance(schemas, dict) or not isinstance(groups, list):
- return per_query
+ return per_query, (UNREACHABLE if hits else None)
for position, group in enumerate(groups[: len(queries)]):
if not isinstance(group, dict):
continue
@@ -72,25 +82,29 @@ def connector_entries_by_group(
picked[name] = (slug, _connector_entry(name, str(schema["connector"]), slug, schema))
per_query[position] = [entry for _, entry in picked.values()]
except Exception:
- logger.debug("connector search merge failed silently (D32)", exc_info=True)
- return [[] for _ in queries]
- return per_query
+ logger.debug("connector search merge failed (D32)", exc_info=True)
+ return [[] for _ in queries], UNREACHABLE
+ return per_query, None
def remote_schemas_for(
names: List[str],
current_tool_defs: List[Dict[str, Any]],
connector_describe: Optional[Any] = None,
-) -> Dict[str, Dict[str, Any]]:
+) -> Tuple[Dict[str, Dict[str, Any]], Optional[str]]:
connector_names = [n for n in names if is_connector_name(n)]
if not connector_names or not connections_in_scope(current_tool_defs):
- return {}
+ return {}, None
try:
if connector_describe is None:
from tools.connectors.gateway.bridge import connector_describe
- remote = connector_describe(connector_names)
- if isinstance(remote, dict) and isinstance(remote.get("tools"), dict):
- return remote["tools"]
+ leg = connector_describe(connector_names)
+ if leg.failure:
+ return {}, leg.failure
+ tools = leg.payload.get("tools")
+ if isinstance(tools, dict):
+ return tools, None
+ return {}, (UNREACHABLE if leg.payload else None)
except Exception:
- logger.debug("connector describe merge failed silently (D32)", exc_info=True)
- return {}
+ logger.debug("connector describe merge failed (D32)", exc_info=True)
+ return {}, UNREACHABLE
diff --git a/tools/connectors/targets.py b/tools/connectors/targets.py
index 05db33c3a14..40cc7637384 100644
--- a/tools/connectors/targets.py
+++ b/tools/connectors/targets.py
@@ -1,8 +1,9 @@
-"""Target normalization and action validation for ``manage_connections``."""
-
from __future__ import annotations
-from typing import Any, List, Optional, Tuple
+import logging
+from typing import Any, List, Optional, Set, Tuple
+
+logger = logging.getLogger(__name__)
CONNECTOR_ACTIONS = ("status", "connect", "reconnect")
MCP_ACTIONS = ("install", "enable", "authorize")
@@ -68,3 +69,42 @@ def validate_action(action: str, managed: List[str], mcp: List[str]) -> Optional
f"{', '.join(MCP_ACTIONS)}."
)
return None
+
+
+def catalog_names() -> Set[str]:
+ try:
+ from hermes_cli.mcp_catalog import list_catalog
+
+ return {e.name for e in list_catalog()}
+ except Exception as exc:
+ logger.debug("MCP catalog for the routing check failed: %s", exc)
+ return set()
+
+
+def hosted_names() -> Optional[Set[str]]:
+ try:
+ from tools.connectors.gateway.client import ConnectorClient
+ from tools.connectors.gateway.config import connectors_available
+
+ if not connectors_available():
+ return None
+ return {str(item.get("connector", "")).lower()
+ for item in ConnectorClient().list_connectors() if isinstance(item, dict)}
+ except Exception as exc:
+ logger.debug("connector list for the routing check failed: %s", exc)
+ return None
+
+
+def misrouted_to_hosted_error(name: str) -> str:
+ return (
+ f"{name} is a local MCP server, not a hosted connector account. "
+ f"Call manage_connections with action install and connectors "
+ f"[{{\"name\": \"{name}\", \"mcp\": true}}]."
+ )
+
+
+def misrouted_to_mcp_error(action: str, name: str) -> str:
+ return (
+ f"{name} is a hosted connector account, not a local MCP server, so '{action}' "
+ f"does not apply. Call manage_connections with action connect and connectors [\"{name}\"]."
+ )
diff --git a/tools/connectors/tool.py b/tools/connectors/tool.py
index 13fef6e20ed..efb62ee673a 100644
--- a/tools/connectors/tool.py
+++ b/tools/connectors/tool.py
@@ -47,24 +47,32 @@ def manage_connections(
MANAGE_CONNECTIONS_SCHEMA = {
"name": "manage_connections",
"description": (
- "Connect the user to apps: managed connector accounts (Gmail, Notion, ...) served "
- "through the tool gateway, and local MCP servers from the catalog. Targets go in "
- "'connectors': a bare slug or {\"name\": \"gmail\"} is a managed connector; "
- "{\"name\": \"linear\", \"mcp\": true} is a local MCP server. "
- "Managed actions: 'status' lists connectors and whether each is connected; 'connect' "
+ "Connect the user to apps. Two kinds: a hosted connector account (Gmail, Notion, ...) "
+ "served through the tool gateway, and a local MCP server from the bundled catalog. "
+ "Targets go in 'connectors': a bare slug or {\"name\": \"gmail\"} is a hosted connector "
+ "account; {\"name\": \"linear\", \"mcp\": true} is a local MCP server. Many names exist on "
+ "both sides, so the user's own words decide. Pass \"mcp\": true only when the user asks "
+ "for an MCP server, a local server or an install, or when the name exists only as a "
+ "catalog entry; otherwise the target is hosted. 'connect' and 'reconnect' are hosted "
+ "actions; 'install', 'enable' and 'authorize' are MCP actions. A target the other side "
+ "owns is refused with the call that does work. "
+ "Hosted actions: 'status' lists connectors and whether each is connected; 'connect' "
"starts an authorization for the given connectors; 'reconnect' checks each one and "
"repairs only what is not connected ('force': true restarts even a working one, for an "
- "account switch). Pass SEVERAL slugs in one call. In the desktop app the call shows the "
- "user a card and blocks until every app is connected, skipped, or the deadline passes; "
- "the result lists each target as connected / skipped / not_connected and never carries "
- "a link. Elsewhere the result carries a connect_url per app for the USER to open in a "
- "browser (never open it yourself); ask them to say when they are done, then use 'status'. "
- "When a connector tool call returns CONNECTION_REQUIRED, use 'connect'. "
- "MCP actions (targets must carry \"mcp\": true): 'install' adds a catalog entry, "
+ "account switch). Pass SEVERAL slugs in one call. In the desktop app, the terminal UI and "
+ "the interactive CLI the call shows the user a card and blocks until every app is "
+ "connected, skipped, or the deadline passes; the result lists each target as connected / "
+ "skipped / not_connected and never carries a link. Where no card exists (a one-shot run, "
+ "a scheduled job, a messaging platform) the result carries a connect_url per app for the "
+ "USER to open in a browser (never open it yourself); ask them to say when they are done, "
+ "then use 'status'. "
+ "When a hosted connector tool call returns CONNECTION_REQUIRED, use 'connect'. "
+ "MCP actions (every target must carry \"mcp\": true): 'install' adds a catalog entry, "
"'enable' re-enables a disabled configured server, 'authorize' runs its OAuth. "
"They show the user an approval card and block until it settles. Never hand-edit "
- "mcp_servers config — always use this tool. Never re-ask after a skip or timeout: continue "
- "without the app or ask in chat. A connected server's tools are named in the result and are "
+ "mcp_servers config — always use this tool. After a skip or a timeout, do not re-ask on "
+ "your own: continue without the app or ask in chat. A later request from the USER for that "
+ "same app is not a re-ask — run it. A connected server's tools are named in the result and are "
"callable at once through tool_describe/tool_call. Where no card exists an MCP target runs at once and the result says what "
"happened, with a link for the user to open when one is needed. This tool can NOT "
"disconnect, delete, or revoke an account — that is deliberately user-only. When asked, say so and direct the user to the "
@@ -76,7 +84,10 @@ MANAGE_CONNECTIONS_SCHEMA = {
"action": {
"type": "string",
"enum": list(ALL_ACTIONS),
- "description": "Defaults to status. install/enable/authorize need mcp:true targets.",
+ "description": (
+ "Defaults to status. connect and reconnect take hosted connector slugs only. "
+ "install, enable and authorize take mcp:true targets only."
+ ),
},
"connectors": {
"type": "array",
@@ -87,7 +98,13 @@ MANAGE_CONNECTIONS_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
- "mcp": {"type": "boolean", "description": "true = local MCP server."},
+ "mcp": {
+ "type": "boolean",
+ "description": (
+ "true = a local MCP server from the catalog; absent or "
+ "false = a hosted connector account."
+ ),
+ },
},
"required": ["name"],
"additionalProperties": False,
@@ -96,7 +113,9 @@ MANAGE_CONNECTIONS_SCHEMA = {
},
"description": (
"Targets. REQUIRED for every action but status "
- "(e.g. [\"gmail\", {\"name\": \"linear\", \"mcp\": true}]); optional filter for status."
+ "(e.g. [\"gmail\", {\"name\": \"linear\", \"mcp\": true}]); optional filter for "
+ "status. A bare slug is a hosted connector, so an MCP server needs the object "
+ "form with \"mcp\": true."
),
},
"force": {
diff --git a/tools/connectors/turn.py b/tools/connectors/turn.py
new file mode 100644
index 00000000000..f5579633f25
--- /dev/null
+++ b/tools/connectors/turn.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Any, Iterator
+
+__all__ = [
+ "CARD",
+ "LINK",
+ "SIDE",
+ "SIDE_AGENT_TOOL_DROPS",
+ "agent_connection_surface",
+ "connection_surface",
+ "scoped_connection_surface",
+ "side_agent_tool_drops",
+]
+
+CARD = "card"
+SIDE = "side"
+LINK = "link"
+
+_SURFACE: ContextVar[str] = ContextVar("hermes_connection_surface", default=LINK)
+
+
+def connection_surface() -> str:
+ return _SURFACE.get()
+
+
+def agent_connection_surface(agent: Any) -> str:
+ if getattr(agent, "connection_callback", None) is not None:
+ return CARD
+ return SIDE if getattr(agent, "side_agent", False) else LINK
+
+
+SIDE_AGENT_TOOL_DROPS = frozenset({"manage_connections"})
+
+
+def side_agent_tool_drops(agent: Any) -> frozenset:
+ return SIDE_AGENT_TOOL_DROPS if getattr(agent, "side_agent", False) else frozenset()
+
+
+@contextmanager
+def scoped_connection_surface(surface: str) -> Iterator[None]:
+ token = _SURFACE.set(surface)
+ try:
+ yield
+ finally:
+ _SURFACE.reset(token)
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index b99d6dea1b5..9e2379f103c 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -237,6 +237,7 @@ def _build_child_agent(
**rt, max_iterations=max_iterations, prefill_messages=getattr(parent_agent, "prefill_messages", None),
enabled_toolsets=child_toolsets, disabled_toolsets=child_disabled_toolsets, quiet_mode=True,
ephemeral_system_prompt=child_prompt, log_prefix=f"[subagent-{task_index}]", platform="subagent",
+ side_agent=True,
skip_context_files=True, skip_memory=True, clarify_callback=None,
thinking_callback=(
(lambda text: _safe_progress(child_progress_cb, "_thinking", text) if text else None)
diff --git a/tools/mcp_tool_agent.py b/tools/mcp_tool_agent.py
index 5e8af44da0b..148cc117fbe 100644
--- a/tools/mcp_tool_agent.py
+++ b/tools/mcp_tool_agent.py
@@ -52,6 +52,14 @@ def _tool_defs_content_changed(agent, new_defs: list) -> bool:
return False
+def _drop_side_agent_tools(agent, new_defs: list, new_names: set) -> tuple:
+ from tools.connectors.turn import side_agent_tool_drops
+ drops = side_agent_tool_drops(agent)
+ if not drops:
+ return new_defs, new_names
+ return [entry for entry in new_defs if _def_name(entry) not in drops], new_names - drops
+
+
def _publish_tool_snapshot(
agent, new_defs: list, new_names: set, *, snapshot_generation: int,
staged_engine_names: set, content_aware: bool, prefix_registered: Optional[set]) -> Optional[set]:
@@ -68,6 +76,7 @@ def _publish_tool_snapshot(
current = {_def_name(t) for t in current_defs}
if prefix_registered is not None:
new_defs, new_names = _merge_preserving_prefix(current_defs, new_defs, prefix_registered)
+ new_defs, new_names = _drop_side_agent_tools(agent, new_defs, new_names)
# Record the generation even when unchanged so an in-flight older caller can't clobber.
agent._tool_snapshot_generation = max(published_gen, snapshot_generation)
# Same NAME set: no change for MCP-reload callers. Content-aware callers
@@ -172,6 +181,7 @@ def restore_agent_tool_prefix(agent, saved_names: list) -> bool:
registered_names = {entry.name for entry in registry.get_all_entries()}
merged, merged_names = _merge_preserving_prefix(saved_defs, fresh_defs, registered_names)
_reinject_authorized_dynamic_tools(agent, merged, merged_names)
+ merged, merged_names = _drop_side_agent_tools(agent, merged, merged_names)
with _agent_tools_lock:
if merged == fresh_defs:
return False
diff --git a/tools/tool_labels.py b/tools/tool_labels.py
new file mode 100644
index 00000000000..6f0efd58ad7
--- /dev/null
+++ b/tools/tool_labels.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional
+
+from tools.connectors.gateway.names import parse_connector_name
+from tools.mcp_tool_schema import MCP_TOOL_NAME_PREFIX
+
+logger = logging.getLogger("tools.tool_labels")
+
+CONNECTOR_EMOJI = "🔗"
+MCP_EMOJI = "🔌"
+SEARCH_EMOJI = "🔎"
+DESCRIBE_EMOJI = "📖"
+DEFAULT_TOOL_EMOJI = "⚡"
+
+_APP_TITLES = {
+ "discord": "Discord",
+ "figma": "Figma",
+ "github": "GitHub",
+ "gmail": "Gmail",
+ "googlecalendar": "Google Calendar",
+ "googledocs": "Google Docs",
+ "googledrive": "Google Drive",
+ "jira": "Jira",
+ "linear": "Linear",
+ "notion": "Notion",
+ "outlook": "Outlook",
+ "slack": "Slack",
+ "stripe_mcp": "Stripe",
+ "todoist": "Todoist",
+}
+
+BRIDGE_TOOL_NAMES = frozenset({"tool_call", "tool_search", "tool_describe"})
+
+__all__ = [
+ "BRIDGE_TOOL_NAMES", "CONNECTOR_EMOJI", "DEFAULT_TOOL_EMOJI", "MCP_EMOJI", "ToolLabel",
+ "app_title", "label_for_tool_name", "labels_for_call"]
+
+
+@dataclass(frozen=True)
+class ToolLabel:
+
+ kind: str
+ app: str
+ action: str
+ emoji: str
+ name: str
+ preview: str = ""
+
+ @property
+ def text(self) -> str:
+ return f"{self.app} · {self.action}" if self.action else self.app
+
+ def as_payload(self) -> Dict[str, str]:
+ return {"kind": self.kind, "app": self.app, "action": self.action, "emoji": self.emoji,
+ "text": self.text, "name": self.name, "preview": self.preview}
+
+
+def app_title(slug: str) -> str:
+ key = (slug or "").strip()
+ known = _APP_TITLES.get(key.lower())
+ if known:
+ return known
+ words = [word for word in key.replace("-", " ").replace("_", " ").split() if word]
+ return " ".join(word[:1].upper() + word[1:] for word in words) or key
+
+
+def _action_phrase(tool: str, app_slug: str = "") -> str:
+ text = (tool or "").strip()
+ prefix = f"{app_slug.replace('-', '_').upper()}_"
+ if app_slug and text.upper().startswith(prefix):
+ text = text[len(prefix):]
+ words = [word for word in text.replace("-", " ").replace("_", " ").split() if word]
+ return " ".join(words).lower()
+
+
+def _registry_emoji(name: str) -> str:
+ try:
+ from tools.registry import registry
+ return registry.get_emoji(name, default="") or DEFAULT_TOOL_EMOJI
+ except Exception:
+ return DEFAULT_TOOL_EMOJI
+
+
+def _arg_preview(name: str, arguments: Any) -> str:
+ if not isinstance(arguments, dict) or not arguments:
+ return ""
+ try:
+ from agent.display import build_tool_preview
+ return build_tool_preview(name, arguments) or ""
+ except Exception:
+ logger.debug("argument preview failed for %s", name, exc_info=True)
+ return ""
+
+
+def _local_tool_label(name: str, arguments: Any) -> ToolLabel:
+ verb = ""
+ try:
+ from agent.display import get_tool_verb
+ verb = get_tool_verb(name) or ""
+ except Exception:
+ logger.debug("friendly verb lookup failed for %s", name, exc_info=True)
+ return ToolLabel(kind="tool", app=verb or app_title(name), action="",
+ emoji=_registry_emoji(name), name=name, preview=_arg_preview(name, arguments))
+
+
+def _unnamed_label(arguments: Any) -> ToolLabel:
+ return ToolLabel(kind="tool", app="Unnamed call", action="", emoji=DEFAULT_TOOL_EMOJI,
+ name="", preview=_arg_preview("", arguments))
+
+
+def label_for_tool_name(name: str, arguments: Any = None) -> Optional[ToolLabel]:
+ if not isinstance(name, str) or not name.strip():
+ return None
+ connector = parse_connector_name(name)
+ if connector is not None:
+ return ToolLabel(kind="connector", app=app_title(connector.connector),
+ action=_action_phrase(connector.tool, connector.connector),
+ emoji=CONNECTOR_EMOJI, name=name, preview=_arg_preview(name, arguments))
+ if name.startswith(MCP_TOOL_NAME_PREFIX):
+ server, _, tool = name[len(MCP_TOOL_NAME_PREFIX):].partition("__")
+ if tool:
+ return ToolLabel(kind="mcp", app=app_title(server), action=_action_phrase(tool),
+ emoji=MCP_EMOJI, name=name, preview=_arg_preview(name, arguments))
+ return _local_tool_label(name, arguments)
+
+
+def _bridge_labels(function_name: str, args: Dict[str, Any]) -> List[ToolLabel]:
+ if function_name == "tool_search":
+ queries = args.get("queries")
+ queries = [queries] if isinstance(queries, str) else queries
+ first = next((str(q) for q in queries if str(q or "").strip()), "") if isinstance(queries, list) else ""
+ return [ToolLabel(kind="tool", app="Searching tools", action=first,
+ emoji=SEARCH_EMOJI, name=function_name)]
+ names = args.get("names")
+ names = [names] if isinstance(names, str) else names
+ count = len(names) if isinstance(names, list) else 0
+ return [ToolLabel(kind="tool", app="Reading tool details",
+ action=f"{count} tool" if count == 1 else f"{count} tools",
+ emoji=DESCRIBE_EMOJI, name=function_name)]
+
+
+def labels_for_call(function_name: str, function_args: Any) -> List[ToolLabel]:
+ args = function_args if isinstance(function_args, dict) else {}
+ if function_name in ("tool_search", "tool_describe"):
+ return _bridge_labels(function_name, args)
+ if function_name != "tool_call":
+ label = label_for_tool_name(function_name, args)
+ return [label] if label is not None and label.kind != "tool" else []
+ entries = args.get("calls")
+ entries = entries if isinstance(entries, list) else [args]
+ labels = []
+ for entry in entries:
+ entry = entry if isinstance(entry, dict) else {}
+ arguments = entry.get("arguments")
+ label = label_for_tool_name(entry.get("name"), arguments)
+ labels.append(label if label is not None else _unnamed_label(arguments))
+ return labels
diff --git a/tools/tool_search.py b/tools/tool_search.py
index 4d953c1a82b..24cf89247eb 100644
--- a/tools/tool_search.py
+++ b/tools/tool_search.py
@@ -25,7 +25,8 @@ from tools.tool_search_catalog import (
from tools.tool_search_validation import (
local_batch_error, normalize_tool_call_entries, not_deferrable_error, validate_deferred_call_args)
from tools.connectors import CONNECTOR_BATCH_SENTINEL, is_connector_name
-from tools.connectors.search import connections_in_scope, connector_entries_by_group, remote_schemas_for
+from tools.connectors.search import (
+ connections_in_scope, connector_entries_by_group, connectors_unavailable, remote_schemas_for)
logger = logging.getLogger("tools.tool_search")
# Bound the work one bridge call requests. Search is capped at the gateway's
@@ -437,13 +438,6 @@ def _string_list_arg(args: Dict[str, Any], key: str, *, dedupe: bool, max_items:
def dispatch_tool_search(args: Dict[str, Any], *, current_tool_defs: List[Dict[str, Any]],
config: Optional[ToolSearchConfig] = None,
connector_search: Optional[Any] = None) -> str:
- """Execute the ``tool_search`` bridge tool -> JSON ``{queries, total_available,
- results: [{query, matches: [names]}], tools: {name: {source, source_name, description,
- required}}}``. ``limit`` is the total PER QUERY across local and connector tools: the
- gateway's hits for a query join the local catalog as documents and one BM25 pass ranks
- them together, so a connector tool that answers the query is never starved by local
- tools that share one word with it. Empty groups get ``available_sources`` + ``hint`` so
- a lexical miss is not mistaken for a missing capability."""
config = config or load_config()
queries, err = _string_list_arg(args, "queries", dedupe=False, max_items=_MAX_QUERIES_PER_CALL,
retry_hint="Retry with fewer, more targeted queries.")
@@ -454,8 +448,10 @@ def dispatch_tool_search(args: Dict[str, Any], *, current_tool_defs: List[Dict[s
else _clamped_int(raw_limit, config.search_default_limit, 1, config.max_search_limit))
catalog = build_catalog(_deferrable_in(current_tool_defs))
remote_entries: List[List[CatalogEntry]] = [[] for _ in queries]
+ hosted_failure: Optional[str] = None
if connections_in_scope(current_tool_defs):
- remote_entries = connector_entries_by_group(queries, connector_search=connector_search)
+ remote_entries, hosted_failure = connector_entries_by_group(
+ queries, connector_search=connector_search)
results: List[Dict[str, Any]] = []
tools_map: Dict[str, Dict[str, Any]] = {}
available_sources = _available_source_summary(catalog) if catalog else []
@@ -475,16 +471,16 @@ def dispatch_tool_search(args: Dict[str, Any], *, current_tool_defs: List[Dict[s
"object before concluding the capability is unavailable.")
results.append(group)
remote_count = sum(1 for name in tools_map if is_connector_name(name))
- return json.dumps({"queries": queries, "total_available": len(catalog) + remote_count, "results": results,
- "tools": tools_map}, ensure_ascii=False)
+ payload: Dict[str, Any] = {"queries": queries, "total_available": len(catalog) + remote_count,
+ "results": results, "tools": tools_map}
+ if hosted_failure:
+ payload["connectors"] = connectors_unavailable(hosted_failure, verb="searched")
+ return json.dumps(payload, ensure_ascii=False)
def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict[str, Any]],
config: Optional[ToolSearchConfig] = None,
connector_describe: Optional[Any] = None) -> str:
- """Execute the ``tool_describe`` bridge tool -> JSON ``{tools: {name: {description,
- parameters}}, not_found: [...] (unknown / not in this assembly; never fails the call),
- errors: {name: msg} (registered but non-deferrable)}``. Duplicates dedupe silently."""
config = config or load_config_readonly()
names, err = _string_list_arg(
args, "names", dedupe=True, max_items=_MAX_DESCRIBE_NAMES_PER_CALL,
@@ -493,10 +489,11 @@ def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict
return err
deferrable = _deferrable_in(current_tool_defs)
by_name = {name: _fn(td) for td, name in zip(deferrable, _tool_def_names(deferrable)) if name}
- remote_schemas = remote_schemas_for(names, current_tool_defs, connector_describe)
+ remote_schemas, hosted_failure = remote_schemas_for(names, current_tool_defs, connector_describe)
tools: Dict[str, Dict[str, Any]] = {}
not_found: List[str] = []
+ undescribed: List[str] = []
errors: Dict[str, str] = {}
for name in names:
fn = by_name.get(name)
@@ -508,7 +505,7 @@ def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict
tools[name] = {"description": str(remote_fn.get("description", "")),
"parameters": remote_fn.get("parameters", {})}
elif is_connector_name(name):
- not_found.append(name)
+ (undescribed if hosted_failure else not_found).append(name)
elif _registry_entry(name) is not None and not is_deferrable_tool_name(
name, load_config_readonly().effective_defer_tools):
# Registered but bridge/core/GUI-surface: a real name, wrong door.
@@ -521,6 +518,8 @@ def dispatch_tool_describe(args: Dict[str, Any], *, current_tool_defs: List[Dict
result["hint"] = "Names in not_found are not currently available. Re-run tool_search to refresh."
if errors:
result["errors"] = errors
+ if hosted_failure:
+ result["connectors"] = connectors_unavailable(hosted_failure, verb="described", names=undescribed)
return json.dumps(result, ensure_ascii=False)
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
index c4ae1a37a12..96ef84db684 100644
--- a/tui_gateway/agent_callbacks.py
+++ b/tui_gateway/agent_callbacks.py
@@ -362,7 +362,8 @@ def _background_agent_kwargs(agent, task_id: str) -> dict:
"request_overrides": dict(g("request_overrides", {}) or {}),
# The side agent persists into the PARENT's store: a named-profile chat's ``bg_*`` rows
# belong to that profile's state.db, not the launch handle.
- "platform": "tui", "session_db": getattr(agent, "_session_db", None) or _get_db(), "fallback_model": fallback}
+ "platform": "tui", "session_db": getattr(agent, "_session_db", None) or _get_db(), "fallback_model": fallback,
+ "side_agent": True}
def _ephemeral_preview_agent_kwargs(agent, task_id: str) -> dict:
diff --git a/tui_gateway/connector_payload.py b/tui_gateway/connector_payload.py
index de4ba239a01..37b90cf0403 100644
--- a/tui_gateway/connector_payload.py
+++ b/tui_gateway/connector_payload.py
@@ -8,8 +8,10 @@ from agent.redact import _key_has_secret_keyword, redact_sensitive_text
def connector_ui_payload(value):
if isinstance(value, dict):
- return {key: ("[REDACTED]" if (_key_has_secret_keyword(key)
- or key.lower() in {"authorization", "proxy-authorization", "cookie", "set-cookie", "credentials"})
+ return {key: ("[REDACTED]" if (not isinstance(item, bool)
+ and (_key_has_secret_keyword(key)
+ or key.lower() in {"authorization", "proxy-authorization", "cookie", "set-cookie",
+ "credentials"}))
else item if key == "connect_url" and isinstance(item, str)
else connector_ui_payload(item)) for key, item in value.items()}
if isinstance(value, list):
diff --git a/tui_gateway/contracts/__init__.py b/tui_gateway/contracts/__init__.py
index e3eb9a969c2..58715d76c2e 100644
--- a/tui_gateway/contracts/__init__.py
+++ b/tui_gateway/contracts/__init__.py
@@ -5,6 +5,7 @@ from . import ( # noqa: F401
billing_delegation_pets,
common,
config_free_tier_control,
+ connectors,
connectors_operation,
events,
groups_bot_relay,
diff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.py
index 5121c20d7ed..3351a79625a 100644
--- a/tui_gateway/contracts/common.py
+++ b/tui_gateway/contracts/common.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from typing import Annotated, Literal
+
from pydantic import Field
from .base import JsonValue, Params, Payload, Result, WireEnum
@@ -128,6 +130,28 @@ class StoredSessionRow(OpenModel):
lineage_ids: list[str] | None = Field(default=None, alias="_lineage_ids")
+class ToolLabelKind(WireEnum):
+ """Which surface one inner call of a bridged ``tool_call`` runs on."""
+
+ connector = "connector"
+ mcp = "mcp"
+ tool = "tool"
+
+
+class ToolLabel(Payload):
+ """``tools.tool_labels.ToolLabel`` — what one call executed through the tool_search bridge is,
+ in words. Clients render ``text`` (or ``app``/``action`` in their own columns) and never parse
+ the tool name themselves."""
+
+ kind: ToolLabelKind
+ app: str
+ action: str
+ emoji: str
+ text: str
+ name: str
+ preview: str = ""
+
+
class TranscriptMessage(OpenModel):
"""One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):
``text`` (never ``content``), display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the
@@ -143,6 +167,7 @@ class TranscriptMessage(OpenModel):
name: str | None = None
context: str | None = None
args: dict[str, JsonValue] | None = None
+ labels: list[ToolLabel] | None = None
reasoning: str | None = None
@@ -204,6 +229,18 @@ class ProfileParams(Params):
profile: str | None = None
+class SessionOwner(Params):
+ type: Literal["session"]
+ session_id: str = Field(min_length=1)
+
+
+class AccountOwner(Params):
+ type: Literal["account"]
+
+
+ConnectorOwner = Annotated[SessionOwner | AccountOwner, Field(discriminator="type")]
+
+
class OkResult(Result):
ok: bool = True
@@ -221,7 +258,8 @@ class EmptyPayload(Payload):
__all__ = [
- "TERMINAL_SUBAGENT_STATUSES", "EmptyPayload", "EmptyResult", "McpServerStatus", "MessageReaction", "OkResult", "OpenModel", "PendingApproval",
- "ProfileParams", "ProjectRef", "SessionLiveInfo", "SessionParams", "StatusResult", "StoredSessionRow",
- "SubagentStatus", "TranscriptMessage", "Usage",
+ "TERMINAL_SUBAGENT_STATUSES", "AccountOwner", "ConnectorOwner", "EmptyPayload", "EmptyResult", "McpServerStatus",
+ "MessageReaction", "OkResult", "OpenModel", "PendingApproval",
+ "ProfileParams", "ProjectRef", "SessionLiveInfo", "SessionOwner", "SessionParams", "StatusResult", "StoredSessionRow",
+ "SubagentStatus", "ToolLabel", "ToolLabelKind", "TranscriptMessage", "Usage",
]
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index afe5a22cb65..be17c41fe10 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -15,7 +15,6 @@ from pydantic import Field
from .base import JsonValue, Params, Result, WireEnum
from .common import OpenModel, ProfileParams, SessionLiveInfo
-from .connectors_operation import ConnectionOperationStatus
from .registry import method
# ── config.get ────────────────────────────────────────────────────────────────────────────────
@@ -281,53 +280,6 @@ method("model.options", params=ModelOptionsParams, result=ModelOptionsResult,
doc="Provider/model inventory for the picker, layered over the session's live provider when given.")
-# ── connectors ────────────────────────────────────────────────────────────────────────────────
-
-
-class ConnectorsListParams(ProfileParams):
- session_id: str
-
-
-class ConnectorRow(OpenModel):
- """One ``manage_connections`` status entry after ``connector_ui_payload`` redaction; the
- connector service owns the closed key set, so unknown metadata passes through."""
-
- connector: str = ""
- connected: bool | None = None
- enabled: bool | None = None
- connectionStatus: str | None = None
- name: str | None = None
- description: str | None = None
-
-
-class ConnectorsListResult(Result):
- available: bool
- connectors: list[ConnectorRow]
-
-
-method("connectors.list", params=ConnectorsListParams, result=ConnectorsListResult,
- doc="Connector catalog + connection state for one owned session (``available=False`` when the toolset is off).")
-
-
-class ConnectorsConnectParams(ProfileParams):
- session_id: str
- connectors: list[str]
- reconnect: bool = False
-
-
-class ConnectorsConnectResult(ConnectionOperationStatus):
- """The operation the connect opened (or re-minted on): ``tools/connectors/managed.py``
- ``_off_desktop_result`` / ``methods_connectors._reissue``. ``status``/``note`` ride along from
- the tool result when the call ran through ``manage_connections``."""
-
- status: str | None = None
- note: str | None = None
-
-
-method("connectors.connect", params=ConnectorsConnectParams, result=ConnectorsConnectResult,
- doc="Start (or re-initiate) authorization for named connectors on the session's connection operation.")
-
-
# ── image.generate ────────────────────────────────────────────────────────────────────────────
diff --git a/tui_gateway/contracts/connectors.py b/tui_gateway/contracts/connectors.py
new file mode 100644
index 00000000000..3f326eee487
--- /dev/null
+++ b/tui_gateway/contracts/connectors.py
@@ -0,0 +1,347 @@
+"""Contracts for connector catalog, authorization, and tool-list reads."""
+
+from __future__ import annotations
+
+from typing import Annotated, Literal
+
+from pydantic import Field
+
+from .base import Result, WireEnum
+from .common import ConnectorOwner, ProfileParams
+from .connectors_operation import ConnectionOperationStatus
+from .registry import method
+
+ConnectorSlug = Annotated[str, Field(pattern=r"^[a-z0-9][a-z0-9_-]*$")]
+
+
+class ConnectorErrorReason(WireEnum):
+ invalid_params = "INVALID_PARAMS"
+ not_owner = "NOT_OWNER"
+ unsupported_runtime = "UNSUPPORTED_RUNTIME"
+ connector_request_failed = "CONNECTOR_REQUEST_FAILED"
+ invalid_connector_response = "INVALID_CONNECTOR_RESPONSE"
+ unknown_target = "UNKNOWN_TARGET"
+ link_still_valid = "LINK_STILL_VALID"
+ reissue_refused = "REISSUE_REFUSED"
+ unknown_operation = "UNKNOWN_OPERATION"
+ invalid_answer = "INVALID_ANSWER"
+ needs_nous_auth = "NEEDS_NOUS_AUTH"
+ connector_not_found = "CONNECTOR_NOT_FOUND"
+ tools_unavailable = "TOOLS_UNAVAILABLE"
+ connectors_unavailable = "CONNECTORS_UNAVAILABLE"
+ catalog_unavailable = "CATALOG_UNAVAILABLE"
+ accounts_unavailable = "ACCOUNTS_UNAVAILABLE"
+ connection_not_found = "CONNECTION_NOT_FOUND"
+ policy_unavailable = "POLICY_UNAVAILABLE"
+ policy_conflict = "POLICY_CONFLICT"
+ forbidden_scope = "FORBIDDEN_SCOPE"
+ org_required = "ORG_REQUIRED"
+ org_access_denied = "ORG_ACCESS_DENIED"
+ invalid_policy = "INVALID_POLICY"
+
+
+class ConnectorsListParams(ProfileParams):
+ owner: ConnectorOwner
+
+
+class ConnectorRow(Result):
+ connector: str
+ enabled: bool
+ connected: bool
+ connection_status: Literal["pending", "active", "failed", "expired", "revoked", "inactive"] | None
+ status_reason: str | None
+ gateway_disabled_tools: list[str]
+
+
+class ConnectorsListResult(Result):
+ available: bool
+ connectors: list[ConnectorRow]
+
+
+method(
+ "connectors.list",
+ params=ConnectorsListParams,
+ result=ConnectorsListResult,
+ doc="Connector catalog + connection state for one session or profile account owner.",
+)
+
+
+class ConnectorsConnectParams(ProfileParams):
+ owner: ConnectorOwner
+ connectors: list[ConnectorSlug] = Field(min_length=1)
+ reconnect: bool = False
+
+
+class ConnectorsConnectResult(ConnectionOperationStatus):
+ """``methods_connectors._reissue`` / ``managed._off_desktop_result``: the operation the connect opened; ``status``/``note`` ride along from the tool result."""
+
+ status: Literal["initiated", "settled"] | None = None
+ note: str | None = None
+
+
+method(
+ "connectors.connect",
+ params=ConnectorsConnectParams,
+ result=ConnectorsConnectResult,
+ doc="Start or re-initiate authorization for named connectors on a session or account operation.",
+)
+
+
+class ConnectorToolsParams(ProfileParams):
+ slug: str
+ refresh: bool = False
+
+
+class ConnectorToolFacet(WireEnum):
+ read = "read"
+ write = "write"
+ destructive = "destructive"
+ unclassified = "unclassified"
+
+
+class ConnectorToolRow(Result):
+ model_config = Result.model_config | {"from_attributes": True}
+
+ slug: str
+ name: str
+ description: str
+ facet: ConnectorToolFacet
+ hints: list[str]
+ categories: list[str]
+ no_auth: bool
+ deprecated: bool
+
+
+class ConnectorToolsSource(WireEnum):
+ cache = "cache"
+ network = "network"
+ revalidated = "revalidated"
+
+
+class ConnectorToolsResult(Result):
+ model_config = Result.model_config | {"from_attributes": True}
+
+ connector: str
+ toolkit_version: str
+ etag: str
+ fetched_at: float
+ source: ConnectorToolsSource
+ stale: bool
+ tools: list[ConnectorToolRow]
+
+
+method(
+ "connectors.tools",
+ params=ConnectorToolsParams,
+ result=ConnectorToolsResult,
+ doc="The scoped profile's cached or current tool list for one connector.",
+)
+
+
+class ConnectorCatalogRow(Result):
+ model_config = Result.model_config | {"from_attributes": True}
+
+ slug: str
+ name: str
+ description: str
+ category: str
+ logo_url: str | None = None
+
+
+class ConnectorsCatalogResult(Result):
+ model_config = Result.model_config | {"from_attributes": True}
+
+ connectors: list[ConnectorCatalogRow]
+
+
+method(
+ "connectors.catalog",
+ params=ProfileParams,
+ result=ConnectorsCatalogResult,
+ doc="The hosted connector catalog available to the scoped member.",
+)
+
+
+class ConnectorAccountStatus(WireEnum):
+ pending = "pending"
+ active = "active"
+ failed = "failed"
+ expired = "expired"
+ revoked = "revoked"
+ inactive = "inactive"
+
+
+class ConnectorAccountsParams(ProfileParams):
+ connector: ConnectorSlug | None = None
+
+
+class ConnectorAccountRow(Result):
+ connection_id: str
+ connector: str
+ status: ConnectorAccountStatus
+ status_reason: str | None = None
+ label: str
+ alias: str | None = None
+ active: bool
+ created_at: str
+ updated_at: str
+
+
+class ConnectorAccountsResult(Result):
+ accounts: list[ConnectorAccountRow]
+
+
+method(
+ "connectors.accounts",
+ params=ConnectorAccountsParams,
+ result=ConnectorAccountsResult,
+ doc="The scoped member's hosted connector accounts, optionally filtered by connector slug.",
+)
+
+
+class ConnectorAccountsRemoveParams(ProfileParams):
+ connection_id: str = Field(min_length=1)
+
+
+class ConnectorAccountsRemoveResult(Result):
+ connection_id: str
+ connector: str
+ status: Literal["removed"]
+
+
+method(
+ "connectors.accounts.remove",
+ params=ConnectorAccountsRemoveParams,
+ result=ConnectorAccountsRemoveResult,
+ doc="Remove one hosted connector account owned by the scoped member.",
+)
+
+
+class ConnectorPolicyLayerKind(WireEnum):
+ org = "org"
+ role = "role"
+ member = "member"
+
+
+class ConnectorPolicyTags(Result):
+ enable: list[str] | None = None
+ disable: list[str] | None = None
+
+
+class ConnectorPolicyUnrestrictedBody(Result):
+ mode: Literal["unrestricted"]
+
+
+class ConnectorPolicyDenyAllBody(Result):
+ mode: Literal["deny-all"]
+
+
+class ConnectorPolicyAllowBody(Result):
+ mode: Literal["allow"]
+ connectors: list[str]
+ tools: dict[str, list[str]]
+ tags: ConnectorPolicyTags | None = None
+
+
+class ConnectorPolicyDenyBody(Result):
+ mode: Literal["deny"]
+ disabled_connectors: list[str]
+ tools: dict[str, list[str]]
+ tags: ConnectorPolicyTags | None = None
+
+
+ConnectorPolicyBody = (
+ ConnectorPolicyUnrestrictedBody
+ | ConnectorPolicyDenyAllBody
+ | ConnectorPolicyAllowBody
+ | ConnectorPolicyDenyBody
+)
+
+
+class ConnectorPolicyEffectiveBase(Result):
+ version: Literal[1]
+ revision: str
+ issued_at_ms: int
+
+
+class ConnectorPolicyEffectiveUnrestricted(ConnectorPolicyEffectiveBase):
+ mode: Literal["unrestricted"]
+
+
+class ConnectorPolicyEffectiveDenyAll(ConnectorPolicyEffectiveBase):
+ mode: Literal["deny-all"]
+
+
+class ConnectorPolicyEffectiveAllow(ConnectorPolicyEffectiveBase):
+ mode: Literal["allow"]
+ connectors: list[str]
+ tools: dict[str, list[str]]
+ tags: ConnectorPolicyTags | None = None
+
+
+class ConnectorPolicyEffectiveDeny(ConnectorPolicyEffectiveBase):
+ mode: Literal["deny"]
+ disabled_connectors: list[str]
+ tools: dict[str, list[str]]
+ tags: ConnectorPolicyTags | None = None
+
+
+ConnectorPolicyEffective = (
+ ConnectorPolicyEffectiveUnrestricted
+ | ConnectorPolicyEffectiveDenyAll
+ | ConnectorPolicyEffectiveAllow
+ | ConnectorPolicyEffectiveDeny
+)
+
+
+class ConnectorPolicyLayer(Result):
+ kind: ConnectorPolicyLayerKind
+ revision: str
+ body: ConnectorPolicyBody = Field(discriminator="mode")
+
+
+class ConnectorPolicyGetResult(Result):
+ layers: list[ConnectorPolicyLayer]
+ effective: ConnectorPolicyEffective = Field(discriminator="mode")
+
+
+method(
+ "connectors.policy.get",
+ params=ProfileParams,
+ result=ConnectorPolicyGetResult,
+ doc="Policy layers for the scoped member, from organization to member scope.",
+)
+
+
+class ToolsChange(Result):
+ type: Literal["tools"]
+ connector: str
+ disabled_tools: list[str] = Field(max_length=2000)
+
+
+class ConnectorChange(Result):
+ type: Literal["connector"]
+ connector: str
+ enabled: bool
+
+
+ConnectorPolicyChange = ToolsChange | ConnectorChange
+ConnectorPolicyRevision = Annotated[str, Field(pattern=r"^[0-7][0-9A-HJKMNP-TV-Z]{25}$")]
+
+
+class ConnectorPolicySetParams(ProfileParams):
+ change: ConnectorPolicyChange = Field(discriminator="type")
+ expected_revision: ConnectorPolicyRevision
+
+
+class ConnectorPolicySetResult(Result):
+ revision: str
+ effective: ConnectorPolicyEffective = Field(discriminator="mode")
+
+
+method(
+ "connectors.policy.set",
+ params=ConnectorPolicySetParams,
+ result=ConnectorPolicySetResult,
+ doc="Apply one scoped member connector or tool-list policy change.",
+)
diff --git a/tui_gateway/contracts/connectors_operation.py b/tui_gateway/contracts/connectors_operation.py
index 4a8009ff1fc..8c52f7cd6ec 100644
--- a/tui_gateway/contracts/connectors_operation.py
+++ b/tui_gateway/contracts/connectors_operation.py
@@ -9,10 +9,12 @@ projection: every frame carries the full target snapshot, and the renderer never
from __future__ import annotations
+from typing import Literal
+
from pydantic import Field
from .base import Params, Payload, Result, WireEnum
-from .common import ProfileParams
+from .common import ConnectorOwner, ProfileParams
from .registry import event, method
@@ -38,7 +40,6 @@ class ConnectionTargetState(WireEnum):
skipped = "skipped"
failed = "failed"
expired = "expired"
- unavailable = "unavailable"
not_connected = "not_connected"
@@ -57,7 +58,6 @@ class ConnectionSettleReason(WireEnum):
continue_ = "continue"
deadline = "deadline"
interrupt = "interrupt"
- unavailable = "unavailable"
class ConnectionTargetEnvField(Payload):
@@ -127,6 +127,7 @@ class ConnectionUpdatePayload(ConnectionOperationStatus, Payload):
"""``methods_connectors._connection_update``: one target transition (``target``/``from``/``to``/
``actor``) or the settlement (none of those), with the full snapshot."""
+ owner: ConnectorOwner
target: str | None = None
from_: ConnectionTargetState | None = Field(default=None, alias="from") # ``from`` is a keyword
to: ConnectionTargetState | None = None
@@ -138,16 +139,16 @@ event("connection.update", ConnectionUpdatePayload,
class ConnectionOperationParams(ProfileParams):
- session_id: str
+ owner: ConnectorOwner
op_id: str
method("connectors.operation.status", params=ConnectionOperationParams, result=ConnectionOperationStatus,
- doc="The current snapshot of one open operation on an owned session.")
+ doc="The current snapshot of one open session or account operation.")
class ConnectionWakeResult(Result):
- status: str
+ status: Literal["ok"]
method("connectors.operation.wake", params=ConnectionOperationParams, result=ConnectionWakeResult,
@@ -184,7 +185,7 @@ class ConnectionRespondParams(ConnectionOperationParams):
class ConnectionRespondResult(Result):
- status: str
+ status: Literal["ok"]
settled: bool
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 81b71d504ef..8e9c5fa971b 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -18,7 +18,7 @@ from __future__ import annotations
from pydantic import Field
from .base import JsonValue, Payload, WireEnum
-from .common import MessageReaction, SessionLiveInfo, SubagentStatus, Usage
+from .common import MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage
from .config_free_tier_control import SessionControlSnapshot
from .registry import event
@@ -251,6 +251,7 @@ class ToolStartPayload(Payload):
args: dict[str, JsonValue] | None = None
args_text: str | None = None
preview: str | None = None
+ labels: list[ToolLabel] | None = None
event("tool.start", ToolStartPayload, doc="A tool call began (stable id + full args).")
@@ -269,6 +270,7 @@ class ToolCompletePayload(Payload):
inline_diff: str | None = None
todos: list[JsonValue] | None = None
revision: int | None = None
+ labels: list[ToolLabel] | None = None
event("tool.complete", ToolCompletePayload, doc="A tool call finished: parsed result, summary, optional diff / todo snapshot.")
@@ -707,6 +709,7 @@ __all__ = [
"SetupReadyPayload", "SideAgentCompletePayload", "SkinPayload", "StatusUpdatePayload",
"StreamDeltaPayload", "SubagentEventPayload", "SubagentOutputTailEntry", "TerminalClosePayload",
"TerminalOutputPayload", "TipShowPayload", "TodoUpdatedPayload", "ToolCompletePayload",
- "ToolGeneratingPayload", "ToolOutputRiskPayload", "ToolStartPayload", "TurnStatus", "VoiceStatusPayload",
+ "ToolGeneratingPayload", "ToolLabel", "ToolLabelKind", "ToolOutputRiskPayload", "ToolStartPayload",
+ "TurnStatus", "VoiceStatusPayload",
"VoiceTranscriptPayload", "WakeDetectedPayload",
]
diff --git a/tui_gateway/contracts/registry.py b/tui_gateway/contracts/registry.py
index 5e7d18fd651..75f218fe7e1 100644
--- a/tui_gateway/contracts/registry.py
+++ b/tui_gateway/contracts/registry.py
@@ -77,24 +77,18 @@ def event(name: str, payload: type[Payload] | None = None, *, doc: str = "") ->
#
# Params are validated on every call: an unknown or mistyped key is the CLIENT's bug and answers
# JSON-RPC ``4000`` with the field path, never a silent ignore. Results and payloads are OUR bug when
-# they drift, so they never break a user's turn: outside the test suite a mismatch is logged once per
-# name; under ``HERMES_TEST_ISOLATION`` (set by ``scripts/run_tests.sh`` / ``tests/conftest.py``) it
# raises, which is what makes the suite the gate.
STRICT = bool(os.environ.get("HERMES_TEST_ISOLATION"))
-_reported: set[str] = set()
-
class ContractViolation(AssertionError):
- """A result/payload the gateway produced does not match its declared contract."""
+ """A result or payload the gateway produced does not match its declared contract."""
def _report(kind: str, name: str, exc: ValidationError) -> None:
if STRICT:
raise ContractViolation(f"{kind} {name!r} violates its contract: {exc}") from exc
- if name not in _reported:
- _reported.add(name)
- logger.warning("%s %r violates its wire contract: %s", kind, name, exc)
+ logger.error("%s %r violates its wire contract: %s", kind, name, exc)
def validate_params(contract: MethodContract | ServerRequestContract, params: dict) -> tuple[dict | None, str | None]:
@@ -118,7 +112,7 @@ def validate_params(contract: MethodContract | ServerRequestContract, params: di
def check_params_accepted(contract: MethodContract | ServerRequestContract, params: dict) -> None:
"""The handler answered with a result: the params it accepted must be valid under the
contract, else the contract is narrower than the wire (a required field that is optional in
- practice, a type the handler coerces). Same strict/log policy as results."""
+ practice, a type the handler coerces). Same strict/error-log policy as results."""
try:
contract.params.model_validate(params)
except ValidationError as exc:
diff --git a/tui_gateway/method_ctx.py b/tui_gateway/method_ctx.py
index 6bb7049b74c..593b5e3ed83 100644
--- a/tui_gateway/method_ctx.py
+++ b/tui_gateway/method_ctx.py
@@ -54,6 +54,9 @@ class HandlerRegistry:
return fn
return dec
+ def names(self) -> set[str]:
+ return {name for name, _ in self._pending}
+
def profile_scoped(self, fn):
"""Drop-in for server.py's ``@_profile_scoped`` (applied at install)."""
fn._hermes_profile_scoped = True
diff --git a/tui_gateway/methods_connectors.py b/tui_gateway/methods_connectors.py
index 2cfe9e0aed9..7d062530951 100644
--- a/tui_gateway/methods_connectors.py
+++ b/tui_gateway/methods_connectors.py
@@ -1,221 +1,342 @@
-"""Session-scoped connector RPCs and the connection-operation bridge.
-
-Live transport ownership, not renderer-supplied profile or identity, authorizes requests.
-The operation itself lives in ``tools.connectors.live``; this module reads and drives it and
-pushes every transition to the session as ``connection.update``.
-"""
-
+import contextlib
import contextvars
from .method_ctx import HandlerRegistry, bind_module
_registry = HandlerRegistry()
method = _registry.method
-_CONNECTOR_RPC_METHODS = frozenset({"connectors.list", "connectors.connect"})
+_CONNECTOR_RPC_METHODS = frozenset({"connectors.list", "connectors.connect", "connection.respond"})
_connector_rpc_origin: contextvars.ContextVar[tuple | None] = contextvars.ContextVar("connector_rpc_origin", default=None)
def _capture_connector_rpc_owner(params):
- sid = params.get("session_id")
- _, owner = _current_session_steer_authority(sid if isinstance(sid, str) else "")
- _connector_rpc_origin.set((owner, owner.get("profile_home") if owner is not None else None))
+ owner = params.get("owner") if isinstance(params, dict) else None
+ sid = owner.get("session_id") if isinstance(owner, dict) and owner.get("type") == "session" else ""
+ _, session = _current_session_steer_authority(sid if isinstance(sid, str) else "")
+ _connector_rpc_origin.set((session, session.get("profile_home") if session is not None else None))
def _connector_rpc_error(rid, code, reason, message):
return _err(rid, code, message, data={"reason": reason})
+def _connector_auth_error(rid, exc):
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ if exc.code in {"no_access", "ORG_ACCESS_DENIED"}:
+ return _connector_rpc_error(
+ rid, 4030, ConnectorErrorReason.org_access_denied,
+ "This account cannot manage connectors for this organization.",
+ )
+ if exc.status == 401 or exc.code in {"invalid_token", "INVALID_TOKEN", "NO_TOKEN"}:
+ return _connector_rpc_error(rid, 4032, ConnectorErrorReason.needs_nous_auth, "Sign in to use connectors.")
+ return _connector_rpc_error(
+ rid, 4030, ConnectorErrorReason.forbidden_scope, "Connector access is not permitted for this account."
+ )
+
+
+def _connector_guard(fn):
+ def handler(rid, params):
+ from tools.connectors.gateway.errors import GatewayAuthError
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ try:
+ return fn(rid, params)
+ except ProfileUnavailableError:
+ raise
+ except GatewayAuthError as exc:
+ return _connector_auth_error(rid, exc)
+ except Exception:
+ return _connector_rpc_error(
+ rid, 5034, ConnectorErrorReason.connector_request_failed, "Connector request failed. Try again explicitly."
+ )
+
+ return handler
+
+
def _connector_owner_matches(sid, owner, profile_home):
_, current = _current_session_steer_authority(sid)
- return (current is owner and not owner.get("_finalized")
- and owner.get("profile_home") == profile_home)
+ return current is owner and not owner.get("_finalized") and owner.get("profile_home") == profile_home
+
+def _session_owner(rid, owner):
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
-def _owned_session(rid, params):
- """(owner, None) for a session this transport owns; (None, error reply) otherwise."""
- sid = params.get("session_id")
- if not isinstance(sid, str) or not sid.strip():
- return None, _connector_rpc_error(rid, 4000, "INVALID_PARAMS", "session_id required")
- _, owner = _current_session_steer_authority(sid)
+ sid = owner.session_id
+ _, session = _current_session_steer_authority(sid)
origin = _connector_rpc_origin.get()
- if (owner is None or owner.get("_finalized")
- or origin is not None and (origin[0] is not owner or origin[1] != owner.get("profile_home"))):
- return None, _connector_rpc_error(rid, 4001, "NOT_OWNER", "session not found or not owned by this transport")
- if _session_uses_compute_host(owner):
- return None, _connector_rpc_error(rid, 5033, "UNSUPPORTED_RUNTIME", "Connectors must be managed on the session's compute host.")
- return owner, None
+ if (session is None or session.get("_finalized")
+ or origin is not None and (origin[0] is not session or origin[1] != session.get("profile_home"))):
+ return None, _connector_rpc_error(
+ rid, 4001, ConnectorErrorReason.not_owner, "session not found or not owned by this transport"
+ )
+ if _session_uses_compute_host(session):
+ return None, _connector_rpc_error(
+ rid, 5033, ConnectorErrorReason.unsupported_runtime, "Connectors must be managed on the session's compute host."
+ )
+ return session, None
-def _connector_rpc(rid, params, action):
- owner, error = _owned_session(rid, params)
- if error:
- return error
- sid = params["session_id"]
- allowed = {"session_id"} if action == "status" else {"session_id", "connectors", "reconnect"}
- # ``profile`` is routing metadata, never authorization.
- allowed.add("profile")
- if set(params) - allowed:
- return _connector_rpc_error(rid, 4000, "INVALID_PARAMS", "unsupported connector parameters")
- args = {"action": action}
- if action != "status":
- import re
- slugs = params.get("connectors")
- if (not isinstance(slugs, list) or not slugs
- or any(not isinstance(slug, str) or re.fullmatch(r"[a-z0-9][a-z0-9_-]*", slug) is None for slug in slugs)
- or not isinstance(params.get("reconnect", False), bool)):
- return _connector_rpc_error(rid, 4000, "INVALID_PARAMS", "connectors must be nonempty slugs; reconnect must be boolean")
- args.update(action="reconnect" if params.get("reconnect", False) else "connect", connectors=slugs)
- profile_home = owner.get("profile_home")
- runtime_token = _current_runtime_session_record.set(owner)
+def _account_gate_closed(rid):
+ from tools.connectors import connectors_available
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ if connectors_available():
+ return None
+ return _connector_rpc_error(rid, 4031, ConnectorErrorReason.connectors_unavailable, "Connectors are not available.")
+
+
+def _parse_params(rid, params, model):
+ from pydantic import ValidationError
+
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
try:
- # Bind the launch profile to prevent ambient sibling-profile leakage.
- scope = {"profile_home": profile_home or str(_hermes_home)}
- with _session_profile_runtime_scope(scope):
- tokens = _set_session_context(owner["session_key"], cwd=_session_cwd(owner), ui_session_id=sid)
- try:
- result = _dispatch_connector_rpc(rid, sid, owner, profile_home, args)
- finally:
- _clear_session_context(tokens)
- if not _connector_owner_matches(sid, owner, profile_home):
- return _connector_rpc_error(rid, 4001, "NOT_OWNER", "session ownership changed")
- return result
- except Exception:
- # Do not expose exception strings: HTTP errors can contain credentials.
- return _connector_rpc_error(rid, 5034, "CONNECTOR_REQUEST_FAILED", "Connector request failed. Try again explicitly.")
- finally:
- _current_runtime_session_record.reset(runtime_token)
+ return model.model_validate(params), None
+ except ValidationError:
+ return None, _connector_rpc_error(rid, 4000, ConnectorErrorReason.invalid_params, "Connector parameters are invalid.")
-def _dispatch_connector_rpc(rid, sid, owner, profile_home, args):
+def _connector_params(rid, params, model):
+ request, error = _parse_params(rid, params, model)
+ if error:
+ return None, None, error
+ if request.owner.type == "account":
+ return request, None, None
+ session, error = _session_owner(rid, request.owner)
+ return request, session, error
+
+
+def _session_connector_gate(rid, session, action):
import model_tools
- from tools.connectors import connectors_available, live
- from tui_gateway.connector_payload import connector_ui_payload
+ from tools.connectors import connectors_available
+
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
- agent = owner.get("agent")
- enabled = (agent.enabled_toolsets if agent is not None
- else _load_enabled_toolsets(_resolve_agent_platform(_session_source(owner))))
+ agent = session.get("agent")
+ enabled = agent.enabled_toolsets if agent is not None else _load_enabled_toolsets(_resolve_agent_platform(_session_source(session)))
disabled = agent.disabled_toolsets if agent is not None else None
- if ("manage_connections" not in model_tools._select_tool_names(enabled, disabled, quiet_mode=True)
- or not connectors_available()):
- if args["action"] == "status":
- return _ok(rid, {"available": False, "connectors": []})
- return _connector_rpc_error(rid, 4031, "CONNECTORS_UNAVAILABLE", "Connectors are not available in this session.")
- if not _connector_owner_matches(sid, owner, profile_home):
- return _connector_rpc_error(rid, 4001, "NOT_OWNER", "session ownership changed")
- if args["action"] != "status" and (
- operation := live.current(owner["session_key"], profile_home=owner.get("profile_home"))) is not None:
- # The card's Try again / Connect while the model's operation is open: reissue on that op.
+ if "manage_connections" not in model_tools._select_tool_names(enabled, disabled, quiet_mode=True) or not connectors_available():
+ if action == "status":
+ return enabled, disabled, _ok(rid, {"available": False, "connectors": []})
+ return enabled, disabled, _connector_rpc_error(
+ rid, 4031, ConnectorErrorReason.connectors_unavailable, "Connectors are not available in this session."
+ )
+ return enabled, disabled, None
+
+
+def _session_connector_rpc(rid, request, session, action):
+ import json
+ import model_tools
+ import uuid
+
+ from tools.connectors import live
+ from tui_gateway.connector_payload import connector_ui_payload
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ sid = request.owner.session_id
+ enabled, disabled, error = _session_connector_gate(rid, session, action)
+ if error:
+ return error
+ if not _connector_owner_matches(sid, session, session.get("profile_home")):
+ return _connector_rpc_error(rid, 4001, ConnectorErrorReason.not_owner, "session ownership changed")
+ args = {"action": "reconnect" if action == "connect" and request.reconnect else action}
+ if action == "connect":
+ args["connectors"] = request.connectors
+ if action == "connect":
+ operation = live.current(session["session_key"], profile_home=session.get("profile_home"))
+ if operation is None:
+ return _connector_rpc_error(
+ rid, 4004, ConnectorErrorReason.unknown_operation, "No open connection operation for this session."
+ )
return _reissue(rid, operation, args)
raw = model_tools.handle_function_call(
- "manage_connections", args, task_id=owner["session_key"],
- session_id=getattr(agent, "session_id", None) or owner["session_key"],
+ "manage_connections",
+ args,
+ task_id=session["session_key"],
+ session_id=getattr(session.get("agent"), "session_id", None) or session["session_key"],
tool_call_id=f"connector-ui-{uuid.uuid4().hex}",
- enabled_toolsets=enabled, disabled_toolsets=disabled,
+ enabled_toolsets=enabled,
+ disabled_toolsets=disabled,
)
data = json.loads(raw) if isinstance(raw, str) else raw
if not isinstance(data, dict) or "error" in data:
- return _connector_rpc_error(rid, 5034, "CONNECTOR_REQUEST_FAILED", "Connector request failed or was refused by policy.")
- if args["action"] == "status":
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.connector_request_failed, "Connector request failed. Try again explicitly.")
+ if action == "status":
if not isinstance(data.get("connectors"), list) or any(not isinstance(row, dict) for row in data["connectors"]):
- return _connector_rpc_error(rid, 5034, "INVALID_CONNECTOR_RESPONSE", "Connector service returned an invalid response.")
- return _ok(rid, {"available": True, "connectors": connector_ui_payload(data["connectors"])})
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.invalid_connector_response, "Connector service returned an invalid response.")
+ return _ok(rid, {"available": True, "connectors": _connector_rows(data["connectors"])})
if not isinstance(data.get("targets"), list):
- return _connector_rpc_error(rid, 5034, "INVALID_CONNECTOR_RESPONSE", "Connector service returned no authorization results.")
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.invalid_connector_response, "Connector service returned no authorization results.")
return _ok(rid, connector_ui_payload(data))
-def _reissue(rid, operation, args):
- """The card's Try again on the open operation: a managed target is re-minted at the gateway, an
- MCP target re-runs its own install / enable / OAuth. Dead rows only — a waiting target already
- holds the link the card reopens, and never calls here."""
- from tools.connectors.contract import TargetState, allowed
+def _connector_rows(rows):
+ from tools.connectors.gateway.wire import ConnectorListItem
from tui_gateway.connector_payload import connector_ui_payload
- targets = [operation.target(n) for n in args["connectors"]]
- if any(t is None for t in targets):
- return _connector_rpc_error(rid, 4004, "UNKNOWN_TARGET", "no such target on the open operation")
- if len({t.kind for t in targets}) != 1:
- return _connector_rpc_error(rid, 4000, "INVALID_PARAMS", "one target kind per request")
- stale = [t.name for t in targets if t.state in (TargetState.failed, TargetState.expired)]
- if len(stale) != len(targets):
- return _connector_rpc_error(rid, 4002, "LINK_STILL_VALID",
- "only a failed or expired target can be re-run; reopen the stored link")
- if operation.settled:
- # Continue can land between the state read above and the re-run: the result is frozen and
- # a fresh mint or flow would have no row to report into.
- return _connector_rpc_error(rid, 4002, "REISSUE_REFUSED", "the operation has settled")
- # The contract says which dead state a kind can leave: an MCP target has no move out of expired.
- frozen = [t.name for t in targets if allowed(t.kind, t.state, TargetState.initiated) is None]
- if frozen:
- return _connector_rpc_error(rid, 4002, "REISSUE_REFUSED",
- f"this target cannot be run again: {', '.join(frozen)}")
- error = _REISSUE_BY_KIND[targets[0].kind](operation, stale)
- if error:
- return _connector_rpc_error(rid, 4002, "REISSUE_REFUSED", error)
- return _ok(rid, connector_ui_payload(_operation_view(operation)))
+ return connector_ui_payload([
+ ConnectorListItem.model_validate(row).model_dump(mode="json", by_alias=False)
+ for row in rows
+ ])
-def _remint_managed(operation, names):
- from tools.connectors.contract import Actor
- from tools.connectors.gateway.client import ConnectorClient
- from tools.connectors.managed import mint
+def _account_connector_list(rid):
+ from tools.connectors.managed import managed_client
- mint(ConnectorClient(), operation, names, reinitiate=True, actor=Actor.user)
- return None
+ return _ok(rid, {"available": True, "connectors": _connector_rows(managed_client().list_connectors())})
-def _rerun_mcp(operation, names):
- from tools.connectors.mcp import retry
+def _account_connector_connect(rid, request):
+ from tools.connectors import account
+ from tui_gateway.connector_payload import connector_ui_payload
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
- return retry(operation, names)
+ action = "reconnect" if request.reconnect else "connect"
+ try:
+ start = account.find_or_start_operation(request.connectors, action=action, profile_home=_account_home(request))
+ if not start.started:
+ from tools.connectors.contract import TargetState
+
+ targets = [start.operation.target(name) for name in request.connectors]
+ if any(target.state in (TargetState.failed, TargetState.expired) for target in targets):
+ return _reissue(rid, start.operation, {"connectors": request.connectors})
+ return _ok(rid, connector_ui_payload(_operation_view(start.operation)))
+ if not account.wait_for_prepare(start):
+ return _ok(rid, connector_ui_payload(_operation_view(start.operation)))
+ if start.failed:
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.connector_request_failed, "Connector request failed. Try again explicitly.")
+ return _ok(rid, connector_ui_payload(_operation_view(start.operation)))
+ except ValueError:
+ return _connector_rpc_error(rid, 4000, ConnectorErrorReason.invalid_params, "Connector parameters are invalid.")
-_REISSUE_BY_KIND = {"connector": _remint_managed, "mcp": _rerun_mcp}
+def _connector_rpc(rid, params, action):
+ from tui_gateway.contracts.connectors import ConnectorErrorReason, ConnectorsConnectParams, ConnectorsListParams
+ model = ConnectorsListParams if action == "status" else ConnectorsConnectParams
+ request, session, error = _connector_params(rid, params, model)
+ if error:
+ return error
+ if request.owner.type == "account":
+ with _account_scope(request):
+ if closed := _account_gate_closed(rid):
+ return _ok(rid, {"available": False, "connectors": []}) if action == "status" else closed
+ return _account_connector_list(rid) if action == "status" else _account_connector_connect(rid, request)
-def _live_operation(rid, params, owner):
- from tools.connectors import live
+ runtime_token = _current_runtime_session_record.set(session)
+ try:
+ profile_home = session.get("profile_home")
+ with _session_profile_runtime_scope({"profile_home": profile_home or str(_hermes_home)}):
+ tokens = _set_session_context(session["session_key"], cwd=_session_cwd(session), ui_session_id=request.owner.session_id)
+ try:
+ result = _session_connector_rpc(rid, request, session, action)
+ finally:
+ _clear_session_context(tokens)
+ if not _connector_owner_matches(request.owner.session_id, session, profile_home):
+ return _connector_rpc_error(rid, 4001, ConnectorErrorReason.not_owner, "session ownership changed")
+ return result
+ finally:
+ _current_runtime_session_record.reset(runtime_token)
- op_id = params.get("op_id")
- if not isinstance(op_id, str) or not op_id:
- return None, _connector_rpc_error(rid, 4000, "INVALID_PARAMS", "op_id required")
- operation = live.get(owner["session_key"], op_id, profile_home=owner.get("profile_home"))
- if operation is None:
- return None, _connector_rpc_error(rid, 4004, "UNKNOWN_OPERATION", "no open operation with that op_id in this session")
- return operation, None
+
+def _reissue(rid, operation, args):
+ from tools.connectors.run import (
+ LINK_STILL_VALID,
+ MIXED_KINDS,
+ NOT_ALLOWED,
+ REFUSED,
+ SETTLED,
+ UNKNOWN_TARGET,
+ reissue,
+ )
+ from tui_gateway.connector_payload import connector_ui_payload
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ reason = reissue(operation, args["connectors"])
+ if reason == UNKNOWN_TARGET:
+ return _connector_rpc_error(rid, 4004, ConnectorErrorReason.unknown_target, "No such target on the open operation.")
+ if reason == MIXED_KINDS:
+ return _connector_rpc_error(rid, 4000, ConnectorErrorReason.invalid_params, "One target kind per request.")
+ if reason == LINK_STILL_VALID:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.link_still_valid, "Reopen the stored link.")
+ if reason == SETTLED:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.reissue_refused, "The operation has settled.")
+ if reason == NOT_ALLOWED:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.reissue_refused, "This target cannot be run again.")
+ if reason == REFUSED:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.reissue_refused, "The target cannot be run again.")
+ return _ok(rid, connector_ui_payload(_operation_view(operation)))
+
+
+def _operation_params(rid, params):
+ from tui_gateway.contracts.connectors_operation import ConnectionOperationParams
+
+ return _connector_params(rid, params, ConnectionOperationParams)
@method("connectors.list")
+@_connector_guard
def _(rid, params):
return _connector_rpc(rid, params, "status")
@method("connectors.connect")
+@_connector_guard
def _(rid, params):
return _connector_rpc(rid, params, "connect")
+def _account_home(request):
+ home = _profile_home(request.profile)
+ return str(home) if home else None
+
+
+def _account_scope(request):
+ with _session_profile_runtime_scope({"profile_home": _account_home(request)}):
+ tokens = _set_session_context("")
+ try:
+ yield
+ finally:
+ _clear_session_context(tokens)
+
+
+def _operation_for_request(rid, request, session):
+ from tools.connectors import live
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ if request.owner.type == "session":
+ operation = live.get(session["session_key"], request.op_id, profile_home=session.get("profile_home"))
+ else:
+ with _account_scope(request):
+ if closed := _account_gate_closed(rid):
+ return None, closed
+ operation = live.get_by_op_id(request.op_id, profile_home=_account_home(request))
+ if operation is None:
+ return None, _connector_rpc_error(rid, 4004, ConnectorErrorReason.unknown_operation, "No open operation with that op_id.")
+ return operation, None
+
+
@method("connectors.operation.status")
+@_connector_guard
def _(rid, params):
from tui_gateway.connector_payload import connector_ui_payload
- owner, error = _owned_session(rid, params)
+ request, session, error = _operation_params(rid, params)
if error:
return error
- operation, error = _live_operation(rid, params, owner)
- if error:
- return error
- return _ok(rid, connector_ui_payload(_operation_view(operation)))
+ operation, error = _operation_for_request(rid, request, session)
+ return error or _ok(rid, connector_ui_payload(_operation_view(operation)))
@method("connectors.operation.wake")
+@_connector_guard
def _(rid, params):
- """The desktop came back from the vendor's done page: read the accounts now instead of at the
- next tick. The link is not trusted for anything else; this only shortens the wait."""
- owner, error = _owned_session(rid, params)
+ request, session, error = _operation_params(rid, params)
if error:
return error
- operation, error = _live_operation(rid, params, owner)
+ operation, error = _operation_for_request(rid, request, session)
if error:
return error
operation.wake.set()
@@ -223,41 +344,44 @@ def _(rid, params):
@method("connection.respond")
+@_connector_guard
def _(rid, params):
- """The card's answer for the operation named by ``op_id``: per target an approval that starts
- the backend's work or a skip, plus an optional Continue. The card never witnesses an outcome,
- so any other claim moves nothing."""
from pydantic import ValidationError
- from tools.connectors import live
- from tools.connectors.contract import SettleReason
- from tools.connectors.mcp import apply_answer
- from tools.connectors.operation import IllegalTransition
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
from tui_gateway.contracts.connectors_operation import ConnectionAnswer
- owner, error = _owned_session(rid, params)
+ envelope = {key: value for key, value in params.items() if key != "result"}
+ request, session, error = _operation_params(rid, envelope)
if error:
return error
- operation, error = _live_operation(rid, params, owner)
+ try:
+ answer = ConnectionAnswer.model_validate(params.get("result"))
+ except ValidationError:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.invalid_answer, "Connection answer is invalid.")
+ operation, error = _operation_for_request(rid, request, session)
if error:
return error
- # The wire check refuses unknown keys only; the closed answer vocabulary (approved / skipped) is
- # this handler's refusal, so a card claiming ``connected`` is answered, not logged.
+ if request.owner.type == "account":
+ with _account_scope(request):
+ return _apply_connection_answer(rid, answer, operation)
+ with _session_profile_runtime_scope({"profile_home": session.get("profile_home") or str(_hermes_home)}):
+ return _apply_connection_answer(rid, answer, operation)
+
+
+def _apply_connection_answer(rid, answer, operation):
+ from tools.connectors import live
+ from tools.connectors.contract import SettleReason
+ from tools.connectors.mcp import apply_answer
+ from tools.connectors.operation import IllegalTransition
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
try:
- answer = ConnectionAnswer.model_validate(params["result"])
- except ValidationError as exc:
- return _connector_rpc_error(rid, 4002, "INVALID_ANSWER", exc.errors()[0].get("msg", "invalid answer"))
- # An approval runs the backend's work on this thread (an enable writes config.yaml, an install
- # stores credentials), so the answer is applied under the session's profile the way
- # ``_connector_rpc`` binds it; the RPC thread carries no profile of its own.
- scope = {"profile_home": owner.get("profile_home") or str(_hermes_home)}
- with _session_profile_runtime_scope(scope):
- try:
- apply_answer(operation, answer.model_dump_json(exclude_none=True))
- except IllegalTransition as exc:
- return _connector_rpc_error(rid, 4002, "ILLEGAL_TRANSITION", str(exc))
- if not operation.settled and operation.all_resolved:
- operation.settle(SettleReason.all_resolved)
+ apply_answer(operation, answer.model_dump_json(exclude_none=True))
+ except IllegalTransition:
+ return _connector_rpc_error(rid, 4002, ConnectorErrorReason.invalid_answer, "Connection answer is invalid.")
+ if not operation.settled and operation.all_resolved:
+ operation.settle(SettleReason.all_resolved)
if operation.settled:
live.close(operation)
return _ok(rid, {"status": "ok", "settled": operation.settled})
@@ -268,29 +392,41 @@ def _snapshot_view(snapshot):
def _operation_view(operation):
- return _snapshot_view(operation.result())
+ return _snapshot_view(operation.snapshot())
def _connection_update(operation, change, snapshot):
- """Emit ``connection.update`` for one transition, a link refresh, or settlement. Every frame
- carries the full target snapshot so the renderer never reconstructs state from deltas. The
- snapshot was taken under the operation's lock with the ``seq`` it carries, so a frame can never
- show a state newer than its own seq names."""
+ from hermes_constants import get_process_hermes_home, hermes_home_key
from tui_gateway import server
+ from tui_gateway.connector_payload import connector_ui_payload
- with server._sessions_lock:
- sid = next((s for s, c in server._sessions.items() if c.get("session_key") == operation.session_key), None)
- if sid is None:
- return
payload = _snapshot_view(snapshot)
if change:
payload.update(change)
- server._emit("connection.update", sid, payload)
+ if operation.session_key.startswith("account:"):
+ payload["targets"] = [
+ {key: value for key, value in target.items() if key not in ("connect_url", "connection_id")}
+ for target in payload["targets"]
+ ]
+ payload["owner"] = {"type": "account"}
+ server._broadcast_global_event("connection.update", connector_ui_payload(payload))
+ return
+ with server._sessions_lock:
+ sid = next(
+ (
+ sid
+ for sid, session in server._sessions.items()
+ if session.get("session_key") == operation.session_key
+ and hermes_home_key(session.get("profile_home") or get_process_hermes_home()) == operation.profile_key
+ ),
+ None,
+ )
+ if sid is not None:
+ payload["owner"] = {"type": "session", "session_id": sid}
+ server._emit("connection.update", sid, connector_ui_payload(payload))
def _install_update_hook():
- """Route every operation change through ``_connection_update``. Idempotent: ``register`` can run
- more than once (reload, tests) and must not stack wrappers."""
from tools.connectors import operation as op_module
if getattr(op_module.ConnectionOperation, "_update_hook_installed", False):
diff --git a/tui_gateway/methods_connectors_account.py b/tui_gateway/methods_connectors_account.py
new file mode 100644
index 00000000000..7094de64fbd
--- /dev/null
+++ b/tui_gateway/methods_connectors_account.py
@@ -0,0 +1,279 @@
+from tui_gateway.contracts.connectors import (
+ ConnectorAccountsParams,
+ ConnectorAccountsRemoveParams,
+ ConnectorErrorReason,
+ ConnectorPolicySetParams,
+ ConnectorToolsParams,
+)
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+method = _registry.method
+_profile_scoped = _registry.profile_scoped
+
+
+def _account_method(params_model=None, *, invalid="", invalid_reason=ConnectorErrorReason.invalid_params,
+ unavailable, unavailable_message):
+ def decorate(fn):
+ def handler(rid, params):
+ from pydantic import ValidationError
+ from tools.connectors import connectors_available
+ from tools.connectors.gateway.errors import GatewayAuthError
+ from tui_gateway.contracts.connectors import ConnectorErrorReason
+
+ if not connectors_available():
+ return _connector_rpc_error(
+ rid, 4031, ConnectorErrorReason.connectors_unavailable, "Connectors are not available."
+ )
+ try:
+ request = params if params_model is None else params_model.model_validate(params)
+ except ValidationError:
+ return _connector_rpc_error(rid, 4000, invalid_reason, invalid)
+ try:
+ return fn(rid, request)
+ except GatewayAuthError as exc:
+ return _connector_auth_error(rid, exc)
+ except Exception as exc:
+ if getattr(exc, "code", None) == "org_required":
+ return _connector_rpc_error(
+ rid, 4090, ConnectorErrorReason.org_required, "Select an organization to manage connector rules."
+ )
+ return _connector_rpc_error(rid, 5034, unavailable, unavailable_message)
+
+ return handler
+
+ return decorate
+
+
+@method("connectors.tools")
+@_profile_scoped
+@_account_method(
+ ConnectorToolsParams,
+ invalid="slug and refresh are required parameters",
+ unavailable=ConnectorErrorReason.tools_unavailable,
+ unavailable_message="Connector tools are unavailable.",
+)
+def _(rid, request):
+ from tools.connectors.gateway.errors import GatewayUnavailable
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tools.connectors.portal.errors import InvalidConnectorSlug
+ from tools.connectors.portal.tools_cache import read_tools
+ from tui_gateway.contracts.connectors import ConnectorErrorReason, ConnectorToolsResult
+
+ client = PortalConnectorClient()
+ client.require_authentication()
+ try:
+ listing = read_tools(request.slug, client=client, refresh=request.refresh)
+ except (InvalidConnectorSlug, GatewayUnavailable):
+ return _connector_rpc_error(rid, 4041, ConnectorErrorReason.connector_not_found, "Connector not found.")
+ return _ok(rid, ConnectorToolsResult.model_validate(listing, from_attributes=True).model_dump(mode="json"))
+
+
+@method("connectors.catalog")
+@_profile_scoped
+@_account_method(
+ unavailable=ConnectorErrorReason.catalog_unavailable,
+ unavailable_message="Connector catalog is unavailable.",
+)
+def _(rid, _params):
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tui_gateway.contracts.connectors import ConnectorsCatalogResult
+
+ client = PortalConnectorClient()
+ client.require_authentication()
+ catalog = client.catalog()
+ return _ok(rid, ConnectorsCatalogResult.model_validate(catalog, from_attributes=True).model_dump(mode="json"))
+
+
+@method("connectors.accounts")
+@_profile_scoped
+@_account_method(
+ ConnectorAccountsParams,
+ invalid="connector must be a slug.",
+ unavailable=ConnectorErrorReason.accounts_unavailable,
+ unavailable_message="Connector accounts are unavailable.",
+)
+def _(rid, request):
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tui_gateway.contracts.connectors import ConnectorAccountRow, ConnectorAccountsResult
+
+ accounts = PortalConnectorClient().list_accounts()
+ rows = [account for account in accounts if request.connector is None or account["connector"] == request.connector]
+ result = ConnectorAccountsResult(accounts=[ConnectorAccountRow(
+ connection_id=account["connectionId"],
+ connector=account["connector"],
+ status=account["status"],
+ status_reason=account.get("statusReason"),
+ label=account["label"],
+ alias=account.get("alias"),
+ active=account["active"],
+ created_at=account["createdAt"],
+ updated_at=account["updatedAt"],
+ ) for account in rows])
+ return _ok(rid, result.model_dump(mode="json"))
+
+
+@method("connectors.accounts.remove")
+@_profile_scoped
+@_account_method(
+ ConnectorAccountsRemoveParams,
+ invalid="connection_id is required.",
+ unavailable=ConnectorErrorReason.accounts_unavailable,
+ unavailable_message="Connector accounts are unavailable.",
+)
+def _(rid, request):
+ from tools.connectors.gateway.errors import GatewayAuthError, GatewayUnavailable, ToolGatewayError
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tui_gateway.contracts.connectors import ConnectorAccountsRemoveResult, ConnectorErrorReason
+
+ try:
+ removed = PortalConnectorClient().delete_account(request.connection_id)
+ except GatewayUnavailable as exc:
+ if exc.code == "connection_not_found":
+ return _connector_rpc_error(rid, 4041, ConnectorErrorReason.connection_not_found, "Connector account not found.")
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.accounts_unavailable, "Connector accounts are unavailable.")
+ except GatewayAuthError:
+ raise
+ except ToolGatewayError as exc:
+ if exc.code == "org_required":
+ raise
+ if exc.code == "invalid_connection_id":
+ return _connector_rpc_error(rid, 4000, ConnectorErrorReason.invalid_params, "Connection id is invalid.")
+ return _connector_rpc_error(rid, 5034, ConnectorErrorReason.accounts_unavailable, "Connector accounts are unavailable.")
+ result = ConnectorAccountsRemoveResult(
+ connection_id=removed["connectionId"], connector=removed["connector"], status=removed["status"]
+ )
+ return _ok(rid, result.model_dump(mode="json"))
+
+
+@method("connectors.policy.get")
+@_profile_scoped
+@_account_method(
+ unavailable=ConnectorErrorReason.policy_unavailable,
+ unavailable_message="Connector policy is unavailable.",
+)
+def _(rid, _params):
+ from tools.connectors.gateway.errors import GatewayAuthError, ToolGatewayError
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tui_gateway.contracts.connectors import ConnectorErrorReason, ConnectorPolicyGetResult, ConnectorPolicyLayer
+
+ try:
+ client = PortalConnectorClient()
+ client.require_authentication()
+ policy = client.policy()
+ except GatewayAuthError as exc:
+ return _connector_rpc_error(rid, *_policy_auth_error(exc, ConnectorErrorReason))
+ except ToolGatewayError as exc:
+ return _connector_rpc_error(rid, *_policy_error(exc, ConnectorErrorReason))
+ result = ConnectorPolicyGetResult(
+ layers=[
+ ConnectorPolicyLayer(kind=layer.kind, revision=layer.revision, body=_contract_policy_body(layer.body))
+ for layer in policy.layers
+ ],
+ effective=_contract_policy_effective(policy.effective),
+ )
+ return _ok(rid, result.model_dump(mode="json"))
+
+
+@method("connectors.policy.set")
+@_profile_scoped
+@_account_method(
+ ConnectorPolicySetParams,
+ invalid="Connector parameters are invalid.",
+ unavailable=ConnectorErrorReason.policy_unavailable,
+ unavailable_message="Connector policy is unavailable.",
+)
+def _(rid, request):
+ from tools.connectors.gateway.errors import GatewayAuthError, ToolGatewayError
+ from tools.connectors.portal.client import PortalConnectorClient
+ from tools.connectors.portal.policy import InvalidMemberPolicy, compose_connector_write, compose_tools_write
+ from tui_gateway.contracts.connectors import ConnectorErrorReason, ConnectorPolicySetResult, ToolsChange
+
+ try:
+ client = PortalConnectorClient()
+ client.require_authentication()
+ policy = client.policy()
+ member = next((layer.body for layer in policy.layers if layer.kind == "member"), None)
+ compose = compose_tools_write if isinstance(request.change, ToolsChange) else compose_connector_write
+ body = compose(member, request.change)
+ body["expectedRevision"] = request.expected_revision
+ result = client.set_policy(body)
+ except GatewayAuthError as exc:
+ return _connector_rpc_error(rid, *_policy_auth_error(exc, ConnectorErrorReason))
+ except InvalidMemberPolicy:
+ return _connector_rpc_error(rid, 4000, ConnectorErrorReason.invalid_policy, "Connector policy change is invalid.")
+ except ToolGatewayError as exc:
+ return _connector_rpc_error(rid, *_policy_error(exc, ConnectorErrorReason))
+ return _ok(rid, ConnectorPolicySetResult(
+ revision=result.revision, effective=_contract_policy_effective(result.effective)
+ ).model_dump(mode="json"))
+
+
+def _policy_rule_fields(body):
+ from tui_gateway.contracts.connectors import ConnectorPolicyTags
+
+ if body.mode in ("unrestricted", "deny-all"):
+ return {}
+ tags = None if body.tags is None else ConnectorPolicyTags(enable=body.tags.enable, disable=body.tags.disable)
+ rules = {"tools": {connector: rule.disable for connector, rule in body.tools.items()}, "tags": tags}
+ if body.mode == "allow":
+ return {"connectors": body.connectors, **rules}
+ return {"disabled_connectors": body.disabled_connectors, **rules}
+
+
+def _contract_policy_body(body):
+ from tui_gateway.contracts import connectors as contract
+
+ models = {
+ "unrestricted": contract.ConnectorPolicyUnrestrictedBody,
+ "deny-all": contract.ConnectorPolicyDenyAllBody,
+ "allow": contract.ConnectorPolicyAllowBody,
+ "deny": contract.ConnectorPolicyDenyBody,
+ }
+ return models[body.mode](mode=body.mode, **_policy_rule_fields(body))
+
+
+def _contract_policy_effective(effective):
+ from tui_gateway.contracts import connectors as contract
+
+ models = {
+ "unrestricted": contract.ConnectorPolicyEffectiveUnrestricted,
+ "deny-all": contract.ConnectorPolicyEffectiveDenyAll,
+ "allow": contract.ConnectorPolicyEffectiveAllow,
+ "deny": contract.ConnectorPolicyEffectiveDeny,
+ }
+ return models[effective.mode](
+ mode=effective.mode, version=effective.version, revision=effective.revision,
+ issued_at_ms=effective.issued_at_ms, **_policy_rule_fields(effective),
+ )
+
+
+def _policy_auth_error(exc, reasons):
+ if exc.code in {"no_access", "ORG_ACCESS_DENIED"}:
+ return 4030, reasons.org_access_denied, "This account cannot manage connectors for this organization."
+ if exc.code == "forbidden":
+ return 4030, reasons.forbidden_scope, "Connector policy cannot be changed for this member."
+ if exc.status == 401 or exc.code in {"invalid_token", "INVALID_TOKEN", "NO_TOKEN"}:
+ return 4032, reasons.needs_nous_auth, "Sign in to use connectors."
+ return 5034, reasons.policy_unavailable, "Connector policy is unavailable."
+
+
+def _policy_error(exc, reasons):
+ by_code = {
+ "policy_changed": (4090, reasons.policy_conflict, "Connector policy changed. Refresh and try again."),
+ "org_required": (4090, reasons.org_required, "Select an organization to manage connector rules."),
+ "forbidden": (4030, reasons.forbidden_scope, "Connector policy cannot be changed for this member."),
+ "no_access": (4030, reasons.org_access_denied, "This account cannot manage connectors for this organization."),
+ "invalid_connector_policy": (4000, reasons.invalid_policy, "Connector policy change is invalid."),
+ }
+ if exc.code in by_code:
+ return by_code[exc.code]
+ if exc.code == f"HTTP_{exc.status}" and exc.status == 400:
+ return 4000, reasons.invalid_policy, "Connector policy change is invalid."
+ return 5034, reasons.policy_unavailable, "Connector policy is unavailable."
+
+
+def register(server):
+ bind_module(globals(), server, skip=("_",))
+ server._LONG_HANDLERS = server._LONG_HANDLERS | _registry.names()
diff --git a/tui_gateway/rpc_dispatch.py b/tui_gateway/rpc_dispatch.py
index fecbe5ef0df..17bb684f137 100644
--- a/tui_gateway/rpc_dispatch.py
+++ b/tui_gateway/rpc_dispatch.py
@@ -68,7 +68,8 @@ def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:
return _err(req.get("id"), 5035, "backend is retiring; reconnect to continue")
try:
ctx = contextvars.copy_context() # the pool worker must see the bound transport
- if normalized[1] in _CONNECTOR_RPC_METHODS:
+ owner = normalized[2].get("owner")
+ if normalized[1] in _CONNECTOR_RPC_METHODS and isinstance(owner, dict) and owner.get("type") == "session":
ctx.run(_capture_connector_rpc_owner, normalized[2])
def run():
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 25b5fa40105..aa4e993ca08 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2046,7 +2046,7 @@ def _current_profile_name() -> str:
# v5 ws_max_size >16 MiB file.attach frames; v6 plugins.manage rows carry the canonical registry key;
# v7 blocking prompts are JSON-RPC server->client requests (`srq-<n>` frames, `open_requests` replay) — a v6
# backend still emits `<kind>.request` notifications the renderer no longer listens for.
-DESKTOP_BACKEND_CONTRACT = 7
+DESKTOP_BACKEND_CONTRACT = 8
def _session_usage_snapshot(session: dict | None) -> dict:
@@ -3329,7 +3329,7 @@ from . import ( # noqa: E402
methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,
methods_session_control as _methods_session_control, methods_subagents as _methods_subagents,
methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,
- methods_connectors as _methods_connectors)
+ methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account)
for _m in (
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@ -3339,6 +3339,7 @@ for _m in (
_methods_browser_control, _methods_session, _methods_prompt, _methods_config,
_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
- _methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors):
+ _methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,
+ _methods_connectors_account):
_m.register(sys.modules[__name__])
del _m
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index 9c71e76a1d3..af1954877b9 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -15,6 +15,12 @@ _DISCORD_TRIGGERING_NOTE_RE = re.compile(
)
+def _bridged_tool_labels(name: str, args: dict) -> list[dict]:
+ from agent.display import tool_labels_for_call
+
+ return [label.as_payload() for label in tool_labels_for_call(name, args)]
+
+
def _active_image_routing_identity(agent: Any) -> tuple[str, str]:
"""Return the live provider/model, falling back before agent startup."""
from agent.auxiliary_client import _read_main_model, _read_main_provider
@@ -222,7 +228,9 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
name = tc_name or m.get("tool_name") or "tool"
args = tc_args or {}
# `context` is an 80-char preview; ship args so a full-call renderer isn't truncated.
- messages.append({"role": "tool", "name": name, "context": _tool_ctx(name, args), **({"args": args} if args else {})})
+ labels = _bridged_tool_labels(name, args)
+ messages.append({"role": "tool", "name": name, "context": _tool_ctx(name, args),
+ **({"args": args} if args else {}), **({"labels": labels} if labels else {})})
continue
# Assistant detail sidecars can carry the only visible reply or reasoning after resume/reload.
has_assistant_detail = role == "assistant" and any(m.get(key) for key in _HISTORY_ASSISTANT_DETAIL_KEYS)
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index 5176a3a14f5..3c8efff65c4 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -188,6 +188,12 @@ def _todo_state_from_history(history) -> dict | None:
return None
+def _tool_labels(name: str, args: dict) -> list[dict] | None:
+ from agent.display import tool_labels_for_call
+
+ return [label.as_payload() for label in tool_labels_for_call(name, args)] or None
+
+
def _connector_tool_lifecycle(name: str, args: dict) -> bool:
from tools.connectors import is_connector_name
@@ -243,6 +249,8 @@ def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
if (_tool_progress_enabled(sid) or _tool_lifecycle_required_for_ui(name)
or _connector_tool_lifecycle(name, args)):
payload: dict[str, object] = {"tool_id": tool_call_id, "name": name, "context": _tool_ctx(name, args)}
+ if (labels := _tool_labels(name, args)) is not None:
+ payload["labels"] = labels
# Full args (not just the 80-char `context` preview) so the desktop's expanded tool row is complete
# while the tool runs. args.todos may be a partial merge — tool.complete is the truth.
if args:
@@ -256,6 +264,8 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
if _connector_lifecycle_is_stale(sid, name, args):
return
payload = {"tool_id": tool_call_id, "name": name, "args": args}
+ if (labels := _tool_labels(name, args)) is not None:
+ payload["labels"] = labels
session = _sessions.get(sid)
snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None) if session is not None else None
started_at = session.setdefault("tool_started_at", {}).pop(tool_call_id, None) if session is not None else None
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index 3a4c8e84c37..d3cd31a30d5 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -1,7 +1,11 @@
import type { ConnectionOperationTarget } from '@hermes/shared/gateway-events'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { $connectionOperation, resetConnectionOperationsForTests } from '../app/connectionOperationStore.js'
+import {
+ $connectionOperation,
+ dismissConnectionOperation,
+ resetConnectionOperationsForTests
+} from '../app/connectionOperationStore.js'
import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'
import { createServerRequestHandler } from '../app/createServerRequestHandler.js'
import { getOverlayState, patchOverlayState, resetOverlayState } from '../app/overlayStore.js'
@@ -93,7 +97,8 @@ describe('createGatewayEventHandler', () => {
it('heals missed completion and blocking prompts only from the focused authoritative idle snapshot', () => {
patchUiState({ sid: 'focused' })
- const onEvent = createGatewayEventHandler(buildCtx([]))
+ const ctx = buildCtx([])
+ const onEvent = createGatewayEventHandler(ctx)
onEvent({ session_id: 'focused', payload: {}, type: 'message.start' } as any)
serverRequest('approval', { session_id: 'focused', request_id: 'approval', command: 'test' })
const busyOverlay = getOverlayState().approval
@@ -138,6 +143,35 @@ describe('createGatewayEventHandler', () => {
type: 'connection.update'
})
expect($connectionOperation.get()).toMatchObject({ seq: 2, targets: [target] })
+
+ // Esc on the "Finishing…" card drops it and it must not come back on a replay, but the settling
+ // frame that follows still records how each app ended.
+ const request = {
+ deadline_at: 10,
+ op_id: 'op-1',
+ seq: 2,
+ targets: [target],
+ timeout_seconds: 30
+ }
+
+ dismissConnectionOperation('op-1')
+ expect($connectionOperation.get()).toBeNull()
+ onEvent({ session_id: 'focused', payload: request, type: 'connection.request' })
+ expect($connectionOperation.get()).toBeNull()
+ expect(getOverlayState().connection).toBeNull()
+
+ onEvent({
+ session_id: 'focused',
+ payload: {
+ deadline_at: 12,
+ op_id: 'op-1',
+ seq: 3,
+ settled: true,
+ targets: [{ ...target, state: 'connected' }]
+ },
+ type: 'connection.update'
+ })
+ expect(ctx.system.sys.mock.calls.map((call: unknown[]) => call[0])).toEqual(['asana: connected'])
})
it('keeps the durable session id when a session.info payload omits it', () => {
diff --git a/ui-tui/src/app/connectionOperationStore.ts b/ui-tui/src/app/connectionOperationStore.ts
index defa08e53df..7295f5c19c6 100644
--- a/ui-tui/src/app/connectionOperationStore.ts
+++ b/ui-tui/src/app/connectionOperationStore.ts
@@ -21,41 +21,75 @@ export interface ConnectionOverlayState {
export const $connectionOperation = atom<ConnectionOperationSnapshot | null>(null)
-const settledOperationIds = new Set<string>()
+const OPERATION_MEMORY = 64
+const settledOperationIds: string[] = []
+const dismissedOperationIds: string[] = []
-export function applyConnectionRequest(payload: ConnectionRequestPayload): void {
- const current = $connectionOperation.get()
-
- if (settledOperationIds.has(payload.op_id)) {
+function remember(opIds: string[], opId: string): void {
+ if (opIds.includes(opId)) {
return
}
- if (current?.opId === payload.op_id && payload.seq <= current.seq) {
+ opIds.push(opId)
+
+ if (opIds.length > OPERATION_MEMORY) {
+ opIds.shift()
+ }
+}
+
+export const isSettledOperation = (opId: string): boolean => settledOperationIds.includes(opId)
+
+export const isDismissedOperation = (opId: string): boolean => dismissedOperationIds.includes(opId)
+
+const outcomeWord = (target: ConnectionOperationTarget): string => {
+ if (target.state === 'connected') {
+ return 'connected'
+ }
+
+ return target.state === 'skipped' ? 'skipped' : 'not connected'
+}
+
+export function applyConnectionRequest(payload: ConnectionRequestPayload): void {
+ if (isSettledOperation(payload.op_id) || isDismissedOperation(payload.op_id)) {
return
}
- $connectionOperation.set({
- deadlineAt: payload.deadline_at,
- opId: payload.op_id,
- seq: payload.seq,
- targets: payload.targets,
- toolCallId: payload.tool_call_id ?? null
- })
+ const current = $connectionOperation.get()
+ const older = current?.opId === payload.op_id && payload.seq <= current.seq
+
+ if (!older) {
+ $connectionOperation.set({
+ deadlineAt: payload.deadline_at,
+ opId: payload.op_id,
+ seq: payload.seq,
+ targets: payload.targets,
+ toolCallId: payload.tool_call_id ?? null
+ })
+ }
+
patchOverlayState({ connection: { opId: payload.op_id } })
}
-export function applyConnectionUpdate(payload: ConnectionUpdatePayload): void {
+export function applyConnectionUpdate(payload: ConnectionUpdatePayload): string[] {
const current = $connectionOperation.get()
-
- if (!current || current.opId !== payload.op_id || payload.seq <= current.seq) {
- return
- }
+ const shown = current !== null && current.opId === payload.op_id
if (payload.settled) {
- settledOperationIds.add(payload.op_id)
- clearConnectionOperation()
+ remember(settledOperationIds, payload.op_id)
- return
+ if (!shown && !isDismissedOperation(payload.op_id)) {
+ return []
+ }
+
+ if (shown) {
+ clearConnectionOperation()
+ }
+
+ return payload.targets.map(target => `${target.name}: ${outcomeWord(target)}`)
+ }
+
+ if (!shown || !current || payload.seq <= current.seq) {
+ return []
}
$connectionOperation.set({
@@ -64,6 +98,9 @@ export function applyConnectionUpdate(payload: ConnectionUpdatePayload): void {
seq: payload.seq,
targets: payload.targets
})
+ patchOverlayState({ connection: { opId: payload.op_id } })
+
+ return []
}
export function clearConnectionOperation(): void {
@@ -71,7 +108,14 @@ export function clearConnectionOperation(): void {
patchOverlayState({ connection: null })
}
+/** Esc on the card: the outcome is still wanted, but this card must never come back. */
+export function dismissConnectionOperation(opId: string): void {
+ remember(dismissedOperationIds, opId)
+ clearConnectionOperation()
+}
+
export function resetConnectionOperationsForTests(): void {
- settledOperationIds.clear()
+ settledOperationIds.length = 0
+ dismissedOperationIds.length = 0
clearConnectionOperation()
}
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 5e7a8cebbb6..ced683d85ad 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -803,7 +803,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
case 'connection.update':
if (ev.payload) {
- applyConnectionUpdate(ev.payload)
+ // The settling frame is the only record of how each app ended; the card is gone by then.
+ for (const line of applyConnectionUpdate(ev.payload)) {
+ sys(line)
+ }
}
return
@@ -1265,7 +1268,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
ev.payload.tool_id,
ev.payload.name ?? 'tool',
ev.payload.context ?? '',
- ev.payload.args_text ? stripAnsi(String(ev.payload.args_text)) : undefined
+ ev.payload.args_text ? stripAnsi(String(ev.payload.args_text)) : undefined,
+ ev.payload.labels ?? undefined
)
return
@@ -1293,7 +1297,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
ev.payload.tool_id,
ev.payload.name,
ev.payload.duration_s ?? undefined,
- resultText
+ resultText,
+ ev.payload.labels ?? undefined
)
} else {
turnController.recordToolComplete(
@@ -1302,7 +1307,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
ev.payload.summary ?? undefined,
ev.payload.duration_s ?? undefined,
ev.payload.todos ?? undefined,
- resultText
+ resultText,
+ ev.payload.labels ?? undefined
)
}
diff --git a/ui-tui/src/app/overlayStore.ts b/ui-tui/src/app/overlayStore.ts
index e36ac0a2235..e5322213190 100644
--- a/ui-tui/src/app/overlayStore.ts
+++ b/ui-tui/src/app/overlayStore.ts
@@ -152,6 +152,9 @@ export const resetOverlayState = () => $overlayState.set(buildOverlayState())
* shouldn't vanish when a turn ends. Called from turnController.idle() on
* every turn completion / interrupt; the old "reset everything" behaviour
* silently closed /agents the moment delegation finished.
+ *
+ * `connection` is preserved too: the card belongs to a backend operation that outlives the turn's
+ * idle edge, and only the operation's own settlement may close it.
*/
export const resetFlowOverlays = () =>
$overlayState.set({
@@ -159,6 +162,7 @@ export const resetFlowOverlays = () =>
agents: $overlayState.get().agents,
agentsInitialHistoryIndex: $overlayState.get().agentsInitialHistoryIndex,
ambient: $overlayState.get().ambient,
+ connection: $overlayState.get().connection,
widget: $overlayState.get().widget,
journey: $overlayState.get().journey,
modelPicker: $overlayState.get().modelPicker,
diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.ts
index b3ef1a431b9..e91462e6b86 100644
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@ -1,4 +1,4 @@
-import type { MessageCompletePayload, SubagentEventPayload } from '@hermes/shared/gateway-events'
+import type { MessageCompletePayload, SubagentEventPayload, ToolLabel } from '@hermes/shared/gateway-events'
import {
REASONING_PULSE_MS,
@@ -12,12 +12,14 @@ import { appendToolShelfMessage, isToolShelfMessage } from '../lib/liveProgress.
import { hasReasoningTag, splitReasoning } from '../lib/reasoning.js'
import {
boundedLiveRenderText,
- buildToolTrailLine,
- buildVerboseToolTrailLine,
estimateTokensRough,
+ formatToolCall,
+ formatToolLabel,
isTransientTrailLine,
sameToolTrailGroup,
- toolTrailLabel
+ toolTrailLabel,
+ toolTrailLine,
+ verboseToolTrailLine
} from '../lib/text.js'
import type { ActiveTool, ActivityItem, Msg, SubagentProgress, TodoItem } from '../types.js'
@@ -27,6 +29,28 @@ import { pushSnapshot } from './spawnHistoryStore.js'
import { archiveDoneTodos, getTurnState, patchTurnState, resetTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
+function toolTrailLines(
+ done: ActiveTool | undefined,
+ name: string,
+ labels: readonly ToolLabel[],
+ summary: string,
+ resultText: string,
+ took?: number
+): string[] {
+ const heads = labels.length ? labels.map(formatToolLabel) : [formatToolCall(name, done?.context || '')]
+ const verbose = Boolean(done?.verboseArgs || resultText)
+
+ return heads.map((head, index) => {
+ if (index < heads.length - 1) {
+ return toolTrailLine(head)
+ }
+
+ return verbose
+ ? verboseToolTrailLine(head, false, took, done?.verboseArgs, resultText || summary)
+ : toolTrailLine(head, false, summary, took)
+ })
+}
+
const INTERRUPT_COOLDOWN_MS = 1500
const ACTIVITY_LIMIT = 8
const TRAIL_LIMIT = 8
@@ -801,16 +825,17 @@ class TurnController {
summary?: string,
duration?: number,
todos?: unknown,
- resultText?: string
+ resultText?: string,
+ labels?: ToolLabel[]
) {
if (this.interrupted) {
return
}
this.recordTodos(todos)
- const line = this.completeTool(toolId, fallbackName, summary, duration, resultText)
+ const lines = this.completeTool(toolId, fallbackName, summary, duration, resultText, labels)
- this.pendingSegmentTools = [...this.pendingSegmentTools, line]
+ this.pendingSegmentTools = [...this.pendingSegmentTools, ...lines]
this.flushPendingToolsIntoLastSegment()
this.publishToolState()
}
@@ -820,14 +845,15 @@ class TurnController {
toolId: string,
fallbackName?: string,
duration?: number,
- resultText?: string
+ resultText?: string,
+ labels?: ToolLabel[]
) {
if (this.interrupted) {
return
}
this.flushStreamingSegment()
- this.pushInlineDiffSegment(diffText, [this.completeTool(toolId, fallbackName, '', duration, resultText)])
+ this.pushInlineDiffSegment(diffText, this.completeTool(toolId, fallbackName, '', duration, resultText, labels))
this.publishToolState()
}
@@ -838,24 +864,17 @@ class TurnController {
fallbackName?: string,
summary?: string,
duration?: number,
- resultText?: string
+ resultText?: string,
+ eventLabels?: ToolLabel[]
) {
const done = this.activeTools.find(tool => tool.id === toolId)
const name = done?.name ?? fallbackName ?? 'tool'
const label = toolTrailLabel(name)
+ const labels = eventLabels?.length ? eventLabels : (done?.labels ?? [])
const fallbackDuration = done?.startedAt ? (Date.now() - done.startedAt) / 1000 : undefined
+ const took = duration ?? fallbackDuration
- const line =
- done?.verboseArgs || resultText
- ? buildVerboseToolTrailLine(
- name,
- done?.context || '',
- false,
- duration ?? fallbackDuration,
- done?.verboseArgs,
- resultText || summary || ''
- )
- : buildToolTrailLine(name, done?.context || '', false, summary || '', duration ?? fallbackDuration)
+ const lines = toolTrailLines(done, name, labels, summary || '', resultText || '', took)
this.activeTools = this.activeTools.filter(tool => tool.id !== toolId)
@@ -867,7 +886,7 @@ class TurnController {
this.turnTools = next.slice(-TRAIL_LIMIT)
- return line
+ return lines
}
private publishToolState() {
@@ -878,7 +897,7 @@ class TurnController {
})
}
- recordToolStart(toolId: string, name: string, context: string, verboseArgs?: string) {
+ recordToolStart(toolId: string, name: string, context: string, verboseArgs?: string, labels?: ToolLabel[]) {
if (this.interrupted) {
return
}
@@ -891,7 +910,7 @@ class TurnController {
const sample = `${name} ${context}`.trim()
this.toolTokenAcc += sample ? estimateTokensRough(sample) : 0
- this.activeTools = [...this.activeTools, { context, id: toolId, name, startedAt: Date.now(), verboseArgs }]
+ this.activeTools = [...this.activeTools, { context, id: toolId, labels, name, startedAt: Date.now(), verboseArgs }]
patchTurnState({ toolTokens: this.toolTokenAcc, tools: this.activeTools })
}
diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.ts
index 2b399be04e3..27867214f52 100644
--- a/ui-tui/src/app/useInputHandlers.ts
+++ b/ui-tui/src/app/useInputHandlers.ts
@@ -238,6 +238,23 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
return
}
+ // The connection card has no local dismissal: the operation belongs to the running turn, so
+ // ending the turn is what settles it (as `interrupt`) and closes the card.
+ if (overlay.connection) {
+ const sid = getUiState().sid
+
+ if (!sid) {
+ return
+ }
+
+ return turnController.interruptTurn({
+ appendMessage: actions.appendMessage,
+ gw: gateway.gw,
+ sid,
+ sys: actions.sys
+ })
+ }
+
if (overlay.sudo || overlay.secret || overlay.vaultUnlock) {
return dismissSensitivePrompt(overlay, gateway.rpc, actions.sys)
}
@@ -415,7 +432,12 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {
// skip the prompt-overlay early-return for scroll keys so they fall
// through to the wheel / PageUp / Shift+arrow handlers below.
const promptOverlay =
- overlay.approval || overlay.billing || overlay.clarify || overlay.confirm || overlay.subscription
+ overlay.approval ||
+ overlay.billing ||
+ overlay.clarify ||
+ overlay.confirm ||
+ overlay.connection ||
+ overlay.subscription
const fallThroughForScroll = promptOverlay && shouldFallThroughForScroll(key)
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 3d00d44c8b8..5c89b56962f 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -302,6 +302,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
(id: string) => {
patchOverlayState({ sessions: false })
patchUiState({ status: 'switching session…' })
+ // The card belongs to the session being left; the activated one answers with its own.
+ clearConnectionOperation()
gw.request<SessionActivateResponse>('session.activate', { session_id: id })
.then(raw => {
@@ -333,6 +335,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
usage: usageFrom(info)
})
hydrateLiveSessionInflight(r.inflight)
+
+ if (r.pending_connection) {
+ applyConnectionRequest(r.pending_connection)
+ }
+
cancelResumeScrollRef.current?.()
cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
})
diff --git a/ui-tui/src/components/connectionSetupOverlay.tsx b/ui-tui/src/components/connectionSetupOverlay.tsx
index 7ed789ab65c..d39435742cc 100644
--- a/ui-tui/src/components/connectionSetupOverlay.tsx
+++ b/ui-tui/src/components/connectionSetupOverlay.tsx
@@ -2,12 +2,21 @@ import { Box, Text, useInput } from '@hermes/ink'
import type {
ConnectionOperationTarget,
ConnectionRespondParams,
- ConnectionTargetEnvField
+ ConnectionRespondResult,
+ ConnectionTargetAction,
+ ConnectionTargetEnvField,
+ ConnectionTargetState,
+ ConnectorsConnectResult
} from '@hermes/shared/gateway-events'
import { useStore } from '@nanostores/react'
-import { useEffect, useMemo, useState } from 'react'
-
-import { $connectionOperation, clearConnectionOperation } from '../app/connectionOperationStore.js'
+import { useEffect, useMemo, useRef, useState } from 'react'
+
+import type { ConnectionOperationSnapshot } from '../app/connectionOperationStore.js'
+import {
+ $connectionOperation,
+ dismissConnectionOperation,
+ isSettledOperation
+} from '../app/connectionOperationStore.js'
import { useGateway } from '../app/gatewayContext.js'
import { $uiSessionId } from '../app/uiStore.js'
import { openExternalUrl } from '../lib/openExternalUrl.js'
@@ -20,14 +29,27 @@ interface ConnectionSetupOverlayProps {
t: Theme
}
-interface FormKeyHandlers {
- cancel: () => void
- connect: () => void
- fieldCount: number
- selectorFocused: boolean
- setAction: (update: (value: 0 | 1) => 0 | 1) => void
- setFocus: (update: (value: number) => number) => void
- submitting: boolean
+type Phase = 'authorized' | 'browser' | 'form' | 'retry' | 'working'
+
+interface AnsweredRow {
+ name: string
+ seq: number
+ state: ConnectionTargetState
+}
+
+const SENDING_TIMEOUT_MS = 5_000
+
+type SendResult = ConnectionRespondResult | ConnectorsConnectResult
+
+const mayAnswer = (operation: ConnectionOperationSnapshot | null, sid: null | string, busy: boolean): boolean =>
+ Boolean(operation) && Boolean(sid) && !busy && !isSettledOperation(operation?.opId ?? '')
+
+const isSending = (operation: ConnectionOperationSnapshot | null, answered: AnsweredRow | null): boolean => {
+ if (!answered || !operation || operation.seq > answered.seq) {
+ return false
+ }
+
+ return operation.targets.find(item => item.name === answered.name)?.state === answered.state
}
interface InputKey {
@@ -41,65 +63,64 @@ interface InputKey {
upArrow: boolean
}
+const RESOLVED_STATES = ['connected', 'skipped', 'not_connected']
+
const isUnresolved = (target: ConnectionOperationTarget): boolean =>
- !['connected', 'skipped', 'expired', 'unavailable'].includes(target.state) || Boolean(target.discovery_error)
+ !RESOLVED_STATES.includes(target.state) || (target.state === 'connected' && Boolean(target.discovery_error))
+
+const VERB = {
+ authorize: 'Authorize',
+ connect: 'Connect',
+ enable: 'Enable',
+ install: 'Install',
+ reconnect: 'Reconnect'
+} satisfies Record<ConnectionTargetAction, string>
+
+const phaseOf = (target: ConnectionOperationTarget): Phase => {
+ if (target.state === 'connected') {
+ return 'authorized'
+ }
-const initialDraft = (fields: ConnectionTargetEnvField[]): Record<string, string> =>
- Object.fromEntries(fields.map(field => [field.name, field.secret ? '' : field.default]))
+ if (target.state === 'failed' || target.state === 'expired') {
+ return target.required_env?.length ? 'form' : 'retry'
+ }
-const fieldLabel = (field: ConnectionTargetEnvField): string => field.prompt || field.name
+ if (target.state === 'initiated') {
+ return target.connect_url ? 'browser' : 'working'
+ }
-const isAuthorizedWithoutTools = (target: ConnectionOperationTarget | null): boolean =>
- target?.state === 'connected' && Boolean(target.discovery_error)
+ return 'form'
+}
-const isAwaitingBrowser = (target: ConnectionOperationTarget | null): boolean =>
- target?.state === 'initiated' && Boolean(target.connect_url)
+const failureLine = (target: ConnectionOperationTarget): string =>
+ target.state === 'expired' ? 'The link expired.' : 'That did not work.'
-/** Key routing while the field list and the Connect/Cancel selector are on screen. */
-function handleFormKey(key: InputKey, h: FormKeyHandlers): void {
- const rows = h.fieldCount + 1
- const back = (value: number) => (value - 1 + rows) % rows
- const forward = (value: number) => (value + 1) % rows
+const hasFailed = (target: ConnectionOperationTarget): boolean =>
+ target.state === 'failed' || target.state === 'expired'
- if (h.submitting) {
- return
- }
+const initialDraft = (fields: ConnectionTargetEnvField[]): Record<string, string> =>
+ Object.fromEntries(fields.map(field => [field.name, field.secret ? '' : field.default]))
- if (key.shift && key.tab) {
- h.setFocus(back)
- } else if (key.tab || (key.downArrow && !h.selectorFocused)) {
- h.setFocus(forward)
- } else if (key.upArrow && !h.selectorFocused) {
- h.setFocus(back)
- } else if (h.selectorFocused && (key.leftArrow || key.rightArrow || key.upArrow || key.downArrow)) {
- h.setAction(value => (value === 0 ? 1 : 0))
- } else if (h.selectorFocused && key.return) {
- h.connect()
- }
-}
+const fieldLabel = (field: ConnectionTargetEnvField): string => field.prompt || field.name
-function AuthorizedWithoutTools({ error, t }: { error: string; t: Theme }) {
- return (
- <Box flexDirection="column">
- <Text bold color={t.color.ok}>
- Authorized. Tools unavailable.
- </Text>
- <Text color={t.color.muted}>{error}</Text>
- <Text color={t.color.accent}>▸ Continue</Text>
- <Text color={t.color.muted}>Esc close</Text>
- </Box>
- )
+interface HeaderProps {
+ more: number
+ t: Theme
+ target: ConnectionOperationTarget
}
-function AwaitingBrowser({ t, target }: { t: Theme; target: ConnectionOperationTarget }) {
+function Header({ more, t, target }: HeaderProps) {
return (
<Box flexDirection="column">
<Text bold color={t.color.text}>
- Set up {target.name}
+ {VERB[target.action]} {target.name}
</Text>
- <Text color={t.color.accent}>{target.connect_url}</Text>
- {target.detail ? <Text color={t.color.muted}>{target.detail}</Text> : null}
- <Text color={t.color.muted}>Press Enter to open in browser</Text>
+ {more > 0 ? <Text color={t.color.muted}>{more} more to answer after this one.</Text> : null}
+ {target.instructions ? (
+ <Text color={t.color.muted} wrap="wrap">
+ {target.instructions}
+ </Text>
+ ) : null}
</Box>
)
}
@@ -111,12 +132,12 @@ interface FieldRowProps {
focused: boolean
onChange: (value: string) => void
onSubmit: () => void
+ sending: boolean
showSet: boolean
- submitting: boolean
t: Theme
}
-function FieldRow({ cols, draftValue, field, focused, onChange, onSubmit, showSet, submitting, t }: FieldRowProps) {
+function FieldRow({ cols, draftValue, field, focused, onChange, onSubmit, sending, showSet, t }: FieldRowProps) {
return (
<Box flexDirection="column">
<Text color={focused ? t.color.accent : t.color.label}>
@@ -131,7 +152,8 @@ function FieldRow({ cols, draftValue, field, focused, onChange, onSubmit, showSe
<TextInput
color={t.color.text}
columns={Math.max(20, cols - 8)}
- focus={!submitting && focused}
+ focus={!sending && focused}
+ ignoreVerticalArrows
mask={field.secret ? '*' : undefined}
onChange={onChange}
onSubmit={onSubmit}
@@ -143,73 +165,198 @@ function FieldRow({ cols, draftValue, field, focused, onChange, onSubmit, showSe
)
}
-interface SetupFormProps {
+interface NavHandlers {
+ confirm: () => void
+ row: number
+ rows: number
+ selectorFocused: boolean
+ setAction: (update: (value: 0 | 1) => 0 | 1) => void
+ setFocus: (update: (value: number) => number) => void
+}
+
+function handleNavKey(key: InputKey, h: NavHandlers): void {
+ const up = key.upArrow && !key.shift
+ const down = key.downArrow && !key.shift
+ const back = () => (h.row - 1 + h.rows) % h.rows
+ const forward = () => (h.row + 1) % h.rows
+
+ if (key.shift && key.tab) {
+ h.setFocus(back)
+ } else if (key.tab || (down && !h.selectorFocused)) {
+ h.setFocus(forward)
+ } else if (up && !h.selectorFocused) {
+ h.setFocus(back)
+ } else if (h.selectorFocused && (key.leftArrow || key.rightArrow || up || down)) {
+ h.setAction(value => (value === 0 ? 1 : 0))
+ } else if (h.selectorFocused && key.return) {
+ h.confirm()
+ }
+}
+
+interface SelectorProps {
+ action: 0 | 1
+ focused: boolean
+ primary: string
+ t: Theme
+}
+
+function Selector({ action, focused, primary, t }: SelectorProps) {
+ return (
+ <Text color={focused ? t.color.accent : t.color.muted}>
+ {action === 0 ? '▸ ' : ' '}
+ {primary}
+ {' '}
+ {action === 1 ? '▸ ' : ' '}Skip
+ </Text>
+ )
+}
+
+interface PhaseProps {
+ more: number
+ notice: string
+ t: Theme
+ target: ConnectionOperationTarget
+}
+
+function DetailLine({ t, text }: { t: Theme; text: null | string | undefined }) {
+ return text ? (
+ <Text color={t.color.error} wrap="wrap">
+ {text}
+ </Text>
+ ) : null
+}
+
+function FinishingPhase({ t }: { t: Theme }) {
+ return (
+ <Box flexDirection="column">
+ <Text color={t.color.muted}>Finishing…</Text>
+ <Text color={t.color.muted}>Esc close · Ctrl+C stop the turn</Text>
+ </Box>
+ )
+}
+
+function AuthorizedPhase({ t, target }: { t: Theme; target: ConnectionOperationTarget }) {
+ return (
+ <Box flexDirection="column">
+ <Text bold color={t.color.ok}>
+ Authorized. Tools unavailable.
+ </Text>
+ <Text color={t.color.muted}>{target.discovery_error ?? ''}</Text>
+ <Text color={t.color.accent}>▸ Continue</Text>
+ <Text color={t.color.muted}>Enter or Esc continue</Text>
+ </Box>
+ )
+}
+
+function BrowserPhase({ more, notice, t, target }: PhaseProps) {
+ return (
+ <Box flexDirection="column">
+ <Header more={more} t={t} target={target} />
+ <Text color={t.color.accent}>{target.connect_url}</Text>
+ <DetailLine t={t} text={target.detail} />
+ <DetailLine t={t} text={notice} />
+ <Text color={t.color.muted}>Enter open in browser · Esc skip · Ctrl+C stop the turn</Text>
+ </Box>
+ )
+}
+
+function WorkingPhase({ more, notice, t, target }: PhaseProps) {
+ return (
+ <Box flexDirection="column">
+ <Header more={more} t={t} target={target} />
+ <Text color={t.color.muted}>Working…</Text>
+ <DetailLine t={t} text={target.detail} />
+ <DetailLine t={t} text={notice} />
+ <Text color={t.color.muted}>Esc skip · Ctrl+C stop the turn</Text>
+ </Box>
+ )
+}
+
+interface RetryPhaseProps extends PhaseProps {
+ action: 0 | 1
+ sending: boolean
+}
+
+function RetryPhase({ action, more, notice, sending, t, target }: RetryPhaseProps) {
+ return (
+ <Box flexDirection="column">
+ <Header more={more} t={t} target={target} />
+ <Text color={t.color.muted}>{failureLine(target)}</Text>
+ <DetailLine t={t} text={target.detail} />
+ <Selector action={action} focused primary="Try again" t={t} />
+ <DetailLine t={t} text={notice} />
+ {sending ? <Text color={t.color.muted}>Pending…</Text> : null}
+ <Text color={t.color.muted}>←/→ select · Enter confirm · Esc skip · Ctrl+C stop the turn</Text>
+ </Box>
+ )
+}
+
+interface FormPhaseProps extends PhaseProps {
action: 0 | 1
cols: number
draft: Record<string, string>
fields: ConnectionTargetEnvField[]
- focus: number
missingRequired: ConnectionTargetEnvField | undefined
onChange: (name: string, value: string) => void
onFieldSubmit: (index: number) => void
+ row: number
selectorFocused: boolean
+ sending: boolean
submittedSecrets: Set<string>
- submitting: boolean
- t: Theme
- target: ConnectionOperationTarget
}
-function SetupForm(p: SetupFormProps) {
+function FormPhase(p: FormPhaseProps) {
const { t, target } = p
+ const reopened = hasFailed(target)
return (
<Box flexDirection="column">
- <Text bold color={t.color.text}>
- Set up {target.name}
- </Text>
- {target.instructions ? (
- <Text color={t.color.muted} wrap="wrap">
- {target.instructions}
- </Text>
- ) : null}
+ <Header more={p.more} t={t} target={target} />
+ {reopened ? <Text color={t.color.muted}>{failureLine(target)}</Text> : null}
+ {reopened ? <DetailLine t={t} text={target.detail} /> : null}
{p.fields.map((field, index) => (
<FieldRow
cols={p.cols}
draftValue={p.draft[field.name] ?? ''}
field={field}
- focused={p.focus === index}
+ focused={p.row === index}
key={field.name}
onChange={value => p.onChange(field.name, value)}
onSubmit={() => p.onFieldSubmit(index)}
- showSet={p.submittedSecrets.has(field.name) && p.submitting}
- submitting={p.submitting}
+ sending={p.sending}
+ showSet={p.submittedSecrets.has(field.name) && p.sending}
t={t}
/>
))}
- {target.state === 'failed' && target.detail ? <Text color={t.color.error}>{target.detail}</Text> : null}
- <Text color={p.selectorFocused ? t.color.accent : t.color.muted}>
- {p.action === 0 ? '▸ ' : ' '}Connect {p.action === 1 ? '▸ ' : ' '}Cancel
- </Text>
+ {reopened ? null : <DetailLine t={t} text={target.detail} />}
+ <Selector action={p.action} focused={p.selectorFocused} primary={VERB[target.action]} t={t} />
{p.missingRequired ? <Text color={t.color.muted}>{fieldLabel(p.missingRequired)} is required.</Text> : null}
- {p.submitting ? <Text color={t.color.muted}>Pending…</Text> : null}
- <Text color={t.color.muted}>↑/↓ or Tab move · ←/→ select · Enter confirm · Esc cancel</Text>
+ <DetailLine t={t} text={p.notice} />
+ {p.sending ? <Text color={t.color.muted}>Pending…</Text> : null}
+ <Text color={t.color.muted}>↑/↓ or Tab move · ←/→ select · Enter confirm · Esc skip · Ctrl+C stop the turn</Text>
</Box>
)
}
-// The component owns one draft across backend snapshots; splitting it would remount and erase failed submissions.
export function ConnectionSetupOverlay({ cols, t }: ConnectionSetupOverlayProps) {
const operation = useStore($connectionOperation)
const sid = useStore($uiSessionId)
const { gw } = useGateway()
- const target = operation?.targets.find(isUnresolved) ?? null
+ const unresolved = operation?.targets.filter(isUnresolved) ?? []
+ const target = unresolved[0] ?? null
const fields = useMemo<ConnectionTargetEnvField[]>(() => target?.required_env ?? [], [target?.required_env])
const targetKey = `${operation?.opId ?? ''}:${target?.name ?? ''}`
const [draft, setDraft] = useState<Record<string, string>>(() => initialDraft(fields))
const [focus, setFocus] = useState(0)
const [action, setAction] = useState<0 | 1>(0)
- const [submitting, setSubmitting] = useState(false)
+ // The row that was answered and the state it was in. A frame for another row of the same
+ // operation must not clear it; that row's own next state does.
+ const [answered, setAnswered] = useState<AnsweredRow | null>(null)
const [submittedSecrets, setSubmittedSecrets] = useState<Set<string>>(() => new Set())
+ const [notice, setNotice] = useState('')
+ // One request at a time, so a held key cannot post the same answer again. It is cleared when the
+ // request settles either way, so no card state can end up unable to answer.
+ const inFlight = useRef(false)
// A new target starts clean. Every backend snapshot carries a freshly parsed required_env, so the
// same target's fields only fill in what the draft lacks: a failed Connect keeps what was typed.
@@ -217,19 +364,28 @@ export function ConnectionSetupOverlay({ cols, t }: ConnectionSetupOverlayProps)
setDraft({})
setFocus(0)
setAction(0)
- setSubmitting(false)
+ setAnswered(null)
setSubmittedSecrets(new Set())
+ setNotice('')
}, [targetKey])
useEffect(() => {
setDraft(current => ({ ...initialDraft(fields), ...current }))
}, [fields])
+ // The third way out of `sending`: the row gives its control back after the timeout even if no
+ // frame ever arrives, so Esc and Skip can never be disabled for good.
useEffect(() => {
- if (target?.state === 'failed') {
- setSubmitting(false)
+ if (!answered) {
+ return
}
+ const timer = setTimeout(() => setAnswered(null), SENDING_TIMEOUT_MS)
+
+ return () => clearTimeout(timer)
+ }, [answered])
+
+ useEffect(() => {
if (target?.state === 'connected') {
setDraft(current =>
Object.fromEntries(fields.map(field => [field.name, field.secret ? '' : (current[field.name] ?? '')]))
@@ -237,118 +393,188 @@ export function ConnectionSetupOverlay({ cols, t }: ConnectionSetupOverlayProps)
}
}, [fields, target?.state])
- useEffect(() => {
- if (operation && operation.targets.every(item => !isUnresolved(item))) {
- clearConnectionOperation()
- }
- }, [operation])
-
+ const phase = target ? phaseOf(target) : 'form'
+ const sending = isSending(operation, answered)
const missingRequired = fields.find(field => field.required && !draft[field.name]?.trim())
- const selectorFocused = focus === fields.length
+ const rows = phase === 'form' ? fields.length + 1 : 1
+ // A snapshot that drops a field leaves the old focus past the last row; the selector owns it.
+ const row = Math.min(focus, rows - 1)
+ const selectorFocused = phase === 'retry' || row === fields.length
+
+ const send = (start: () => Promise<SendResult>, failure: string) => {
+ inFlight.current = true
+ setNotice('')
+ void start()
+ .catch(() => {
+ setAnswered(null)
+ setNotice(failure)
+ })
+ .finally(() => {
+ inFlight.current = false
+ })
+ }
- const respond = (result: ConnectionRespondParams['result']) => {
- if (!operation || !sid || submitting) {
+ const respond = (result: ConnectionRespondParams['result'], answeredAt: AnsweredRow | null) => {
+ if (!operation || !sid || !mayAnswer(operation, sid, inFlight.current)) {
return
}
- setSubmitting(true)
- void gw
- .request('connection.respond', { op_id: operation.opId, result, session_id: sid })
- .catch(() => setSubmitting(false))
+ setAnswered(answeredAt)
+ send(
+ () =>
+ gw.request<ConnectionRespondResult>('connection.respond', {
+ op_id: operation.opId,
+ owner: { session_id: sid, type: 'session' },
+ result
+ }),
+ 'That answer did not reach Hermes. Try again.'
+ )
}
- const settleOnKey = (key: InputKey): boolean => {
- if (isAuthorizedWithoutTools(target)) {
- if (key.escape || key.return) {
- respond({ settled_by: 'continue' })
- }
+ const answeredNow = (): AnsweredRow | null =>
+ target && operation ? { name: target.name, seq: operation.seq, state: target.state } : null
- return true
+ const skip = () => {
+ if (!target || sending) {
+ return
}
- if (isAwaitingBrowser(target)) {
- if (key.return && target?.connect_url) {
- openExternalUrl(target.connect_url)
- }
+ respond({ targets: [{ name: target.name, status: 'skipped' }] }, answeredNow())
+ }
- return !key.escape
+ const connect = () => {
+ if (!target || sending) {
+ return
}
- return false
- }
+ if (missingRequired) {
+ const index = fields.indexOf(missingRequired)
- const cancel = () => {
- if (!target) {
- clearConnectionOperation()
+ setFocus(index < 0 ? 0 : index)
return
}
- respond({ targets: [{ name: target.name, status: 'skipped' }] })
+ setSubmittedSecrets(new Set(fields.filter(field => field.secret).map(field => field.name)))
+ respond({ targets: [{ env: draft, name: target.name, status: 'approved' }] }, answeredNow())
}
- const connect = () => {
- if (!target || missingRequired) {
- const index = missingRequired ? fields.indexOf(missingRequired) : 0
- setFocus(index < 0 ? 0 : index)
+ // Try again on a failed row with no credentials to correct: the desktop's re-mint, on the open
+ // operation, with this session as the owner.
+ const tryAgain = () => {
+ if (!target || !operation || !sid || sending || !mayAnswer(operation, sid, inFlight.current)) {
+ return
+ }
+ setAnswered(answeredNow())
+ send(
+ () =>
+ gw.request<ConnectorsConnectResult>('connectors.connect', {
+ connectors: [target.name],
+ owner: { session_id: sid, type: 'session' },
+ reconnect: true
+ }),
+ 'Hermes could not start that again. Try again.'
+ )
+ }
+
+ const openLink = () => {
+ if (!target?.connect_url) {
return
}
- setSubmittedSecrets(new Set(fields.filter(field => field.secret).map(field => field.name)))
- respond({ targets: [{ env: draft, name: target.name, status: 'approved' }] })
+ setNotice(openExternalUrl(target.connect_url) ? '' : 'The browser did not open. Copy the link above.')
}
- // A single input owner guarantees Esc and navigation cause exactly one action.
+ // A single input owner guarantees every key causes exactly one action. Esc skips the row in every
+ // phase; Ctrl+C reaches the global handler, which interrupts the turn.
useInput((_ch, key) => {
- if (settleOnKey(key)) {
+ // Every row is answered and the settling frame has not landed. Esc closes the card here, so no
+ // silence from the gateway can leave it with no way out. The id is remembered, so the settle
+ // that follows still writes its transcript lines and this card cannot return.
+ if (!target) {
+ if (key.escape && operation) {
+ dismissConnectionOperation(operation.opId)
+ }
+
+ return
+ }
+
+ if (phase === 'authorized') {
+ if ((key.escape || key.return) && !sending) {
+ respond({ settled_by: 'continue' }, answeredNow())
+ }
+
return
}
if (key.escape) {
- cancel()
+ return skip()
+ }
+
+ if (phase === 'browser') {
+ if (key.return) {
+ openLink()
+ }
return
}
- handleFormKey(key, {
- cancel,
- connect: () => (action === 0 ? connect() : cancel()),
- fieldCount: fields.length,
+ if (phase === 'working') {
+ return
+ }
+
+ handleNavKey(key, {
+ confirm: () => (action === 1 ? skip() : phase === 'retry' ? tryAgain() : connect()),
+ rows,
selectorFocused,
setAction,
setFocus,
- submitting
+ row
})
})
- if (!operation || !target) {
+ if (!operation) {
return null
}
- if (isAuthorizedWithoutTools(target)) {
- return <AuthorizedWithoutTools error={target.discovery_error ?? ''} t={t} />
+ // Every row is answered; the backend settles the operation and its frame closes the card.
+ if (!target) {
+ return <FinishingPhase t={t} />
+ }
+
+ if (phase === 'authorized') {
+ return <AuthorizedPhase t={t} target={target} />
+ }
+
+ const shared = { more: unresolved.length - 1, notice, t, target }
+
+ if (phase === 'browser') {
+ return <BrowserPhase {...shared} />
+ }
+
+ if (phase === 'working') {
+ return <WorkingPhase {...shared} />
}
- if (isAwaitingBrowser(target)) {
- return <AwaitingBrowser t={t} target={target} />
+ if (phase === 'retry') {
+ return <RetryPhase {...shared} action={action} sending={sending} />
}
return (
- <SetupForm
+ <FormPhase
+ {...shared}
action={action}
cols={cols}
draft={draft}
fields={fields}
- focus={focus}
missingRequired={missingRequired}
onChange={(name, value) => setDraft(current => ({ ...current, [name]: value }))}
onFieldSubmit={index => setFocus(index === fields.length - 1 ? fields.length : index + 1)}
+ row={row}
selectorFocused={selectorFocused}
+ sending={sending}
submittedSecrets={submittedSecrets}
- submitting={submitting}
- t={t}
- target={target}
/>
)
}
diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsx
index d35919f2312..172795a4f66 100644
--- a/ui-tui/src/components/textInput.tsx
+++ b/ui-tui/src/components/textInput.tsx
@@ -783,6 +783,7 @@ export function TextInput({
mask,
mouseApiRef,
cursorSnapshotRef,
+ ignoreVerticalArrows = false,
voiceRecordKey = DEFAULT_VOICE_RECORD_KEY,
placeholder = '',
placeholderColor,
@@ -1429,7 +1430,7 @@ export function TextInput({
return
}
- if (k.upArrow || k.downArrow) {
+ if ((k.upArrow || k.downArrow) && !ignoreVerticalArrows) {
flushKeyBurst()
const next = lineNav(vRef.current, curRef.current, k.upArrow ? -1 : 1)
@@ -1828,6 +1829,8 @@ interface TextInputProps {
columns?: number
cursorSnapshotRef?: MutableRefObject<InputCursorSnapshot | null>
focus?: boolean
+ /** Leave ↑/↓ to the owner: a form that moves field focus with them owns the key, not the field. */
+ ignoreVerticalArrows?: boolean
mask?: string
mouseApiRef?: MutableRefObject<null | TextInputMouseApi>
onChange: (v: string) => void
diff --git a/ui-tui/src/components/thinking.tsx b/ui-tui/src/components/thinking.tsx
index 222b8a0a150..7e21dfb0c61 100644
--- a/ui-tui/src/components/thinking.tsx
+++ b/ui-tui/src/components/thinking.tsx
@@ -20,6 +20,7 @@ import {
compactPreview,
estimateTokensRough,
formatToolCall,
+ formatToolLabels,
parseToolTrailResultLine,
pick,
splitToolDuration,
@@ -890,7 +891,8 @@ export const ToolTrail = memo(function ToolTrail({
}
for (const tool of tools) {
- const label = formatToolCall(tool.name, tool.context || '')
+ // A bridged call names its inner calls; anything else is still name + preview.
+ const label = tool.labels?.length ? formatToolLabels(tool.labels) : formatToolCall(tool.name, tool.context || '')
groups.push({
color: t.color.text,
diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.ts
index ec6cc4dea4a..832f8e028af 100644
--- a/ui-tui/src/gatewayTypes.ts
+++ b/ui-tui/src/gatewayTypes.ts
@@ -1,5 +1,6 @@
import type { UsageModelData } from '@hermes/shared/billing'
import type {
+ ConnectionRequestPayload,
GatewayEvent,
GatewayEventName,
InflightTurn,
@@ -208,6 +209,7 @@ export interface SessionActivateResponse {
info?: SessionInfo
message_count?: number
messages: TranscriptMessage[]
+ pending_connection?: ConnectionRequestPayload | null
running?: boolean
session_id: string
session_key?: string
diff --git a/ui-tui/src/lib/text.ts b/ui-tui/src/lib/text.ts
index 96c0ca05de9..b3a75529c2d 100644
--- a/ui-tui/src/lib/text.ts
+++ b/ui-tui/src/lib/text.ts
@@ -1,5 +1,6 @@
import { stripAnsi } from '@hermes/shared/ansi'
import { compactNumber } from '@hermes/shared/format'
+import type { ToolLabel } from '@hermes/shared/gateway-events'
import {
LIVE_RENDER_MAX_CHARS,
@@ -179,19 +180,31 @@ export const formatToolCall = (name: string, context = '') => {
return preview ? `${label}("${preview}")` : label
}
-export const buildToolTrailLine = (
- name: string,
- context: string,
- error?: boolean,
- note?: string,
- duration?: number
-) => {
+/** One row's worth of a bridged call: the gateway already phrased it, preview included. */
+export const formatToolLabel = (label: ToolLabel) =>
+ `${label.emoji} ${compactPreview(label.preview ? `${label.text} ${label.preview}` : label.text, 72)}`
+
+export const formatToolLabels = (labels: readonly ToolLabel[]) => {
+ const [first, ...rest] = labels
+
+ if (first === undefined) {
+ return ''
+ }
+
+ return rest.length > 0 ? `${formatToolLabel(first)} +${rest.length}` : formatToolLabel(first)
+}
+
+/** A finished trail row for an already-phrased call. */
+export const toolTrailLine = (call: string, error?: boolean, note?: string, duration?: number) => {
const detail = compactPreview(note ?? '', 72)
const took = duration !== undefined ? ` (${duration.toFixed(1)}s)` : ''
- return `${formatToolCall(name, context)}${took}${detail ? ` :: ${detail}` : ''} ${error ? '✗' : '✓'}`
+ return `${call}${took}${detail ? ` :: ${detail}` : ''} ${error ? '✗' : '✓'}`
}
+export const buildToolTrailLine = (name: string, context: string, error?: boolean, note?: string, duration?: number) =>
+ toolTrailLine(formatToolCall(name, context), error, note, duration)
+
const verboseToolBlock = (label: string, text?: string) => {
const body = (text ?? '').trim()
@@ -207,9 +220,9 @@ const verboseToolBlock = (label: string, text?: string) => {
: ''
}
-export const buildVerboseToolTrailLine = (
- name: string,
- context: string,
+/** The Args and Result blocks for an already-phrased call. */
+export const verboseToolTrailLine = (
+ call: string,
error?: boolean,
duration?: number,
argsText?: string,
@@ -221,9 +234,18 @@ export const buildVerboseToolTrailLine = (
const took = duration !== undefined ? ` (${duration.toFixed(1)}s)` : ''
- return `${formatToolCall(name, context)}${took}${detail ? ` :: ${detail}` : ''} ${error ? '✗' : '✓'}`
+ return `${call}${took}${detail ? ` :: ${detail}` : ''} ${error ? '✗' : '✓'}`
}
+export const buildVerboseToolTrailLine = (
+ name: string,
+ context: string,
+ error?: boolean,
+ duration?: number,
+ argsText?: string,
+ resultText?: string
+) => verboseToolTrailLine(formatToolCall(name, context), error, duration, argsText, resultText)
+
export const isToolTrailResultLine = (line: string) => line.endsWith(' ✓') || line.endsWith(' ✗')
export const parseToolTrailResultLine = (line: string) => {
diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts
index 5e4f42807b9..b44ea9ed834 100644
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@ -1,8 +1,9 @@
-import type { ProjectInfo, SessionLiveInfo, SubagentStatus } from '@hermes/shared/gateway-events'
+import type { ProjectInfo, SessionLiveInfo, SubagentStatus, ToolLabel } from '@hermes/shared/gateway-events'
export interface ActiveTool {
context?: string
id: string
+ labels?: ToolLabel[]
name: string
verboseArgs?: string
startedAt?: number
diff --git a/website/docs/user-guide/features/tool-search.md b/website/docs/user-guide/features/tool-search.md
index 37de8c1ca0b..9bec47d2988 100644
--- a/website/docs/user-guide/features/tool-search.md
+++ b/website/docs/user-guide/features/tool-search.md
@@ -192,6 +192,12 @@ local MCP servers from the catalog (targets with `mcp: true`), so it is
present whether or not you are signed in; only the managed-connector actions
need the sign-in.
+The desktop backend's account-list and disconnect APIs use the Portal's
+account-management service, including its organization membership checks and
+disconnect audit. An unavailable Portal does not fall back to direct gateway
+account management. Tool discovery, execution, and connection-status watching
+continue through the gateway; the model tool cannot disconnect an account.
+
`tool_call` accepts a batch: `calls` is an array of `{name, arguments}`
entries (a single call is an array of one). Each connector entry in a batch
is dispatched as its own gateway request, one after another; local deferred